From a34f17b327086f241c4921777dfe2bd77f8973bf Mon Sep 17 00:00:00 2001 From: jmmana <33883620+jmmana@users.noreply.github.com> Date: Fri, 4 Dec 2026 18:49:34 -0500 Subject: [PATCH 1/2] feat(vanna): add vanna-sqlguardllm package Guarded SqlRunner and RunSqlTool builder for Vanna 2.x, with SQLite tests. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/publish-vanna.yml | 71 +++++++++++ .github/workflows/vanna-package.yml | 36 ++++++ clients/vanna/README.md | 65 ++++++++++ clients/vanna/pyproject.toml | 47 +++++++ .../vanna/src/vanna_sqlguardllm/__init__.py | 20 +++ clients/vanna/src/vanna_sqlguardllm/runner.py | 83 ++++++++++++ clients/vanna/tests/test_runner.py | 120 ++++++++++++++++++ docs/INTEGRATIONS.md | 4 + 8 files changed, 446 insertions(+) create mode 100644 .github/workflows/publish-vanna.yml create mode 100644 .github/workflows/vanna-package.yml create mode 100644 clients/vanna/README.md create mode 100644 clients/vanna/pyproject.toml create mode 100644 clients/vanna/src/vanna_sqlguardllm/__init__.py create mode 100644 clients/vanna/src/vanna_sqlguardllm/runner.py create mode 100644 clients/vanna/tests/test_runner.py diff --git a/.github/workflows/publish-vanna.yml b/.github/workflows/publish-vanna.yml new file mode 100644 index 0000000..eb9c3a4 --- /dev/null +++ b/.github/workflows/publish-vanna.yml @@ -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 diff --git a/.github/workflows/vanna-package.yml b/.github/workflows/vanna-package.yml new file mode 100644 index 0000000..943fe37 --- /dev/null +++ b/.github/workflows/vanna-package.yml @@ -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 diff --git a/clients/vanna/README.md b/clients/vanna/README.md new file mode 100644 index 0000000..ba039c7 --- /dev/null +++ b/clients/vanna/README.md @@ -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. diff --git a/clients/vanna/pyproject.toml b/clients/vanna/pyproject.toml new file mode 100644 index 0000000..c33c291 --- /dev/null +++ b/clients/vanna/pyproject.toml @@ -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"] diff --git a/clients/vanna/src/vanna_sqlguardllm/__init__.py b/clients/vanna/src/vanna_sqlguardllm/__init__.py new file mode 100644 index 0000000..4e0aac0 --- /dev/null +++ b/clients/vanna/src/vanna_sqlguardllm/__init__.py @@ -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", +] diff --git a/clients/vanna/src/vanna_sqlguardllm/runner.py b/clients/vanna/src/vanna_sqlguardllm/runner.py new file mode 100644 index 0000000..3f05fa9 --- /dev/null +++ b/clients/vanna/src/vanna_sqlguardllm/runner.py @@ -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: "`` 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.}`` from the Vanna user. + + The values come from the ``User`` your ``UserResolver`` authenticated (its ``metadata``), + never from the model. + """ + return {"user": {"id": context.user.id, **context.user.metadata}} + + +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, + ) diff --git a/clients/vanna/tests/test_runner.py b/clients/vanna/tests/test_runner.py new file mode 100644 index 0000000..c31f966 --- /dev/null +++ b/clients/vanna/tests/test_runner.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +import asyncio +import sqlite3 +from pathlib import Path +from typing import Any + +import pytest + +pytest.importorskip("vanna") + +from sqlguardllm import Guard, Policy +from vanna import ToolCall, ToolContext, ToolRegistry, User +from vanna.capabilities.sql_runner import RunSqlToolArgs, SqlRunner +from vanna.integrations.local import LocalFileSystem +from vanna.integrations.local.agent_memory import DemoAgentMemory +from vanna.integrations.sqlite import SqliteRunner + +from vanna_sqlguardllm import GuardedSqlRunner, SqlGuardRefusal, 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, +) +SECRET = "ana@example.com" + + +class Recorder(SqlRunner): + """Wraps a runner and remembers the SQL it was asked to run.""" + + def __init__(self, inner: SqlRunner) -> None: + self.inner = inner + self.seen: list[str] = [] + + async def run_sql(self, args: RunSqlToolArgs, context: ToolContext) -> Any: + self.seen.append(args.sql) + return await self.inner.run_sql(args, context) + + +def make_context() -> ToolContext: + user = User(id="ana", group_memberships=["user"], metadata={"branches": [1, 2]}) + return ToolContext( + user=user, conversation_id="c", request_id="r", agent_memory=DemoAgentMemory() + ) + + +@pytest.fixture() +def db_path(tmp_path: Path) -> Path: + path = tmp_path / "sales.db" + conn = sqlite3.connect(path) + conn.executescript( + f""" + CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, email TEXT); + CREATE TABLE invoices (id INTEGER PRIMARY KEY, branch_id INTEGER, total REAL); + INSERT INTO customers VALUES (1, 'Ana', '{SECRET}'); + INSERT INTO invoices VALUES (10, 1, 100.0), (11, 2, 250.0), (12, 3, 900.0); + """ + ) + conn.commit() + conn.close() + return path + + +@pytest.fixture() +def recorder(db_path: Path) -> Recorder: + return Recorder(SqliteRunner(database_path=str(db_path))) + + +def call_tool(recorder: Recorder, tmp_path: Path, sql: str) -> Any: + tool = guarded_run_sql_tool( + recorder, Guard(POLICY), file_system=LocalFileSystem(str(tmp_path / "out")) + ) + registry = ToolRegistry() + registry.register_local_tool(tool, access_groups=["user"]) + call = ToolCall(id="1", name="run_sql", arguments={"sql": sql}) + return asyncio.run(registry.execute(call, make_context())) + + +def test_allowed_query_is_rewritten_with_filter_and_limit( + recorder: Recorder, tmp_path: Path +) -> None: + result = call_tool(recorder, tmp_path, "SELECT id FROM invoices ORDER BY id") + assert result.success + assert "10" in result.result_for_llm and "11" in result.result_for_llm + assert "12" not in result.result_for_llm + (executed,) = recorder.seen + assert "branch_id IN (1, 2)" in executed + assert "LIMIT 100" in executed.upper() + + +def test_write_hidden_in_cte_is_refused(recorder: Recorder, tmp_path: Path) -> None: + sql = "WITH gone AS (DELETE FROM invoices RETURNING id) SELECT id FROM gone" + result = call_tool(recorder, tmp_path, sql) + assert not result.success + assert "write_operation" in result.result_for_llm + assert recorder.seen == [] + + +def test_hidden_column_is_refused_and_message_reaches_the_agent( + recorder: Recorder, tmp_path: Path +) -> None: + result = call_tool(recorder, tmp_path, "SELECT name, email FROM customers") + assert not result.success + assert result.result_for_llm.startswith("Error executing query: Refused by the SQL firewall") + assert "hidden_column" in result.result_for_llm + assert "customers.email is a hidden column" in result.result_for_llm + assert "Rewrite the query" in result.result_for_llm + assert SECRET not in result.result_for_llm + assert recorder.seen == [] + + +def test_runner_raises_refusal_with_codes(recorder: Recorder) -> None: + runner = GuardedSqlRunner(recorder, Guard(POLICY)) + with pytest.raises(SqlGuardRefusal) as info: + asyncio.run(runner.run_sql(RunSqlToolArgs(sql="DROP TABLE invoices"), make_context())) + assert info.value.codes + assert recorder.seen == [] diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.md index 4ca1032..fc41451 100644 --- a/docs/INTEGRATIONS.md +++ b/docs/INTEGRATIONS.md @@ -46,3 +46,7 @@ Runnable code for each stack, tested in CI with fake model output, is in **[RECI | [ChatIApp](https://github.com/jmmana/ChatIApp) | Uses sqlguardllm as its SQL guard; policies come from its semantic model | Using sqlguardllm somewhere else? Open a PR to add your recipe. + +## Vanna package + +For Vanna 2.x there is a ready-made package, [`vanna-sqlguardllm`](../clients/vanna/README.md): `guarded_run_sql_tool(runner, guard)` returns Vanna's `RunSqlTool` on top of a `GuardedSqlRunner`. It builds the guard context from the authenticated Vanna user, runs only the rewritten SQL and returns refusals (with violation codes) to the model as a failed tool result. From b0378f461f385b9b143163321d10c14388713321 Mon Sep 17 00:00:00 2001 From: jmmana <33883620+jmmana@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:03:48 -0500 Subject: [PATCH 2/2] vanna: authenticated user id always wins over metadata Co-Authored-By: Claude Opus 5.5 --- clients/vanna/src/vanna_sqlguardllm/runner.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clients/vanna/src/vanna_sqlguardllm/runner.py b/clients/vanna/src/vanna_sqlguardllm/runner.py index 3f05fa9..609a14b 100644 --- a/clients/vanna/src/vanna_sqlguardllm/runner.py +++ b/clients/vanna/src/vanna_sqlguardllm/runner.py @@ -33,9 +33,9 @@ def user_context(context: ToolContext) -> Mapping[str, Any]: """Default trusted context: ``{user.id}`` and ``{user.}`` from the Vanna user. The values come from the ``User`` your ``UserResolver`` authenticated (its ``metadata``), - never from the model. + never from the model. The authenticated ``id`` always wins over a ``metadata["id"]``. """ - return {"user": {"id": context.user.id, **context.user.metadata}} + return {"user": {**context.user.metadata, "id": context.user.id}} class GuardedSqlRunner(SqlRunner):