Skip to content

Commit be09e1e

Browse files
committed
SQL: Stronger read-only mode, using sqlparse
1 parent 4f122fd commit be09e1e

File tree

11 files changed

+274
-13
lines changed

11 files changed

+274
-13
lines changed

CHANGES.md

+1
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,4 @@
1414
- MCP docs: Used Hishel for transparently caching documentation resources,
1515
by default for one hour. Use the `CRATEDB_MCP_DOCS_CACHE_TTL` environment
1616
variable to adjust (default: 3600)
17+
- SQL: Stronger read-only mode, using `sqlparse`

README.md

+6-4
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,12 @@ LLMs can still hallucinate and give incorrect answers.
4040
* What is the storage consumption of my tables, give it in a graph.
4141
* How can I format a timestamp column to '2019 Jan 21'.
4242

43-
# Data integrity
44-
We do not recommend letting the LLMs insert data or modify columns by itself, as such we tell the
45-
LLMs to only allow 'SELECT' statements in the `cratedb_sql` tool, you can jailbreak this against
46-
our recommendation.
43+
# Read-only access
44+
We do not recommend letting LLM-based agents insert or modify data by itself.
45+
As such, only `SELECT` statements are permitted and forwarded to the database.
46+
All other operations will raise a `ValueError` exception, unless the
47+
`CRATEDB_MCP_PERMIT_ALL_STATEMENTS` environment variable is set to a
48+
truthy value.
4749

4850
# Install
4951
```shell

cratedb_mcp/__main__.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from .knowledge import DOCUMENTATION_INDEX, Queries
66
from .settings import DOCS_CACHE_TTL, HTTP_URL
7+
from .util.sql import sql_is_permitted
78

89
# Configure Hishel, an httpx client with caching.
910
# Define one hour of caching time.
@@ -22,7 +23,7 @@ def query_cratedb(query: str) -> list[dict]:
2223
@mcp.tool(description="Send a SQL query to CrateDB, only 'SELECT' queries are allows, queries that"
2324
" modify data, columns or are otherwise deemed un-safe are rejected.")
2425
def query_sql(query: str):
25-
if 'select' not in query.lower():
26+
if not sql_is_permitted(query):
2627
raise ValueError('Only queries that have a SELECT statement are allowed.')
2728
return query_cratedb(query)
2829

cratedb_mcp/settings.py

+11
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import os
22
import warnings
33

4+
from attr.converters import to_bool
5+
46
HTTP_URL: str = os.getenv("CRATEDB_MCP_HTTP_URL", "http://localhost:4200")
57

68
# Configure cache lifetime for documentation resources.
@@ -12,3 +14,12 @@
1214
# TODO: Add software test after refactoring away from module scope.
1315
warnings.warn(f"Environment variable `CRATEDB_MCP_DOCS_CACHE_TTL` invalid: {e}. "
1416
f"Using default value: {DOCS_CACHE_TTL}.", category=UserWarning, stacklevel=2)
17+
18+
19+
# Whether to permit all statements. By default, only SELECT operations are permitted.
20+
PERMIT_ALL_STATEMENTS: bool = to_bool(os.getenv("CRATEDB_MCP_PERMIT_ALL_STATEMENTS", "false"))
21+
22+
# TODO: Refactor into code which is not on the module level. Use OOM early.
23+
if PERMIT_ALL_STATEMENTS: # pragma: no cover
24+
warnings.warn("All types of SQL statements are permitted. This means the LLM "
25+
"agent can write and modify the connected database", category=UserWarning, stacklevel=2)

cratedb_mcp/util/__init__.py

Whitespace-only changes.

cratedb_mcp/util/sql.py

+132
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
import dataclasses
2+
import logging
3+
import typing as t
4+
5+
import sqlparse
6+
7+
from cratedb_mcp.settings import PERMIT_ALL_STATEMENTS
8+
9+
logger = logging.getLogger(__name__)
10+
11+
12+
def sql_is_permitted(expression: str) -> bool:
13+
"""
14+
Validate the SQL expression, only permit read queries by default.
15+
16+
When the `CRATEDB_MCP_PERMIT_ALL_STATEMENTS` environment variable is set,
17+
allow all types of statements.
18+
19+
FIXME: Revisit implementation, it might be too naive or weak.
20+
Issue: https://github.com/crate/cratedb-mcp/issues/10
21+
Question: Does SQLAlchemy provide a solid read-only mode, or any other library?
22+
"""
23+
is_dql = SqlStatementClassifier(expression=expression, permit_all=PERMIT_ALL_STATEMENTS).is_dql
24+
if is_dql is True:
25+
logger.info(f"Permitted SQL expression: {expression}")
26+
else:
27+
logger.warning(f"Denied SQL expression: {expression}")
28+
return is_dql
29+
30+
31+
@dataclasses.dataclass
32+
class SqlStatementClassifier:
33+
"""
34+
Helper to classify an SQL statement.
35+
36+
Here, most importantly: Provide the `is_dql` property that
37+
signals truthfulness for read-only SQL SELECT statements only.
38+
"""
39+
expression: str
40+
permit_all: bool = False
41+
42+
_parsed_sqlparse: t.Any = dataclasses.field(init=False, default=None)
43+
44+
def __post_init__(self) -> None:
45+
if self.expression:
46+
self.expression = self.expression.strip()
47+
48+
def parse_sqlparse(self):
49+
"""
50+
Parse expression using traditional `sqlparse` library.
51+
"""
52+
if self._parsed_sqlparse is None:
53+
self._parsed_sqlparse = sqlparse.parse(self.expression)
54+
return self._parsed_sqlparse
55+
56+
@property
57+
def is_dql(self) -> bool:
58+
"""
59+
Whether the statement is a DQL statement, which effectively invokes read-only operations only.
60+
"""
61+
62+
if not self.expression:
63+
return False
64+
65+
if self.permit_all:
66+
return True
67+
68+
# Parse the SQL statement using `cratedb-sqlparse`.
69+
parsed = self.parse_sqlparse()
70+
71+
# Reject multiple statements to prevent potential SQL injections.
72+
if len(parsed) > 1:
73+
return False
74+
75+
# Check if the expression is valid and if it's a DQL/SELECT statement,
76+
# also trying to consider `SELECT ... INTO ...` and evasive
77+
# `SELECT * FROM users; \uff1b DROP TABLE users` statements.
78+
return self.is_select and not self.is_camouflage
79+
80+
@property
81+
def is_select(self) -> bool:
82+
"""
83+
Whether the expression is an SQL SELECT statement.
84+
"""
85+
return self.operation == 'SELECT'
86+
87+
@property
88+
def operation(self) -> str:
89+
"""
90+
The SQL operation: SELECT, INSERT, UPDATE, DELETE, CREATE, etc.
91+
"""
92+
return self._parsed_sqlparse[0].get_type().upper()
93+
94+
@property
95+
def is_camouflage(self) -> bool:
96+
"""
97+
Innocent-looking `SELECT` statements can evade filters.
98+
"""
99+
return self.is_select_into or self.is_evasive
100+
101+
@property
102+
def is_select_into(self) -> bool:
103+
"""
104+
Use traditional `sqlparse` for catching `SELECT ... INTO ...` statements.
105+
106+
Note: With `cratedb-sqlparse`, we can't find the `INTO` token at all?
107+
108+
Examples:
109+
110+
SELECT * INTO foobar FROM bazqux
111+
SELECT * FROM bazqux INTO foobar
112+
"""
113+
parsed = self.parse_sqlparse()
114+
tokens = [str(token).upper() for token in parsed[0].tokens]
115+
return "INTO" in tokens
116+
117+
@property
118+
def is_evasive(self) -> bool:
119+
"""
120+
Use traditional `sqlparse` for catching evasive SQL statements.
121+
122+
A practice picked up from CodeRabbit was to reject multiple statements
123+
to prevent potential SQL injections. Is it a viable suggestion?
124+
125+
Note: This currently does not work with `cratedb-sqlparse`?
126+
127+
Examples:
128+
129+
SELECT * FROM users; \uff1b DROP TABLE users
130+
"""
131+
parsed = self.parse_sqlparse()
132+
return len(parsed) > 1

docs/backlog.md

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# CrateDB MCP backlog
2+
3+
## Iteration +1
4+
- Docs: HTTP caching
5+
- Docs: Load documentation index from custom outline file
6+
- SQL: Extract `SqlFilter` or `SqlGateway` functionality to `cratedb-sqlparse`
7+
8+
## Done
9+
- SQL: Stronger read-only mode

pyproject.toml

+2
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,10 @@ dynamic = [
2020
"version",
2121
]
2222
dependencies = [
23+
"attrs",
2324
"hishel<0.2",
2425
"mcp[cli]>=1.5.0",
26+
"sqlparse<0.6",
2527
]
2628
optional-dependencies.develop = [
2729
"mypy<1.16",

tests/test_knowledge.py

+2
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,5 @@ def test_queries():
1616
assert "sys.health" in Queries.TABLES_METADATA
1717
assert "WITH partitions_health" in Queries.TABLES_METADATA
1818
assert "LEFT JOIN" in Queries.TABLES_METADATA
19+
20+

tests/test_mcp.py

+9-8
Original file line numberDiff line numberDiff line change
@@ -24,19 +24,20 @@ def test_fetch_docs_permitted():
2424
assert "initcap" in response
2525

2626

27-
def test_query_sql_forbidden():
27+
def test_query_sql_permitted():
28+
assert query_sql("SELECT 42")["rows"] == [[42]]
29+
30+
31+
def test_query_sql_forbidden_easy():
2832
with pytest.raises(ValueError) as ex:
2933
assert "RelationUnknown" in str(query_sql("INSERT INTO foobar (id) VALUES (42) RETURNING id"))
3034
assert ex.match("Only queries that have a SELECT statement are allowed")
3135

3236

33-
def test_query_sql_permitted():
34-
assert query_sql("SELECT 42")["rows"] == [[42]]
35-
36-
37-
def test_query_sql_permitted_exploit():
38-
# FIXME: Read-only protection must become stronger.
39-
query_sql("INSERT INTO foobar (operation) VALUES ('select')")
37+
def test_query_sql_forbidden_sneak_value():
38+
with pytest.raises(ValueError) as ex:
39+
query_sql("INSERT INTO foobar (operation) VALUES ('select')")
40+
assert ex.match("Only queries that have a SELECT statement are allowed")
4041

4142

4243
def test_get_table_metadata():

tests/test_util.py

+100
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
import cratedb_mcp
2+
from cratedb_mcp.util.sql import sql_is_permitted
3+
4+
5+
def test_sql_select_permitted():
6+
"""Regular SQL SELECT statements are permitted"""
7+
assert sql_is_permitted("SELECT 42") is True
8+
assert sql_is_permitted(" SELECT 42") is True
9+
assert sql_is_permitted("select 42") is True
10+
11+
12+
def test_sql_select_rejected():
13+
"""Bogus SQL SELECT statements are rejected"""
14+
assert sql_is_permitted(r"--\; select 42") is False
15+
16+
17+
def test_sql_insert_allowed(mocker):
18+
"""When explicitly allowed, permit any kind of statement"""
19+
mocker.patch.object(cratedb_mcp.util.sql, "PERMIT_ALL_STATEMENTS", True)
20+
assert sql_is_permitted("INSERT INTO foobar") is True
21+
22+
23+
def test_sql_select_multiple_rejected():
24+
"""Multiple SQL statements are rejected"""
25+
assert sql_is_permitted("SELECT 42; SELECT 42;") is False
26+
27+
28+
def test_sql_create_rejected():
29+
"""DDL statements are rejected"""
30+
assert sql_is_permitted("CREATE TABLE foobar AS SELECT 42") is False
31+
32+
33+
def test_sql_insert_rejected():
34+
"""DML statements are rejected"""
35+
assert sql_is_permitted("INSERT INTO foobar") is False
36+
37+
38+
def test_sql_select_into_rejected():
39+
"""SELECT+DML statements are rejected"""
40+
assert sql_is_permitted("SELECT * INTO foobar FROM bazqux") is False
41+
assert sql_is_permitted("SELECT * FROM bazqux INTO foobar") is False
42+
43+
44+
def test_sql_empty_rejected():
45+
"""Empty statements are rejected"""
46+
assert sql_is_permitted("") is False
47+
48+
49+
def test_sql_almost_empty_rejected():
50+
"""Quasi-empty statements are rejected"""
51+
assert sql_is_permitted(" ") is False
52+
53+
54+
def test_sql_none_rejected():
55+
"""Void statements are rejected"""
56+
assert sql_is_permitted(None) is False
57+
58+
59+
def test_sql_multiple_statements_rejected():
60+
assert sql_is_permitted("SELECT 42; INSERT INTO foo VALUES (1)") is False
61+
62+
63+
def test_sql_with_comments_rejected():
64+
assert sql_is_permitted(
65+
"/* Sneaky comment */ INSERT /* another comment */ INTO foo VALUES (1)") is False
66+
67+
68+
def test_sql_update_rejected():
69+
"""UPDATE statements are rejected"""
70+
assert sql_is_permitted("UPDATE foobar SET column = 'value'") is False
71+
72+
73+
def test_sql_delete_rejected():
74+
"""DELETE statements are rejected"""
75+
assert sql_is_permitted("DELETE FROM foobar") is False
76+
77+
78+
def test_sql_truncate_rejected():
79+
"""TRUNCATE statements are rejected"""
80+
assert sql_is_permitted("TRUNCATE TABLE foobar") is False
81+
82+
83+
def test_sql_drop_rejected():
84+
"""DROP statements are rejected"""
85+
assert sql_is_permitted("DROP TABLE foobar") is False
86+
87+
88+
def test_sql_alter_rejected():
89+
"""ALTER statements are rejected"""
90+
assert sql_is_permitted("ALTER TABLE foobar ADD COLUMN newcol INTEGER") is False
91+
92+
93+
def test_sql_case_manipulation_rejected():
94+
"""Statements with case manipulation to hide intent are rejected"""
95+
assert sql_is_permitted("SeLeCt * FrOm users; DrOp TaBlE users") is False
96+
97+
98+
def test_sql_unicode_evasion_rejected():
99+
"""Statements with unicode characters to evade filters are rejected"""
100+
assert sql_is_permitted("SELECT * FROM users; \uFF1B DROP TABLE users") is False

0 commit comments

Comments
 (0)