Skip to content

Guarding queries

Running SQL that came from somewhere you do not control - a language model, a user, another service - against a database that has real data in it.

In quackjvm-agent

This page is part of the quackjvm-agent module, not core: add io.github.bdarwin:quackjvm-agent beside quackjvm-core. GuardedQuery.on(quack, policy) borrows a connection per query, and Hardening.openSandbox() opens a hardened Quack.

GuardedQuery guard = GuardedQuery.on(connection, QueryPolicy.readOnly());
GuardedResult result = guard.run(whateverTheAgentWrote);
System.out.println(result.toText());

Four things stand between the statement and the database: what it is, how long it may run, how much it may return, and - if you turn it on - what it can reach.

What it is: DuckDB's parser decides

The check is json_serialize_sql, which parses the text and hands back its syntax tree. DuckDB serializes only queries, so everything else comes back as an error and is refused:

allowed refused
SELECT, WITH, FROM-first, TABLE, VALUES INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, TRUNCATE
DESCRIBE, SUMMARIZE, UNPIVOT ATTACH, COPY, INSTALL, LOAD, EXPORT
EXPLAIN, EXPLAIN ANALYZE of an allowed query SET, PRAGMA, CALL, BEGIN, PREPARE, CREATE MACRO

A CTE with a write inside it - WITH x AS (DELETE ... RETURNING *) SELECT * FROM x - is refused too, by the parser, not by us. The statements come back as an array, so more than one statement is a count, not a hunt for semicolons: SELECT 'a;b', $$c;d$$, -- comments and /* nested /* ones */ */ are the parser's problem rather than ours.

Why it never prepares the statement to find out

With duckdb_jdbc 1.5.5, and still with 2.0.0, preparing a multi-statement string executes all but the last statement:

connection.prepareStatement("DROP TABLE secrets; SELECT 1");   // never executed
// secrets is gone

That is measured, in AgentGuardedQueries, and it is why a guard that validates by preparing has already lost. Nothing here prepares a statement until the parser has said it is a single query.

PIVOT, which cannot be checked

DuckDB refuses to serialize PIVOT as well - even wrapped in a subquery - so the parser cannot tell a pivot apart from a statement that writes. It is refused by default, and the message says so. If you need it:

QueryPolicy.readOnly().allowUnverified(QueryPolicy.PIVOT);

What that gives up: the parser is no longer what decides. The statement is recognised by its leading keyword, and a small scanner - one that knows quotes, dollar-quoting and nested comments - stands in for the parser's promise that there is only one statement. The caps and the timeout still apply. Nothing else can be allowed this way; allowUnverified("INSERT") throws.

How long, and how much

QueryPolicy.readOnly()
        .timeout(Duration.ofSeconds(2))
        .maxRows(50)
        .maxBytes(1 << 20);
  • Timeout cancels the statement through Statement.cancel() from a daemon scheduler. DuckDB stops mid-scan and the connection stays usable - measured at 310 ms to cancel a query that would have run for minutes.
  • maxRows becomes a LIMIT around the statement, so the rows are never built: a SELECT range FROM range(2000000000) with a five-row cap comes back in milliseconds. A query that would exceed the cap is refused, not quietly cut short - a truncated answer read as a whole one is worse than no answer. If the statement cannot be wrapped, the cap is applied as the rows arrive instead.
  • maxBytes is counted as the values are read, and is an estimate: two bytes a character, eight for a number, the length of a blob.

The first rows, said to be the first

Refusing is the right answer for an agent that would read a partial answer as a whole one. A person paging through a large result wants its first rows instead:

GuardedQuery firstRows = GuardedQuery.on(quack, QueryPolicy.readOnly()
        .maxRows(100)
        .whenOver(QueryPolicy.Over.TRUNCATE));

GuardedResult page = firstRows.run("SELECT * FROM events ORDER BY at");
page.getRows();        // at most 100
page.isTruncated();    // true when there were more

The row cap is still the LIMIT around the statement, one row over, so the extra row is what says there were more - range(1000) with a cap of 50 gives 50 rows and isTruncated(), range(50) gives 50 and not. The byte cap cuts short the same way, before the row that would cross it. Refusing stays the default.

Stopping it from outside

The timeout stops a query nobody is watching. A Stop button, or a caller that was itself cancelled, needs to stop it now:

CancelSignal stop = new CancelSignal();
executor.submit(() -> guard.run(sql, stop));
...
stop.cancel();         // the run throws QueryCancelled

It is the same Statement.cancel() the timeout uses, so the connection stays usable; tested on a query that would run for minutes, stopped within two seconds of the cancel. QueryCancelled is not a QueryTimedOut: no limit was reached. A signal cancelled before the run starts stops it before anything runs, and one cancelled after it finished changes nothing.

An application often has a flag already, such as a button's state or an abandoned call. In that case it can hand over the flag:

guard.run(sql, CancelSignal.from(stop::get));                          // asked every 50 ms
guard.run(sql, CancelSignal.polling(stop::get, Duration.ofMillis(5)));  // or as often as you like
  • A flag that is already set stops the run before the query is even parsed.
  • While the query runs, one daemon thread polls the flag. Measured: the query stopped 0–59 ms after the flag turned, median 31 ms.
  • A supplier that throws counts as "not stopped".

What it can reach: hardening

Hardening.DATABASE takes away the database's access to files, extensions and the network, so a statement that somehow got past the check still cannot reach anything:

QueryPolicy.readOnly().hardening(Hardening.DATABASE);

Read this before turning it on. In DuckDB this is a property of the database, not of a connection, and it cannot be undone while the database runs - "Cannot enable external access while database is running". Every connection to that database loses file access at once, including yours: MeasureTable.archive, MeasureHistory.export, read_parquet and every Parquet restore stop working. That is why it is off by default.

The sandbox, which costs nothing

try (Connection sandbox = Hardening.sandbox()) {
    // register live Java data on it, or copy snapshots in
    GuardedQuery.on(sandbox, QueryPolicy.readOnly()).run(sql);
}

A second, empty database opened with external access off and the configuration locked. A hardened database can still see live Java objects through a registered table function, and can hold tables copied into it - both measured - so an agent gets a database with no way out while the database your application writes to keeps everything it had.

Locked down, with folders of its own

All or nothing is too little for SQL people write over their own files. Hardening.options() locks everything else - no network, no other folder, no extension, no SET - and lets in the folders named:

Hardening.Options options = Hardening.options()
        .allowedFolders(logFolder, home)
        .tempFolder(temp)
        .memoryLimit("4GB")
        .threads(7);

Quack db = Quack.builder(path).settings(options.properties()).open();   // starts that way
Hardening.apply(otherDb, options);                                       // or, once open

.allowedFiles(...) lets single files in, rather than their folders: DuckDB's allowed_paths. A query session uses it for a file table's cache.

On a database already open, apply sets them in the order DuckDB needs - the folders before external access goes, everything before the configuration is locked - and leaves a database whose configuration is locked already as it is.

Measured on duckdb_jdbc 1.5.5.1 and 2.0.0.0, with a folder allowed:

  • Its files, and those of the folders below it, are read. A file in any other folder, a neighbour whose name starts the same (/logs2 when /logs is allowed), a way out through .., a URL, INSTALL and SET are all refused.
  • An allowed folder can be written as well as read. DuckDB has no read-only form of it: COPY ... TO and ATTACH of a file there both work. GuardedQuery refuses both statements, so SQL that goes through it only reads; SQL run on the database directly can write there.
  • SQL can read and write in the temp folder, as if it were an allowed one. DuckDB spills into it without it being listed (sorting 8 million rows under a 200 MB limit spilled 375 MB into it), but it also lets read_csv, glob, COPY ... TO and ATTACH reach it and the folders below it, measured on 2.0.0.0. So give it a folder of its own, never a shared one such as the system's temp folder: properties() and Hardening.apply refuse a temp folder that holds anything but DuckDB's own duckdb_temp files. GuardedQuery refuses COPY and ATTACH, so through it SQL can only read there.
  • One JVM opening the same file twice shares one database. With the same options that is fine; with different ones the driver refuses - "Can't open a connection to same database file with a different configuration" - so the second open never meets a lock it did not expect.

What it costs

Measured on 200,000 rows, this machine, DuckDB 2.0.0:

the check alone, nothing run 0.61 ms
a grouped aggregate, guarded 3.58 ms
the same, unguarded 2.06 ms

One parse of the statement, and one of the wrapped form that carries the row cap - about one and a half milliseconds on DuckDB 2.0, whatever the query costs afterwards. On 1.5.5 the check alone was 0.23 ms and the guarded aggregate 2.7-2.8 ms: 2.0's parser is slower, and the check is mostly parsing.

When it refuses

Every refusal is an exception whose message is written to be read by whoever sent the SQL:

  • QueryRejected - what was refused and what is allowed instead.
  • QueryFailed, a QueryRejected - the guard let the SQL through and DuckDB could not run it. The message is DuckDB's, all of it: the Candidate bindings it suggests for a misspelt column, and the LINE n: pointer with its ^^^, numbered as the SQL was written. getErrorType() says "Binder", "Catalog", "Conversion", "Permission" and so on, and the cause is the driver's SQLException. Catch it before QueryRejected to show DuckDB's message for one and "only queries can run here" for the other.
  • QueryTimedOut - how long it was given, and that narrowing the query would help.
  • ResultTruncated - which cap was passed, and that a LIMIT, a filter or a GROUP BY would help.

guard.whyRejected(sql) gives the same message without running anything, for a tool that wants to tell an agent why before it tries.

See examples/src/main/java/AgentGuardedQueries.java for all of it, with its real output.