Add rls-safe-mode module: Hibernate 8.0.0.CR2 HQL safe mode and PostgreSQL row-level security for @TenantId

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b6ZEVHGaYy15HAxRzy
This commit is contained in:
Ankur Mhatre
2026-12-01 08:08:31 +05:30
co-authored by Claude Sonnet 5.5
parent 54c6d606ff
commit 1c9d9423c0
20 changed files with 817 additions and 1 deletions
+32
View File
@@ -0,0 +1,32 @@
# Hibernate 8 safe mode for HQL, and PostgreSQL row-level security for multi-tenancy
Runnable companion to the ankurm.com post on `hibernate.query.safe_mode_enabled` and Hibernate 8's generated
PostgreSQL row-level-security policy for `@TenantId`. Every figure in the post comes from a file in
[`output/`](output); each file is written by a test that asserts the same facts, so a claim that stops being true
fails the build.
Tested on Hibernate ORM 8.0.0.CR2 (release candidate, 24 Nov 2026), Jakarta Persistence 4.0.0-M8 (resolved
transitively), PostgreSQL 16.15, pgjdbc 42.7.15, Temurin 25.0.5.1, JUnit 6.1.3, Maven 3.9.11.
Both features are marked `@Incubating(since = "8.0")` in the CR2 sources. Behaviour may change before GA.
./scripts/setup-postgres.sh # once: role "app" (no superuser, no BYPASSRLS) and database "tenantdemo"
./scripts/run-all.sh # runs the tests and prints output/*.txt
| File | What it shows |
|---|---|
| `src/main/java/com/ankurm/tenant/Invoice.java` | `@TenantId` entity |
| `src/main/java/com/ankurm/tenant/Receipt.java` | `@SQLUpdate` / `@SQLDelete` with the extra tenant parameter |
| `src/main/java/com/ankurm/tenant/TenantContext.java` | thread-bound tenant resolver, `admin` is the root tenant |
| `src/main/java/com/ankurm/tenant/AppFunctions.java` | `FunctionContributor`: the safe-mode allow-list |
| `src/main/resources/META-INF/services/org.hibernate.boot.model.FunctionContributor` | registers the contributor |
| `src/test/java/com/ankurm/tenant/Lab.java` | boots a SessionFactory with safe mode and RLS toggled |
| `src/test/java/com/ankurm/tenant/SqlRecorder.java` | JDBC wrapper that records SQL with bound values |
| `src/test/java/com/ankurm/tenant/RlsSafeModeTest.java` | the five scenarios |
| Output | Scenario |
|---|---|
| `output/01-safe-mode.txt` | nine HQL and Criteria calls, safe mode off and on |
| `output/02-generated-rls-policy.txt`, `02b-rls-disabled.txt` | the policy Hibernate generated; nothing generated with `rls_enabled=false` |
| `output/03-isolation.txt` | HQL, native SQL, raw JDBC, superuser, root tenant, no tenant |
| `output/04-function-moves-tenant.txt` | a `set_config()` call from HQL moves the tenant |
| `output/05-custom-sql-tenant-parameter.txt` | the tenant parameter in `@SQLUpdate` and `@SQLDelete` |
+22
View File
@@ -0,0 +1,22 @@
hibernate.query.safe_mode_enabled=false
upper() built in ok: [ALICE, BOB]
initcap() contributed ok: [Alice, Bob]
quote_ident() unregistered ok: [alice, bob]
current_setting() unregistered ok: tenantA
set_config() unregistered ok: tenantB
sql('...') raw SQL ok: [alice, bob]
criteria function() ok: tenantA
criteria sql() ok: [alice, bob]
translate() built in on PostgreSQL ok: [xlice, bob]
hibernate.query.safe_mode_enabled=true
upper() built in ok: [ALICE, BOB]
initcap() contributed ok: [Alice, Bob]
quote_ident() unregistered rejected: SemanticException: Function [quote_ident] is not allowed in safe mode [select quote_ident(i.customer) from Invoice i order by i.id]
current_setting() unregistered rejected: SemanticException: Function [current_setting] is not allowed in safe mode [select current_setting('hibernate.tenant_id')]
set_config() unregistered rejected: SemanticException: Function [set_config] is not allowed in safe mode [select set_config('hibernate.tenant_id', 'tenantB', true)]
sql('...') raw SQL rejected: SemanticException: Function [sql] is not allowed in safe mode [select sql('lower(?)', i.customer) from Invoice i order by i.id]
criteria function() rejected: SemanticException: Function [current_setting] is not allowed in safe mode
criteria sql() rejected: SemanticException: Function [sql] is not allowed in safe mode
translate() built in on PostgreSQL ok: [xlice, bob]
@@ -0,0 +1,11 @@
select relname, relrowsecurity, relforcerowsecurity from pg_class (invoice, receipt)
invoice rowsecurity=true force=true
receipt rowsecurity=true force=true
select tablename, policyname, cmd, qual, with_check from pg_policies
table=invoice policy=hibernate_tenant_isolation cmd=ALL
using (((tenant_id)::text = ((NULLIF(current_setting('hibernate.tenant_id'::text, true), ''::text))::character varying(255))::text) OR COALESCE((NULLIF(current_setting('hibernate.tenant_id_root'::text, true), ''::text))::boolean, false))
with check (((tenant_id)::text = ((NULLIF(current_setting('hibernate.tenant_id'::text, true), ''::text))::character varying(255))::text) OR COALESCE((NULLIF(current_setting('hibernate.tenant_id_root'::text, true), ''::text))::boolean, false))
table=receipt policy=hibernate_tenant_isolation cmd=ALL
using (((tenant_id)::text = ((NULLIF(current_setting('hibernate.tenant_id'::text, true), ''::text))::character varying(255))::text) OR COALESCE((NULLIF(current_setting('hibernate.tenant_id_root'::text, true), ''::text))::boolean, false))
with check (((tenant_id)::text = ((NULLIF(current_setting('hibernate.tenant_id'::text, true), ''::text))::character varying(255))::text) OR COALESCE((NULLIF(current_setting('hibernate.tenant_id_root'::text, true), ''::text))::boolean, false))
@@ -0,0 +1,2 @@
hibernate.multi_tenant.rls_enabled=false
policies=0 tables with row security=0
+20
View File
@@ -0,0 +1,20 @@
rls_enabled=true. Rows: tenantA=2, tenantB=1
tenantA HQL select count(i) from Invoice i -> 2
tenantA native select count(*) from invoice -> 2
SQL that reached PostgreSQL for the native query:
select set_config('hibernate.tenant_id', ?, true), set_config('hibernate.tenant_id_root', ?, true) [tenantA, false]
select set_config('hibernate.tenant_id', ?, true), set_config('hibernate.tenant_id_root', ?, true) [tenantA, false]
select count(*) from invoice []
tenantA native insert for tenantB -> rejected: PSQLException: ERROR: new row violates row-level security policy for table "invoice"
admin (root) HQL count -> 3 native count -> 3
no tenant set -> rejected: HibernateException: SessionFactory configured for multi-tenancy, but no tenant identifier specified
Outside Hibernate, on plain JDBC connections:
role app, no tenant variable set select count(*) -> 0
role app, after set_config('...','tenantB') select count(*) -> 1
role postgres (superuser) select count(*) -> 3
role app superuser=false bypassrls=false
role postgres superuser=true bypassrls=true
rls_enabled=false. Same data.
tenantA HQL count -> 2 native count -> 3
@@ -0,0 +1,8 @@
safe_mode_enabled=false. tenantA runs a hostile HQL fragment, then the app counts rows natively in the same transaction.
hostile set_config(): ran
native count afterwards -> ok: 1
safe_mode_enabled=true. tenantA runs a hostile HQL fragment, then the app counts rows natively in the same transaction.
hostile set_config(): blocked (SemanticException)
native count afterwards -> ok: 2
@@ -0,0 +1,12 @@
rls_enabled=false, so only the SQL in @SQLUpdate and @SQLDelete stands between tenants.
tenantA edits its own receipt:
update receipt set memo=? where id=? and tenant_id=coalesce(?,tenant_id) [a-edited, 1, tenantA]
root edits tenantB's receipt:
update receipt set memo=? where id=? and tenant_id=coalesce(?,tenant_id) [b-edited-by-root, 2, null]
tenantA tries to delete tenantB's receipt through a reference:
-> rejected: ObjectNotFoundException: No row with the given identifier exists for entity [com.ankurm.tenant.Receipt with id '2']
tenantB's receipt still exists: true
tenantA deletes its own receipt:
delete from receipt where id=? and tenant_id=coalesce(?,tenant_id) [1, tenantA]
root deletes tenantB's receipt:
delete from receipt where id=? and tenant_id=coalesce(?,tenant_id) [2, null]
+51
View File
@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ankurm</groupId>
<artifactId>hibernate8-rls-safe-mode</artifactId>
<version>1.0.0</version>
<name>Hibernate 8 safe mode for HQL and PostgreSQL row-level security</name>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<hibernate.version>8.0.0.CR2</hibernate.version>
<postgresql.version>42.7.15</postgresql.version>
<junit.version>6.1.3</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.17</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.4</version>
</plugin>
</plugins>
</build>
</project>
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# Runs the whole suite and prints the transcripts it wrote to output/. Needs JDK 25, Maven and PostgreSQL 16+.
# Override the connection with PG_URL, PG_USER, PG_PASSWORD (default jdbc:postgresql://localhost:5433/tenantdemo, app/app).
set -euo pipefail
cd "$(dirname "$0")/.."
mvn -B -q test
for f in output/*.txt; do
echo "##### $f"
cat "$f"
echo
done
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Creates the role and database the tests expect on a PostgreSQL you already run.
# The application role must NOT be a superuser and must NOT have BYPASSRLS, or row-level security is skipped.
# Usage: PGHOST=localhost PGPORT=5432 PGUSER=postgres ./scripts/setup-postgres.sh
set -euo pipefail
psql -v ON_ERROR_STOP=1 -c "create role app login password 'app' nosuperuser nobypassrls"
psql -v ON_ERROR_STOP=1 -c "create database tenantdemo owner app"
echo "Done. Tests connect to \${PG_URL:-jdbc:postgresql://localhost:5433/tenantdemo} as app/app."
echo "The superuser comparison in 03-isolation connects as 'postgres' with an empty password (trust auth)."
@@ -0,0 +1,23 @@
package com.ankurm.tenant;
import org.hibernate.boot.model.FunctionContributions;
import org.hibernate.boot.model.FunctionContributor;
import org.hibernate.type.StandardBasicTypes;
/**
* The allow-list. With {@code hibernate.query.safe_mode_enabled=true} HQL may only call functions the
* dialect or a contributor registered. This contributor registers PostgreSQL's {@code initcap} and
* nothing else. It is discovered through META-INF/services.
*/
public class AppFunctions implements FunctionContributor {
@Override
public void contributeFunctions(FunctionContributions contributions) {
var string = contributions.getTypeConfiguration().getBasicTypeRegistry().resolve(StandardBasicTypes.STRING);
contributions.getFunctionRegistry()
.namedDescriptorBuilder("initcap")
.setExactArgumentCount(1)
.setInvariantType(string)
.register();
}
}
@@ -0,0 +1,38 @@
package com.ankurm.tenant;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import org.hibernate.annotations.TenantId;
/**
* A tenant-owned row. {@code @TenantId} makes Hibernate (1) add {@code tenant_id = ?} to every HQL
* query and (2) in Hibernate 8, generate a PostgreSQL row-level-security policy on the table.
*/
@Entity
@Table(name = "invoice")
public class Invoice {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;
@TenantId
@Column(name = "tenant_id", nullable = false)
public String tenant;
public String customer;
public int cents;
public Invoice() {
}
public Invoice(String customer, int cents) {
this.customer = customer;
this.cents = cents;
}
}
@@ -0,0 +1,38 @@
package com.ankurm.tenant;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.SQLUpdate;
import org.hibernate.annotations.TenantId;
/**
* Custom SQL for update and delete. Hibernate runs the SQL as written and adds no tenant predicate, so
* the statement must carry one. Hibernate 8 lets it declare one extra trailing {@code ?} that is bound
* to the session tenant (or to null for a root tenant).
*/
@Entity
@Table(name = "receipt")
@SQLUpdate(sql = "update receipt set memo=? where id=? and tenant_id=coalesce(?,tenant_id)")
@SQLDelete(sql = "delete from receipt where id=? and tenant_id=coalesce(?,tenant_id)")
public class Receipt {
@Id
public Long id;
@TenantId
@Column(name = "tenant_id", nullable = false)
public String tenant;
public String memo;
public Receipt() {
}
public Receipt(Long id, String memo) {
this.id = id;
this.memo = memo;
}
}
@@ -0,0 +1,33 @@
package com.ankurm.tenant;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
/** Thread-bound tenant. {@code "admin"} is the root tenant: it may see every tenant's rows. */
public class TenantContext implements CurrentTenantIdentifierResolver<String> {
public static final String ROOT = "admin";
private static final ThreadLocal<String> CURRENT = new ThreadLocal<>();
public static void set(String tenant) {
CURRENT.set(tenant);
}
public static void clear() {
CURRENT.remove();
}
@Override
public String resolveCurrentTenantIdentifier() {
return CURRENT.get();
}
@Override
public boolean validateExistingCurrentSessions() {
return false;
}
@Override
public boolean isRoot(String tenantId) {
return ROOT.equals(tenantId);
}
}
@@ -0,0 +1 @@
com.ankurm.tenant.AppFunctions
@@ -0,0 +1,66 @@
package com.ankurm.tenant;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.jpa.HibernatePersistenceConfiguration;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
/** Boots a Hibernate 8 SessionFactory on a real PostgreSQL with safe mode and RLS toggled per test. */
final class Lab implements AutoCloseable {
final SessionFactory sf;
Lab(boolean safeMode, boolean rls) {
var cfg = new HibernatePersistenceConfiguration("lab")
.managedClasses(Invoice.class, Receipt.class)
.property("hibernate.connection.provider_class", SqlRecorder.class.getName())
.property("hibernate.tenant_identifier_resolver", new TenantContext())
.property("hibernate.query.safe_mode_enabled", Boolean.toString(safeMode))
.property("hibernate.multi_tenant.rls_enabled", Boolean.toString(rls))
.property("jakarta.persistence.schema-generation.database.action", "drop-and-create");
this.sf = cfg.createEntityManagerFactory().unwrap(SessionFactory.class);
SqlRecorder.LOG.clear();
}
/** Runs work in one transaction as the given tenant. */
void as(String tenant, Consumer<Session> work) {
TenantContext.set(tenant);
try {
sf.inTransaction(work);
} finally {
TenantContext.clear();
}
}
<T> T asReturning(String tenant, Function<Session, T> work) {
TenantContext.set(tenant);
try {
return sf.fromTransaction(work);
} finally {
TenantContext.clear();
}
}
/** SQL executed since the last call, then forgets it. */
List<String> drain() {
List<String> copy = List.copyOf(SqlRecorder.LOG);
SqlRecorder.LOG.clear();
return copy;
}
/** A plain JDBC connection that bypasses Hibernate entirely. */
static Connection raw(String user, String password) throws SQLException {
return DriverManager.getConnection(SqlRecorder.URL, user, password);
}
@Override
public void close() {
sf.close();
}
}
@@ -0,0 +1,307 @@
package com.ankurm.tenant;
import jakarta.persistence.criteria.CriteriaBuilder;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.criteria.HibernateCriteriaBuilder;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import static org.junit.jupiter.api.Assertions.*;
/**
* Each test writes output/NN-name.txt and asserts the same facts the post quotes, so a figure that
* stops being true fails the build. Needs PostgreSQL: see ../README.md.
*/
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class RlsSafeModeTest {
static void seed(Lab lab) {
lab.as("tenantA", s -> {
s.persist(new Invoice("alice", 1000));
s.persist(new Invoice("bob", 2500));
});
lab.as("tenantB", s -> s.persist(new Invoice("zed", 9900)));
lab.drain();
}
/** "ok: ..." or "rejected: ExceptionSimpleName: first line of the message". */
static String attempt(Callable<Object> c) {
try {
return "ok: " + c.call();
} catch (Exception e) {
Throwable t = e;
while (t.getCause() != null && !(t instanceof org.hibernate.query.SemanticException)
&& !(t instanceof SQLException)) {
t = t.getCause();
}
String msg = String.valueOf(t.getMessage()).lines().findFirst().orElse("");
return "rejected: " + t.getClass().getSimpleName() + ": " + msg;
}
}
static long nativeCount(Session s) {
return ((Number) s.createNativeQuery("select count(*) from invoice", Object.class).getSingleResult()).longValue();
}
static long scalar(Connection c, String sql) throws SQLException {
try (Statement st = c.createStatement(); ResultSet rs = st.executeQuery(sql)) {
rs.next();
return rs.getLong(1);
}
}
// ---------------------------------------------------------------- 01 safe mode
@Test
@Order(1)
void safeModeBlocksUnregisteredFunctions() {
record Q(String label, java.util.function.Function<Session, Object> run) {
}
List<Q> queries = List.of(
new Q("upper() built in", s -> s.createSelectionQuery("select upper(i.customer) from Invoice i order by i.id", String.class).getResultList()),
new Q("initcap() contributed", s -> s.createSelectionQuery("select initcap(i.customer) from Invoice i order by i.id", String.class).getResultList()),
new Q("quote_ident() unregistered", s -> s.createSelectionQuery("select quote_ident(i.customer) from Invoice i order by i.id", String.class).getResultList()),
new Q("current_setting() unregistered", s -> s.createSelectionQuery("select current_setting('hibernate.tenant_id')", String.class).getSingleResult()),
new Q("set_config() unregistered", s -> s.createSelectionQuery("select set_config('hibernate.tenant_id', 'tenantB', true)", String.class).getSingleResult()),
new Q("sql('...') raw SQL", s -> s.createSelectionQuery("select sql('lower(?)', i.customer) from Invoice i order by i.id", String.class).getResultList()),
new Q("criteria function()", s -> {
HibernateCriteriaBuilder cb = s.getCriteriaBuilder();
var q = cb.createQuery(String.class);
q.select(cb.function("current_setting", String.class, cb.literal("hibernate.tenant_id")));
return s.createSelectionQuery(q).getSingleResult();
}),
new Q("criteria sql()", s -> {
HibernateCriteriaBuilder cb = s.getCriteriaBuilder();
var q = cb.createQuery(String.class);
var root = q.from(Invoice.class);
q.select(cb.sql("lower(?)", String.class, root.get("customer")));
return s.createSelectionQuery(q).getResultList();
}),
new Q("translate() built in on PostgreSQL", s -> s.createSelectionQuery("select translate(i.customer, 'a', 'x') from Invoice i order by i.id", String.class).getResultList())
);
try (var t = new Transcript("01-safe-mode")) {
for (boolean safe : new boolean[]{false, true}) {
try (Lab lab = new Lab(safe, true)) {
seed(lab);
t.line("hibernate.query.safe_mode_enabled=%s", safe);
for (Q q : queries) {
String r = attempt(() -> lab.asReturning("tenantA", q.run()));
t.line(" %-34s %s", q.label(), r);
}
t.line("");
if (!safe) {
assertTrue(attempt(() -> lab.asReturning("tenantA", queries.get(4).run())).startsWith("ok"));
} else {
for (int i : new int[]{2, 3, 4, 5, 6, 7}) {
String r = attempt(() -> lab.asReturning("tenantA", queries.get(i).run()));
assertTrue(r.startsWith("rejected: SemanticException"), queries.get(i).label() + " -> " + r);
}
for (int i : new int[]{0, 1, 8}) {
String r = attempt(() -> lab.asReturning("tenantA", queries.get(i).run()));
assertTrue(r.startsWith("ok"), queries.get(i).label() + " -> " + r);
}
}
}
}
}
}
// ---------------------------------------------------------------- 02 what Hibernate generated
@Test
@Order(2)
void hibernateGeneratesTheRlsPolicy() throws Exception {
try (Lab lab = new Lab(true, true); Connection su = Lab.raw("postgres", ""); var t = new Transcript("02-generated-rls-policy")) {
t.line("select relname, relrowsecurity, relforcerowsecurity from pg_class (invoice, receipt)");
try (Statement st = su.createStatement();
ResultSet rs = st.executeQuery("select relname, relrowsecurity, relforcerowsecurity from pg_class where relname in ('invoice','receipt') order by 1")) {
while (rs.next()) {
t.line(" %s rowsecurity=%s force=%s", rs.getString(1), rs.getBoolean(2), rs.getBoolean(3));
assertTrue(rs.getBoolean(2));
assertTrue(rs.getBoolean(3));
}
}
t.line("");
t.line("select tablename, policyname, cmd, qual, with_check from pg_policies");
int n = 0;
try (Statement st = su.createStatement();
ResultSet rs = st.executeQuery("select tablename, policyname, cmd, qual, with_check from pg_policies order by 1")) {
while (rs.next()) {
n++;
t.line(" table=%s policy=%s cmd=%s", rs.getString(1), rs.getString(2), rs.getString(3));
t.line(" using %s", rs.getString(4));
t.line(" with check %s", rs.getString(5));
assertEquals("hibernate_tenant_isolation", rs.getString(2));
}
}
assertEquals(2, n);
}
try (Lab lab = new Lab(true, false); Connection su = Lab.raw("postgres", ""); var t = new Transcript("02b-rls-disabled")) {
t.line("hibernate.multi_tenant.rls_enabled=false");
long policies = scalar(su, "select count(*) from pg_policies");
long rlsTables = scalar(su, "select count(*) from pg_class where relname in ('invoice','receipt') and relrowsecurity");
t.line(" policies=%d tables with row security=%d", policies, rlsTables);
assertEquals(0, policies);
assertEquals(0, rlsTables);
}
}
// ---------------------------------------------------------------- 03 isolation
@Test
@Order(3)
void rlsProtectsWhatTheHibernateFilterCannot() throws Exception {
try (var t = new Transcript("03-isolation")) {
try (Lab lab = new Lab(true, true); Connection su = Lab.raw("postgres", "")) {
seed(lab);
t.line("rls_enabled=true. Rows: tenantA=2, tenantB=1");
long hql = lab.asReturning("tenantA", s -> s.createSelectionQuery("select count(i) from Invoice i", Long.class).getSingleResult());
t.line(" tenantA HQL select count(i) from Invoice i -> %d", hql);
assertEquals(2, hql);
long nat = lab.asReturning("tenantA", RlsSafeModeTest::nativeCount);
t.line(" tenantA native select count(*) from invoice -> %d", nat);
assertEquals(2, nat);
lab.drain();
lab.as("tenantA", s -> nativeCount(s));
List<String> sql = lab.drain();
t.line(" SQL that reached PostgreSQL for the native query:");
sql.forEach(x -> t.line(" %s", x));
assertTrue(sql.get(0).startsWith("select set_config('hibernate.tenant_id', ?, true)"));
assertTrue(sql.get(sql.size() - 1).startsWith("select count(*) from invoice"));
String ins = attempt(() -> lab.asReturning("tenantA", s -> s.createNativeMutationQuery(
"insert into invoice(tenant_id, customer, cents) values ('tenantB', 'forged', 1)").executeUpdate()));
t.line(" tenantA native insert for tenantB -> %s", ins);
assertTrue(ins.contains("row-level security policy"));
long rootHql = lab.asReturning(TenantContext.ROOT, s -> s.createSelectionQuery("select count(i) from Invoice i", Long.class).getSingleResult());
long rootNat = lab.asReturning(TenantContext.ROOT, RlsSafeModeTest::nativeCount);
t.line(" admin (root) HQL count -> %d native count -> %d", rootHql, rootNat);
String none = attempt(() -> lab.sf.fromTransaction(s -> s.createSelectionQuery("select count(i) from Invoice i", Long.class).getSingleResult()));
t.line(" no tenant set -> %s", none);
assertTrue(none.contains("no tenant identifier"));
t.line("");
t.line("Outside Hibernate, on plain JDBC connections:");
try (Connection app = Lab.raw("app", "app")) {
long zero = scalar(app, "select count(*) from invoice");
t.line(" role app, no tenant variable set select count(*) -> %d", zero);
assertEquals(0, zero);
try (Statement st = app.createStatement()) {
st.execute("select set_config('hibernate.tenant_id', 'tenantB', false)");
}
long b = scalar(app, "select count(*) from invoice");
t.line(" role app, after set_config('...','tenantB') select count(*) -> %d", b);
assertEquals(1, b);
}
long all = scalar(su, "select count(*) from invoice");
t.line(" role postgres (superuser) select count(*) -> %d", all);
assertEquals(3, all);
try (Statement st = su.createStatement(); ResultSet rs = st.executeQuery(
"select rolname, rolsuper, rolbypassrls from pg_roles where rolname in ('app','postgres') order by 1")) {
while (rs.next()) {
t.line(" role %-8s superuser=%s bypassrls=%s", rs.getString(1), rs.getBoolean(2), rs.getBoolean(3));
}
}
}
t.line("");
try (Lab lab = new Lab(true, false)) {
seed(lab);
t.line("rls_enabled=false. Same data.");
long hql = lab.asReturning("tenantA", s -> s.createSelectionQuery("select count(i) from Invoice i", Long.class).getSingleResult());
long nat = lab.asReturning("tenantA", RlsSafeModeTest::nativeCount);
t.line(" tenantA HQL count -> %d native count -> %d", hql, nat);
assertEquals(2, hql);
assertEquals(3, nat);
}
}
}
// ---------------------------------------------------------------- 04 a function can move the tenant
@Test
@Order(4)
void aFunctionCallCanMoveTheTenant() {
try (var t = new Transcript("04-function-moves-tenant")) {
for (boolean safe : new boolean[]{false, true}) {
try (Lab lab = new Lab(safe, true)) {
seed(lab);
t.line("safe_mode_enabled=%s. tenantA runs a hostile HQL fragment, then the app counts rows natively in the same transaction.", safe);
String[] out = new String[2];
String r = attempt(() -> lab.asReturning("tenantA", s -> {
try {
s.createSelectionQuery("select set_config('hibernate.tenant_id', 'tenantB', true)", String.class).getSingleResult();
out[0] = "ran";
} catch (RuntimeException e) {
out[0] = "blocked (" + e.getClass().getSimpleName() + ")";
}
return nativeCount(s);
}));
t.line(" hostile set_config(): %s", out[0]);
t.line(" native count afterwards -> %s", r);
assertEquals(safe ? "ok: 2" : "ok: 1", r);
t.line("");
}
}
}
}
// ---------------------------------------------------------------- 05 custom SQL
@Test
@Order(5)
void customSqlGetsATenantParameter() {
try (var t = new Transcript("05-custom-sql-tenant-parameter")) {
try (Lab lab = new Lab(true, false)) {
lab.as("tenantA", s -> s.persist(new Receipt(1L, "a-first")));
lab.as("tenantB", s -> s.persist(new Receipt(2L, "b-first")));
lab.drain();
t.line("rls_enabled=false, so only the SQL in @SQLUpdate and @SQLDelete stands between tenants.");
lab.as("tenantA", s -> s.find(Receipt.class, 1L).memo = "a-edited");
t.line("tenantA edits its own receipt:");
lab.drain().stream().filter(x -> x.startsWith("update")).forEach(x -> t.line(" %s", x));
lab.as(TenantContext.ROOT, s -> s.find(Receipt.class, 2L).memo = "b-edited-by-root");
t.line("root edits tenantB's receipt:");
lab.drain().stream().filter(x -> x.startsWith("update")).forEach(x -> t.line(" %s", x));
assertEquals("b-edited-by-root", lab.asReturning(TenantContext.ROOT, s -> s.find(Receipt.class, 2L).memo));
assertEquals("a-edited", lab.asReturning(TenantContext.ROOT, s -> s.find(Receipt.class, 1L).memo));
String r = attempt(() -> lab.asReturning("tenantA", s -> {
s.remove(s.getReference(Receipt.class, 2L));
s.flush();
return "deleted";
}));
t.line("tenantA tries to delete tenantB's receipt through a reference:");
lab.drain().stream().filter(x -> x.startsWith("delete")).forEach(x -> t.line(" %s", x));
t.line(" -> %s", r);
long still = lab.asReturning(TenantContext.ROOT, s -> s.createSelectionQuery("select count(r) from Receipt r where r.id = 2", Long.class).getSingleResult());
t.line(" tenantB's receipt still exists: %s", still == 1);
assertEquals(1, still);
lab.drain();
lab.as("tenantA", s -> s.remove(s.find(Receipt.class, 1L)));
t.line("tenantA deletes its own receipt:");
lab.drain().stream().filter(x -> x.startsWith("delete")).forEach(x -> t.line(" %s", x));
lab.as(TenantContext.ROOT, s -> s.remove(s.find(Receipt.class, 2L)));
t.line("root deletes tenantB's receipt:");
lab.drain().stream().filter(x -> x.startsWith("delete")).forEach(x -> t.line(" %s", x));
long left = lab.asReturning(TenantContext.ROOT, s -> s.createSelectionQuery("select count(r) from Receipt r", Long.class).getSingleResult());
assertEquals(0, left);
}
}
}
}
@@ -0,0 +1,88 @@
package com.ankurm.tenant;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/** Records every prepared statement with its bound values, so a transcript can show what reached PostgreSQL. */
public class SqlRecorder implements ConnectionProvider {
public static final List<String> LOG = Collections.synchronizedList(new ArrayList<>());
public static final String URL = System.getenv().getOrDefault("PG_URL", "jdbc:postgresql://localhost:5433/tenantdemo");
public static final String USER = System.getenv().getOrDefault("PG_USER", "app");
public static final String PASSWORD = System.getenv().getOrDefault("PG_PASSWORD", "app");
public SqlRecorder() {
}
@Override
public Connection getConnection() throws SQLException {
Connection real = DriverManager.getConnection(URL, USER, PASSWORD);
return (Connection) Proxy.newProxyInstance(
SqlRecorder.class.getClassLoader(), new Class<?>[]{Connection.class},
(proxy, method, args) -> {
Object result = invoke(real, method, args);
if (method.getName().equals("prepareStatement") && result instanceof PreparedStatement ps) {
return wrap(ps, (String) args[0]);
}
return result;
});
}
private static Object invoke(Object target, java.lang.reflect.Method m, Object[] args) throws Throwable {
try {
return m.invoke(target, args);
} catch (java.lang.reflect.InvocationTargetException e) {
throw e.getCause();
}
}
private static PreparedStatement wrap(PreparedStatement ps, String sql) {
Map<Integer, Object> params = new TreeMap<>();
InvocationHandler h = (proxy, method, args) -> {
String n = method.getName();
if (n.startsWith("set") && args != null && args.length >= 2 && args[0] instanceof Integer i) {
params.put(i, n.equals("setNull") ? "null" : args[1]);
}
if (n.equals("executeUpdate") || n.equals("execute") || n.equals("executeQuery") || n.equals("addBatch")) {
LOG.add(sql.replaceAll("\\s+", " ").trim() + " " + params.values());
if (n.equals("addBatch")) {
params.clear();
}
}
return invoke(ps, method, args);
};
return (PreparedStatement) Proxy.newProxyInstance(
SqlRecorder.class.getClassLoader(), new Class<?>[]{PreparedStatement.class}, h);
}
@Override
public void closeConnection(Connection conn) throws SQLException {
conn.close();
}
@Override
public boolean supportsAggressiveRelease() {
return false;
}
@Override
public boolean isUnwrappableAs(Class<?> unwrapType) {
return unwrapType.isAssignableFrom(SqlRecorder.class);
}
@Override
public <T> T unwrap(Class<T> unwrapType) {
return unwrapType.cast(this);
}
}
@@ -0,0 +1,44 @@
package com.ankurm.tenant;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/**
* Collects printed lines and writes them to output/NN-name.txt. The blog post quotes these
* files verbatim, and the test that writes each one asserts the same behaviour, so a claim that stops
* being true fails the build.
*/
final class Transcript implements AutoCloseable {
private final Path file;
private final List<String> lines = new ArrayList<>();
Transcript(String name) {
this.file = Path.of("output", name + ".txt");
}
void line(String fmt, Object... args) {
lines.add(args.length == 0 ? fmt : String.format(fmt, args));
}
void sql(String label, List<String> statements) {
long n = statements.stream().filter(x -> !x.startsWith("--")).count();
line("%s (%d statement%s)", label, n, n == 1 ? "" : "s");
for (String s : statements) {
line(" %s", s);
}
}
@Override
public void close() {
try {
Files.createDirectories(file.getParent());
Files.write(file, lines);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}