SteelreedSteelreed

Fail the build on the query that forgets tenant_id.

A query on tenant data without a tenant filter passes code review, and it passes your tests too, because test data usually holds one tenant. QueryFence checks every SQL statement your integration tests send to the database and fails the test that ran the leaking one, naming the class, method and line.

com.steelreed:queryfence-spring-test:0.1.0
QueryFence./mvnw verify
QueryFence [queryfence.yml, mode FAIL]: 1 violation in 1 test

  [tenant-isolation] MISSING_PREDICATE
    table   : invoice (alias i1_0)    problem : invoice (i1_0) has no tenant filter. Add "i1_0.tenant_id = ?" to the WHERE clause of the query block that uses it.    sql     : select i1_0.id,i1_0.amount,i1_0.status,i1_0.tenant_id from invoice i1_0 where i1_0.status=?    origin  : com.acme.billing.InvoiceService#openInvoices (InvoiceService.java:20)    test    : com.acme.billing.InvoiceServiceTest#listsOpenInvoices
Full report: target/queryfence/report.json
BUILD FAILURE

Three steps. No test code to change.

  1. Add the dependency. Test scope only, so your production code never depends on it. Without Spring, use queryfence-junit5.
  2. Declare the policy. One YAML file lists the tables that must always be filtered by tenant. Start in REPORT mode on a project that already exists.
  3. Run your tests. Every DataSource in the Spring test context is wrapped. After each test, the SQL it ran is checked, and a violation fails that test.

QueryFence checks the SQL that reaches JDBC. A write in a @Transactional test that is never flushed is never sent, so it is never checked. Call flush() or use saveAndFlush().

<!-- pom.xml -->
<dependency>
  <groupId>com.steelreed</groupId>
  <artifactId>queryfence-spring-test</artifactId>
  <version>0.1.0</version>
  <scope>test</scope>
</dependency>

What it catches.

Each rule walks the whole statement: joins, subqueries, CTEs and every UNION branch. Every message states the problem and the fix.

  1. MISSING_PREDICATENo tenant filter

    SELECT * FROM invoice WHERE status = ?

    invoice is a protected table and nothing filters it by tenant_id. The message names the condition to add.

  2. MISSING_PREDICATEAn OR cancels the filter

    ... WHERE o.tenant_id = ? OR o.status = 'OPEN'

    An OR counts only when every branch filters the table. This one returns the open orders of every tenant.

  3. MISSING_PREDICATEA JOIN leaves a table unfiltered

    ... FROM purchase_order o JOIN order_item i ON i.order_id = o.id WHERE o.tenant_id = ?

    Each protected table needs its own filter. Here purchase_order is filtered and order_item is not.

  4. PRIMARY_KEY_LOOKUPA lookup by id alone

    select c1_0.id,c1_0.name from customer c1_0 where c1_0.id=?

    This is what findById and EntityManager.find send. An id can be guessed, so it does not isolate tenants. Use findByIdAndTenantId, or map the tenant with Hibernate @TenantId.

  5. NO_WHEREUPDATE or DELETE without WHERE

    UPDATE customer SET status = 'ARCHIVED'

    It changes every row in the table. A WHERE that is always true is reported too, as TAUTOLOGICAL_WHERE.

  6. MISSING_INSERT_COLUMNAn INSERT that skips the tenant

    INSERT INTO audit_log (action, at) VALUES (?, ?)

    An INSERT into a protected table has to set the tenant column.

SQL it cannot parse is reported as UNPARSEABLE, never skipped, and the finding names the protected tables the statement mentions. All rules

Works with the stack you already run.

It reads the SQL that reaches the JDBC driver, so it does not matter what wrote it: a derived query, JPQL, native SQL, MyBatis XML, jOOQ or a JdbcTemplate call. The SQL goes to the driver unchanged.

Spring BootHibernate / JPAMyBatisJdbcTemplatePostgreSQLMySQLJUnit 5Testcontainers

Tested on every pull request: MySQL 8.4 and PostgreSQL 17 through Testcontainers, JUnit 5.10 to 6.1, Spring Boot 3.3 to 4.1, Java 17, 21 and 25.

How the checker is tested.

A leak that slips past a rule is the worst bug QueryFence can have, so the rule engine is tested from several sides.

  • 260 golden cases: SQL, policy and the expected violations with their exact messages.
  • Metamorphic tests weaken every passing case five ways and require a violation each time.
  • PIT mutation testing, with the build failing below an 88% threshold.
  • A Testcontainers matrix runs Hibernate, MyBatis and JdbcTemplate against MySQL and PostgreSQL.
Dogfood run on Northwind Shop
queryfence.yml [REPORT]: 20 findings, 75 statements, 62 tests

By code                    Verdict
MISSING_PREDICATE       17  real leak            15
MISSING_INSERT_COLUMN    1  false positive        4
PRIMARY_KEY_LOOKUP       1  deliberate exception  1
UNPARSEABLE              1

We ran it on a multi-tenant app it was not written for: 75 statements checked, 15 real leaks, 4 false positives. All four are explained in the published report.

Read the dogfood report

In 0.1

  • Tenant filter, UPDATE and DELETE rules
  • JUnit 5 extension and Spring Boot test support
  • FAIL and REPORT modes
  • Suppressions that require a reason
  • Console summary and report.json

Not yet

  • Blocking SQL at runtime
  • Checking parameter values
  • Baseline file and HTML report
  • JUnit parallel execution

Next to the tools you may already use.

Most of these enforce tenant isolation at runtime. QueryFence verifies in CI that every query your tests run is filtered, whichever layer does the filtering, so it works alongside them.

ToolWhat it doesWhere it worksWhat it misses
Code reviewA person reads the diffAny codeA missing filter is an absence, and absences are hard to see in a diff
Hibernate @TenantId and filtersAdds the tenant condition to entity queries at runtimeHibernate entity queriesNative SQL, JdbcTemplate, MyBatis, jOOQ, a disabled filter
PostgreSQL row-level securityThe database refuses rows of other tenantsPostgreSQLOther databases, roles that bypass RLS, a wrong session tenant
MyBatis-Plus tenant interceptorRewrites SQL at runtimeMyBatis-PlusOther data-access code, tables on its ignore list
QueryFenceChecks every executed statement against a policy and fails the buildAny JDBC DataSourceRuntime protection, SQL your tests never run, the bound tenant value

Questions

Does QueryFence change my SQL?

No. It records statements through a DataSource proxy and passes them to the driver unchanged. It never blocks a statement.

Does my production code depend on it?

No. The dependency is test scope, there is no annotation to add, and suppressions live in the policy file.

Why did it report findById?

A primary key is not a tenant filter: ids can be guessed, and where id = ? returns another tenant's row just as well. Use findByIdAndTenantId, or map the tenant with Hibernate @TenantId.

Does it slow my tests down?

Each distinct SQL string is parsed once and cached. The integration suite checks tens of statements per test with no measurable difference.

Does it check that the tenant value is the right one?

No. It checks that a tenant filter exists in the SQL, not that the bound value is the current tenant. It also sees only the SQL your tests run.

Can I use it outside tests?

Not in 0.1. The rule engine has no JDBC or test dependencies, which keeps a runtime mode possible later, but nothing ships for it yet.

How do I add it to a project that already exists?

Start in REPORT mode, read the report, fix each finding or suppress it with a reason, then switch to FAIL. The adoption guide walks through it in about an hour.

Run it on your own queries.

Add the dependency, list your tenant tables and run the tests you already have. If you find SQL that slips past a rule, please report it privately to security@steelreed.com.