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 [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.
- Add the dependency. Test scope only, so your production code never depends on it. Without Spring, use
queryfence-junit5. - 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.
- Run your tests. Every
DataSourcein 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>
// build.gradle.kts dependencies { testImplementation("com.steelreed:queryfence-spring-test:0.1.0") } // Reports go to build/queryfence/
# src/test/resources/queryfence.yml version: 1 mode: FAIL # or REPORT while you adopt it onUnparseable: FAIL # SQL it cannot parse is a violation rules: - id: tenant-isolation type: require-predicate column: tenant_id tables: [purchase_order, order_item, invoice] - id: no-unbounded-update type: update-without-where suppressions: - rule: tenant-isolation origin: com.acme.admin.PlatformReportJob#nightlyTotals reason: Cross-tenant report that runs as the platform operator.
// Without Spring: queryfence-junit5 class OrderRepositoryTest { @RegisterExtension static final QueryFenceExtension queryFence = QueryFenceExtension.fromClasspath(); OrderRepository repository; @BeforeEach void setUp() { DataSource ds = queryFence.wrap(TestDatabase.dataSource()); repository = new OrderRepository(new JdbcTemplate(ds)); } }
What it catches.
Each rule walks the whole statement: joins, subqueries, CTEs and every UNION branch. Every message states the problem and the fix.
- MISSING_PREDICATENo tenant filter
SELECT * FROM invoice WHERE status = ?
invoiceis a protected table and nothing filters it bytenant_id. The message names the condition to add. - 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.
- 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_orderis filtered andorder_itemis not. - 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
findByIdandEntityManager.findsend. An id can be guessed, so it does not isolate tenants. UsefindByIdAndTenantId, or map the tenant with Hibernate@TenantId. - 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. - 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.
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.
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 reportIn 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.
| Tool | What it does | Where it works | What it misses |
|---|---|---|---|
| Code review | A person reads the diff | Any code | A missing filter is an absence, and absences are hard to see in a diff |
Hibernate @TenantId and filters | Adds the tenant condition to entity queries at runtime | Hibernate entity queries | Native SQL, JdbcTemplate, MyBatis, jOOQ, a disabled filter |
| PostgreSQL row-level security | The database refuses rows of other tenants | PostgreSQL | Other databases, roles that bypass RLS, a wrong session tenant |
| MyBatis-Plus tenant interceptor | Rewrites SQL at runtime | MyBatis-Plus | Other data-access code, tables on its ignore list |
| QueryFence | Checks every executed statement against a policy and fails the build | Any JDBC DataSource | Runtime 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.