Database queries cannot be enabled through the API, and use bounded memory

The config update API refuses to change `allow_database_query`; only an edit of
wrolpi.yaml on the WROLPi can enable queries.  Query connections refuse values
over 32 MB and rows over 100 columns, rows are read one at a time, and the
response stops at 5 million characters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-10-11 17:01:14 -06:00
parent 4e3fb68373
commit 468a7a4d12
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
3 changed files with 68 additions and 4 deletions

View file

@ -10,6 +10,12 @@ from wrolpi.errors import InvalidConfig
config_bp = Blueprint('config', '/api/config')
# Settings which can only be changed by editing the config file on the WROLPi. The API has no login, so anyone who
# can reach it must not be able to grant themselves more access.
FILE_ONLY_SETTINGS = {
'wrolpi.yaml': {'allow_database_query'},
}
@config_bp.get('/')
@openapi.description('Get the status (imported, valid, etc.) of all configs.')
@ -36,6 +42,11 @@ def get_config(request: Request):
def post_config_update(request: Request, body: config_schema.ConfigUpdateRequest):
file_name, = request.args['file_name']
config = get_config_by_file_name(file_name)
# The Configs page sends the whole config back, so only a change is refused.
changed = {k for k in FILE_ONLY_SETTINGS.get(file_name, set()) & set(body.config)
if body.config[k] != config.dict().get(k)}
if changed:
raise InvalidConfig(f'{", ".join(sorted(changed))} can only be changed by editing {file_name}')
config.update(body.config)
return response.empty()

View file

@ -9,7 +9,9 @@ A query can never change the database:
A query cannot monopolize the device:
* A progress handler interrupts it after `QUERY_TIMEOUT` seconds (this also bounds how long it pins a
WAL snapshot).
* Rows are capped at `MAX_LIMIT`, and long values are cut to `MAX_CELL_LENGTH`.
* SQLite refuses to build a value longer than `MAX_VALUE_LENGTH`, or a row wider than `MAX_COLUMNS`.
* Rows are read one at a time; long values are cut to `MAX_CELL_LENGTH`, and rows stop at `MAX_LIMIT` or once
the response holds `MAX_RESPONSE_LENGTH` characters.
"""
import asyncio
import contextlib
@ -35,6 +37,10 @@ logger = logger.getChild(__name__)
DEFAULT_LIMIT = 500
MAX_LIMIT = 5000
MAX_CELL_LENGTH = 10_000
MAX_RESPONSE_LENGTH = 5_000_000
# Larger than any value WROLPi stores (a document's text), far smaller than SQLite's 1 GB default.
MAX_VALUE_LENGTH = 32 * 1024 * 1024
MAX_COLUMNS = 100
QUERY_TIMEOUT = 10.0
# How many SQLite VM instructions run between timeout checks.
PROGRESS_INTERVAL = 10_000
@ -79,6 +85,8 @@ def read_only_connection(timeout: float = QUERY_TIMEOUT):
deadline = time.monotonic() + timeout
conn.set_progress_handler(lambda: int(time.monotonic() > deadline), PROGRESS_INTERVAL)
conn.set_authorizer(_authorizer)
conn.setlimit(sqlite3.SQLITE_LIMIT_LENGTH, MAX_VALUE_LENGTH)
conn.setlimit(sqlite3.SQLITE_LIMIT_COLUMN, MAX_COLUMNS)
yield conn
finally:
conn.close()
@ -92,12 +100,18 @@ def _cell(value):
return value
def _cell_length(value) -> int:
return len(value) if isinstance(value, str) else 8
def _raise_query_error(e: sqlite3.Error):
message = str(e)
if isinstance(e, sqlite3.OperationalError) and message == 'interrupted':
message = f'Query exceeded the {QUERY_TIMEOUT:g} second time limit'
elif 'not authorized' in message:
message = 'Only read-only queries (SELECT) are allowed'
elif 'too big' in message:
message = f'A value is too large (over {MAX_VALUE_LENGTH} bytes)'
raise InvalidDatabaseQuery(message) from e
@ -108,19 +122,25 @@ def run_query(sql: str, limit: int = DEFAULT_LIMIT) -> dict:
limit = max(1, min(int(limit or DEFAULT_LIMIT), MAX_LIMIT))
start = time.monotonic()
rows, truncated, response_length = [], False, 0
with read_only_connection() as conn:
try:
curs = conn.execute(sql)
columns = [i[0] for i in curs.description or []]
rows = curs.fetchmany(limit + 1)
# One row at a time, so only the kept (truncated) values are held.
for row in curs:
if len(rows) >= limit or response_length >= MAX_RESPONSE_LENGTH:
truncated = True
break
row = [_cell(i) for i in row]
response_length += sum(_cell_length(i) for i in row)
rows.append(row)
except sqlite3.Error as e:
_raise_query_error(e)
except sqlite3.Warning as e:
# Python refuses more than one statement.
raise InvalidDatabaseQuery(str(e)) from e
truncated = len(rows) > limit
rows = [[_cell(i) for i in row] for row in rows[:limit]]
return dict(
columns=columns,
rows=rows,

View file

@ -189,3 +189,36 @@ async def test_database_schema(test_session, async_client, allow_database_query)
assert f'{table["name"]}_data' not in tables
assert not any(name.startswith('sqlite_') for name in tables)
assert get_db_file().is_file()
@pytest.mark.asyncio
async def test_database_query_cannot_be_enabled_by_api(test_session, async_client, test_wrolpi_config):
"""The config update API refuses to enable queries; only an edit of wrolpi.yaml on the WROLPi can."""
body = dict(config=dict(allow_database_query=True))
request, response = await async_client.post('/api/config?file_name=wrolpi.yaml', content=json.dumps(body))
assert response.status_code == HTTPStatus.BAD_REQUEST
assert get_wrolpi_config().allow_database_query is False
request, response = await post_query(async_client, 'SELECT 1')
assert response.status_code == HTTPStatus.FORBIDDEN
@pytest.mark.asyncio
async def test_database_query_memory_limits(test_session, async_client, allow_database_query):
"""A query cannot build huge values or rows, and the response is bounded however many rows are asked for."""
request, response = await post_query(async_client, f'SELECT zeroblob({db_query.MAX_VALUE_LENGTH + 1})')
assert response.status_code == HTTPStatus.BAD_REQUEST
assert 'too large' in response.json['error']
columns = ', '.join(['1'] * (db_query.MAX_COLUMNS + 1))
request, response = await post_query(async_client, f'SELECT {columns}')
assert response.status_code == HTTPStatus.BAD_REQUEST
# Every row is a full-size cell; rows stop once the response budget is spent.
sql = (f"WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM n WHERE x < 100)"
f" SELECT printf('%.*c', {db_query.MAX_CELL_LENGTH}, 'a') FROM n")
with mock.patch.object(db_query, 'MAX_RESPONSE_LENGTH', db_query.MAX_CELL_LENGTH * 3):
request, response = await post_query(async_client, sql, limit=100)
assert response.status_code == HTTPStatus.OK, response.json
assert response.json['row_count'] == 3
assert response.json['truncated'] is True