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
71 changes: 71 additions & 0 deletions .github/workflows/publish-vanna.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
name: Publish vanna-sqlguardllm

# Publishes the vanna-sqlguardllm package (clients/vanna) to PyPI with Trusted Publishing
# (OIDC): no token is stored. It is separate from release.yml on purpose: this package has its own
# version and release cadence. Run it by hand from main with the exact version.
#
# One-time setup, on PyPI (https://pypi.org/manage/account/publishing/), a pending publisher:
# project vanna-sqlguardllm
# owner jmmana repository sqlguardllm
# workflow publish-vanna.yml environment pypi-vanna
# and create the environment `pypi-vanna` in the repository settings.
on:
workflow_dispatch:
inputs:
version:
description: Exact version of clients/vanna on main (for example 0.1.0a1)
required: true
type: string

permissions:
contents: read

concurrency:
group: publish-vanna
cancel-in-progress: false

jobs:
build:
name: Build and verify
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5
- name: The requested version is the one in the package
env:
REQUESTED_VERSION: ${{ inputs.version }}
run: |
actual=$(grep -m1 '^version = ' clients/vanna/pyproject.toml | cut -d'"' -f2)
if [ "$actual" != "$REQUESTED_VERSION" ]; then
echo "clients/vanna is $actual, not $REQUESTED_VERSION" >&2
exit 1
fi
- name: Tests against the current Vanna
run: uv run --with "./clients/vanna[test]" --with pytest pytest clients/vanna/tests -q
- run: uv build clients/vanna --out-dir dist
- name: Smoke-test wheel with runtime dependencies only
run: |
wheel=$(find dist -maxdepth 1 -name 'vanna_sqlguardllm-*.whl')
test -n "$wheel"
uv run --isolated --no-project --with "./$wheel" python -c 'import vanna_sqlguardllm'
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: dist
path: dist/

pypi:
name: Publish to PyPI
needs: build
runs-on: ubuntu-latest
environment:
name: pypi-vanna
url: https://pypi.org/project/vanna-sqlguardllm/
permissions:
id-token: write
steps:
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: dist
path: dist/
- uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # release/v1
36 changes: 36 additions & 0 deletions .github/workflows/vanna-package.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
name: vanna-sqlguardllm

on:
pull_request:
paths:
- "clients/vanna/**"
- ".github/workflows/vanna-package.yml"
workflow_dispatch:
schedule:
- cron: "0 6 * * 1"

permissions:
contents: read

jobs:
package:
name: Build, test and lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5
with:
python-version: "3.12"
- name: Build
run: uv build clients/vanna --out-dir dist
- name: Smoke-test wheel with runtime dependencies only
run: |
wheel=$(find dist -maxdepth 1 -name 'vanna_sqlguardllm-*.whl')
test -n "$wheel"
uv run --isolated --no-project --with "./$wheel" python -c 'import vanna_sqlguardllm'
- name: Tests
run: >
uv run --with "./clients/vanna[test]" --with pytest
pytest clients/vanna/tests -q
- name: Lint
run: uvx ruff check clients/vanna
65 changes: 65 additions & 0 deletions clients/vanna/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# vanna-sqlguardllm

A guarded SQL runner and `run_sql` tool for [Vanna](https://vanna.ai) 2.x agents, built on
[sqlguardllm](https://github.com/jmmana/sqlguardllm), a deterministic SQL firewall: the model
writes SQL, sqlguardllm checks and rewrites it against your policy, and only then does it run.

**Status: alpha.** Targets Vanna 2.0.x (`vanna>=2.0,<3`); the Vanna 0.x `VannaBase.run_sql`
API is not supported.

```bash
pip install --pre vanna-sqlguardllm
```

## Quick start

```python
from sqlguardllm import Guard, Policy
from vanna import ToolRegistry
from vanna.integrations.sqlite import SqliteRunner
from vanna_sqlguardllm import guarded_run_sql_tool

policy = Policy(
dialect="sqlite",
tables={"customers", "invoices"},
hidden_columns={"customers.email"},
row_filters={"invoices": "branch_id IN ({user.branches})"},
max_rows=100,
)

tools = ToolRegistry()
tools.register_local_tool(
guarded_run_sql_tool(SqliteRunner(database_path="sales.db"), Guard(policy)),
access_groups=["user"],
)
```

`guarded_run_sql_tool` returns Vanna's own `RunSqlTool`. To build the tool yourself, wrap any
runner: `RunSqlTool(sql_runner=GuardedSqlRunner(runner, guard))`.

## Trusted context

Row-filter placeholders such as `{user.branches}` are filled from the context, which comes from
the application, never from the model. By default `user_context` uses the authenticated Vanna
user: `{user.id}` and every key of `User.metadata` (set by your `UserResolver`). Pass your own
`context_fn(tool_context) -> Mapping` as the third argument to change it.

## What the model sees

Only the rewritten SQL runs. A rejected query is returned as a failed tool result the model can
repair, for example:

```
Error executing query: Refused by the SQL firewall [hidden_column]: customers.email is a hidden
column. Rewrite the query and try again.
```

## Safety notes

- Keep the layers under the guard: connect with a **read-only database user** and set a
statement timeout.
- The **context comes from the authenticated session**, never from the model.
- Vanna's other tools (visualization, Python, memory) are outside this package; register only
the tools you trust.

More at https://github.com/jmmana/sqlguardllm.
47 changes: 47 additions & 0 deletions clients/vanna/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "vanna-sqlguardllm"
version = "0.1.0a1"
description = "A Vanna 2.x SQL runner and run_sql tool that only run SQL made safe by sqlguardllm."
readme = "README.md"
license = "Apache-2.0"
requires-python = ">=3.10"
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Topic :: Database",
"Topic :: Security",
"Typing :: Typed",
]
dependencies = [
"sqlguardllm>=0.5.0a8",
"vanna>=2.0,<3",
]

[project.optional-dependencies]
test = [
"pytest>=8",
]

[project.urls]
Homepage = "https://github.com/jmmana/sqlguardllm"
Repository = "https://github.com/jmmana/sqlguardllm"
Issues = "https://github.com/jmmana/sqlguardllm/issues"

[tool.hatch.build.targets.wheel]
packages = ["src/vanna_sqlguardllm"]

[tool.ruff]
line-length = 100

[tool.pytest.ini_options]
testpaths = ["tests"]
20 changes: 20 additions & 0 deletions clients/vanna/src/vanna_sqlguardllm/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""Vanna 2.x integration for sqlguardllm: a guarded SQL runner and run_sql tool."""

from __future__ import annotations

from vanna_sqlguardllm.runner import (
GuardedSqlRunner,
SqlGuardRefusal,
guarded_run_sql_tool,
user_context,
)

__version__ = "0.1.0a1"

__all__ = [
"GuardedSqlRunner",
"SqlGuardRefusal",
"__version__",
"guarded_run_sql_tool",
"user_context",
]
83 changes: 83 additions & 0 deletions clients/vanna/src/vanna_sqlguardllm/runner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
"""A Vanna ``SqlRunner`` that only executes SQL sqlguardllm has made safe."""

from __future__ import annotations

from collections.abc import Callable, Mapping
from typing import Any

import pandas as pd
from sqlguardllm import Guard
from vanna.capabilities.file_system import FileSystem
from vanna.capabilities.sql_runner import RunSqlToolArgs, SqlRunner
from vanna.core.tool import ToolContext
from vanna.tools import RunSqlTool


class SqlGuardRefusal(Exception):
"""The guard rejected the query. The message lists the violation codes and reasons.

``RunSqlTool`` returns it to the model as ``"Error executing query: <message>"`` with
``success=False``, so the model can rewrite the query.
"""

def __init__(self, codes: list[str], reasons: list[str]) -> None:
self.codes = codes
self.reasons = reasons
super().__init__(
"Refused by the SQL firewall "
f"[{', '.join(codes)}]: {'; '.join(reasons)}. Rewrite the query and try again."
)


def user_context(context: ToolContext) -> Mapping[str, Any]:
"""Default trusted context: ``{user.id}`` and ``{user.<key>}`` from the Vanna user.

The values come from the ``User`` your ``UserResolver`` authenticated (its ``metadata``),
never from the model. The authenticated ``id`` always wins over a ``metadata["id"]``.
"""
return {"user": {**context.user.metadata, "id": context.user.id}}


class GuardedSqlRunner(SqlRunner):
"""Checks every query with ``guard`` and hands only the rewritten SQL to ``runner``.

A drop-in replacement for any Vanna ``SqlRunner``: wrap yours and pass it to ``RunSqlTool``.
``context_fn`` builds the guard context from the tool context (the authenticated user).
"""

def __init__(
self,
runner: SqlRunner,
guard: Guard,
context_fn: Callable[[ToolContext], Mapping[str, Any]] = user_context,
) -> None:
self.runner = runner
self.guard = guard
self.context_fn = context_fn

async def run_sql(self, args: RunSqlToolArgs, context: ToolContext) -> pd.DataFrame:
result = self.guard.check(args.sql, self.context_fn(context))
if not result.ok or result.sql is None:
raise SqlGuardRefusal(
[v.code.value for v in result.violations],
[v.message for v in result.violations],
)
return await self.runner.run_sql(RunSqlToolArgs(sql=result.sql), context)


def guarded_run_sql_tool(
runner: SqlRunner,
guard: Guard,
context_fn: Callable[[ToolContext], Mapping[str, Any]] = user_context,
*,
file_system: FileSystem | None = None,
custom_tool_name: str | None = None,
custom_tool_description: str | None = None,
) -> RunSqlTool:
"""Build Vanna's own ``RunSqlTool`` on top of a ``GuardedSqlRunner``."""
return RunSqlTool(
sql_runner=GuardedSqlRunner(runner, guard, context_fn),
file_system=file_system,
custom_tool_name=custom_tool_name,
custom_tool_description=custom_tool_description,
)
Loading
Loading