You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@grails.apache.org by jd...@apache.org on 2026/10/12 07:53:26 UTC

(grails-core) branch fix/multi-tenant-get-by-id updated: Tell withoutId apart from the tenant id DEFAULT

This is an automated email from the ASF dual-hosted git repository.

jdaugherty pushed a commit to branch fix/multi-tenant-get-by-id
in repository https://gitbox.apache.org/repos/asf/grails-core.git


The following commit(s) were added to refs/heads/fix/multi-tenant-get-by-id by this push:
     new 70743888e0 Tell withoutId apart from the tenant id DEFAULT
70743888e0 is described below

commit 70743888e047c751606465b079758009b3e7dfaa
Author: James Daugherty <jd...@jdresources.net>
AuthorDate: Mon Oct 12 08:52:18 2026 +0100

    Tell withoutId apart from the tenant id DEFAULT
    
    Tenants.isWithoutId() compared the tenant id bound to the thread with the
    name of the default connection source, so a thread that withId or
    withCurrent bound to the tenant id DEFAULT counted as running without a
    tenant. Inside Tenants.withCurrent, or a @CurrentTenant method, with a
    tenant resolver that resolves DEFAULT, such as SubDomainTenantResolver for
    a host name without a subdomain, a lookup by id was therefore not
    restricted while a query was.
    
    Tenants.CurrentTenant now binds a marker in place of a tenant id while the
    thread runs without a tenant, reports it as the default connection source
    from get(), and isWithoutId() checks for the marker. A nested withTenant
    replaces and restores the marker as it does a tenant id, so withId and
    withCurrent restrict a lookup by id to the tenant DEFAULT as they restrict
    a query, and only withoutId lifts the restriction.
    
    PartitionedLookupByIdSpec and MongoLookupByIdMultiTenancySpec gain a
    feature for withCurrent with a resolver that resolves DEFAULT and a
    withTenant(DEFAULT) case, and the isWithoutId feature gains withId(DEFAULT),
    withCurrent and the restore after a nested withTenant. The upgrade note
    and the GORM for MongoDB guide say that only withoutId lifts the
    restriction.
---
 .../MongoLookupByIdMultiTenancySpec.groovy         | 27 +++++++++++++++
 .../asciidoc/multiTenancy/multiTenancyModes.adoc   |  2 +-
 .../partitioned/PartitionedLookupByIdSpec.groovy   | 38 ++++++++++++++++++++
 .../groovy/grails/gorm/multitenancy/Tenants.groovy | 40 ++++++++++++++++------
 .../src/en/guide/upgrading/upgrading60x.adoc       |  2 +-
 5 files changed, 97 insertions(+), 12 deletions(-)

diff --git a/grails-data-mongodb/core/src/test/groovy/org/grails/datastore/gorm/mongo/multitenancy/MongoLookupByIdMultiTenancySpec.groovy b/grails-data-mongodb/core/src/test/groovy/org/grails/datastore/gorm/mongo/multitenancy/MongoLookupByIdMultiTenancySpec.groovy
index a4aa0b4967..51d625206c 100644
--- a/grails-data-mongodb/core/src/test/groovy/org/grails/datastore/gorm/mongo/multitenancy/MongoLookupByIdMultiTenancySpec.groovy
+++ b/grails-data-mongodb/core/src/test/groovy/org/grails/datastore/gorm/mongo/multitenancy/MongoLookupByIdMultiTenancySpec.groovy
@@ -246,10 +246,37 @@ class MongoLookupByIdMultiTenancySpec extends AutoStartedMongoSpec {
         thrown(DataIntegrityViolationException)
     }
 
+    void 'withCurrent with a tenant resolver that resolves the default connection source does not lift the restriction'() {
+        given:
+        System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, ConnectionSource.DEFAULT)
+
+        expect: 'a lookup by id inside withCurrent agrees with a query'
+        Tenants.withCurrent(MongoDatastore) {
+            Memo.withNewSession {
+                [findById: Memo.findById(ownId),
+                 get     : Memo.get(ownId),
+                 read    : Memo.read(otherId),
+                 exists  : Memo.exists(ownId),
+                 getAll  : Memo.getAll(ownId, otherId)]
+            }
+        } == [findById: null, get: null, read: null, exists: false, getAll: [null, null]]
+
+        when:
+        Tenants.withCurrent(MongoDatastore) { Memo.withNewSession { Memo.load(ownId).title } }
+
+        then:
+        thrown(DataIntegrityViolationException)
+    }
+
     void 'a lookup by id inside withTenant is restricted to that tenant'() {
         expect:
         Memo.withTenant('other') { Memo.withNewSession { Memo.get(otherId)?.title } } == 'Other'
         Memo.withTenant('other') { Memo.withNewSession { Memo.get(ownId) } } == null
+
+        and: 'the tenant id DEFAULT restricts it as it restricts a query'
+        Memo.withTenant(ConnectionSource.DEFAULT) {
+            Memo.withNewSession { [Memo.findById(ownId), Memo.get(ownId), Memo.getAll(ownId, otherId)] }
+        } == [null, null, [null, null]]
     }
 
     void 'a lookup by id inside withoutId is not restricted to a tenant'() {
diff --git a/grails-data-mongodb/docs/src/docs/asciidoc/multiTenancy/multiTenancyModes.adoc b/grails-data-mongodb/docs/src/docs/asciidoc/multiTenancy/multiTenancyModes.adoc
index 42ef5865d3..23e08fe260 100644
--- a/grails-data-mongodb/docs/src/docs/asciidoc/multiTenancy/multiTenancyModes.adoc
+++ b/grails-data-mongodb/docs/src/docs/asciidoc/multiTenancy/multiTenancyModes.adoc
@@ -115,7 +115,7 @@ Lookups by id are restricted to the current tenant as well. `get`, `read`, `exis
 Book.get(id)
 ----
 
-Without a current tenant a lookup by id throws `TenantNotFoundException`, as a query does. Inside `Tenants.withoutId { }` a lookup by id is not restricted to a tenant, and neither is a proxy returned by `load` that is initialized there.
+Without a current tenant a lookup by id throws `TenantNotFoundException`, as a query does. Inside `Tenants.withoutId { }` a lookup by id is not restricted to a tenant, and neither is a proxy returned by `load` that is initialized there. Only `withoutId` lifts the restriction: a tenant id of `DEFAULT`, whether a tenant resolver resolves it or `withId` or `withCurrent` binds it, restricts a lookup by id to that tenant as it restricts a query.
 
 But this logic bypasses any built into tenant id interception and inclusion:
 
diff --git a/grails-datamapping-core-test/src/test/groovy/grails/gorm/multitenancy/partitioned/PartitionedLookupByIdSpec.groovy b/grails-datamapping-core-test/src/test/groovy/grails/gorm/multitenancy/partitioned/PartitionedLookupByIdSpec.groovy
index f6725181fe..c7158cc066 100644
--- a/grails-datamapping-core-test/src/test/groovy/grails/gorm/multitenancy/partitioned/PartitionedLookupByIdSpec.groovy
+++ b/grails-datamapping-core-test/src/test/groovy/grails/gorm/multitenancy/partitioned/PartitionedLookupByIdSpec.groovy
@@ -256,11 +256,38 @@ class PartitionedLookupByIdSpec extends Specification {
         thrown(DataIntegrityViolationException)
     }
 
+    void 'withCurrent with a tenant resolver that resolves the default connection source does not lift the restriction'() {
+        given:
+        System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, ConnectionSource.DEFAULT)
+
+        expect: 'a lookup by id inside withCurrent agrees with a query'
+        Tenants.withCurrent(SimpleMapDatastore) {
+            Note.withNewSession {
+                [findById: Note.findById(ownId),
+                 get     : Note.get(ownId),
+                 read    : Note.read(otherId),
+                 exists  : Note.exists(ownId),
+                 getAll  : Note.getAll(ownId, otherId)]
+            }
+        } == [findById: null, get: null, read: null, exists: false, getAll: [null, null]]
+
+        when:
+        Tenants.withCurrent(SimpleMapDatastore) { Note.withNewSession { Note.load(ownId).title } }
+
+        then:
+        thrown(DataIntegrityViolationException)
+    }
+
     void 'a lookup by id inside withTenant is restricted to that tenant'() {
         expect:
         Note.withTenant('other') { Note.withNewSession { Note.get(otherId)?.title } } == 'Other'
         Note.withTenant('other') { Note.withNewSession { Note.get(ownId) } } == null
         Note.withTenant('other').get(ownId) == null
+
+        and: 'the tenant id DEFAULT restricts it as it restricts a query'
+        Note.withTenant(ConnectionSource.DEFAULT) {
+            Note.withNewSession { [Note.findById(ownId), Note.get(ownId), Note.getAll(ownId, otherId)] }
+        } == [null, null, [null, null]]
     }
 
     void 'a lookup by id inside withoutId is not restricted to a tenant'() {
@@ -277,12 +304,23 @@ class PartitionedLookupByIdSpec extends Specification {
         !Tenants.withoutId(datastore) { Note.withTenant('own') { Tenants.isWithoutId() } }
         !Note.withTenant('own') { Tenants.isWithoutId() }
 
+        and: 'it is restored after a nested withTenant'
+        Tenants.withoutId(datastore) {
+            Note.withTenant('own') { Tenants.isWithoutId() }
+            Tenants.isWithoutId()
+        }
+
+        and: 'the tenant id DEFAULT does not count'
+        !Tenants.withId(datastore, ConnectionSource.DEFAULT) { Tenants.isWithoutId() }
+        !Note.withTenant(ConnectionSource.DEFAULT) { Tenants.isWithoutId() }
+
         when: 'the tenant resolver resolves the default connection source'
         System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, ConnectionSource.DEFAULT)
 
         then:
         Tenants.currentId(datastore) == ConnectionSource.DEFAULT
         !Tenants.isWithoutId()
+        !Tenants.withCurrent(SimpleMapDatastore) { Tenants.isWithoutId() }
     }
 
     void 'a proxy created under a tenant is not restricted to a tenant when it is initialized inside withoutId'() {
diff --git a/grails-datamapping-core/src/main/groovy/grails/gorm/multitenancy/Tenants.groovy b/grails-datamapping-core/src/main/groovy/grails/gorm/multitenancy/Tenants.groovy
index bd84823536..3b8a3f46f4 100644
--- a/grails-datamapping-core/src/main/groovy/grails/gorm/multitenancy/Tenants.groovy
+++ b/grails-datamapping-core/src/main/groovy/grails/gorm/multitenancy/Tenants.groovy
@@ -124,15 +124,16 @@ class Tenants {
     }
 
     /**
-     * Whether the current thread runs without a tenant id, as it does inside {@link #withoutId(Closure)}. Unlike
-     * {@link #currentId()}, this does not consult the tenant resolver, so a resolver that resolves the name of the
-     * default connection source as the tenant id does not count.
+     * Whether the current thread runs without a tenant id, as it does inside {@link #withoutId(Closure)}. The name of
+     * the default connection source does not count as running without a tenant id, whether the tenant resolver
+     * resolves it or {@link #withId(Serializable, Closure)} binds it, so it restricts a lookup by id as it restricts a
+     * query.
      *
-     * @return Whether the default connection source is bound to the current thread as the current tenant
+     * @return Whether the current thread runs without a tenant id
      * @since 7.0.18
      */
     static boolean isWithoutId() {
-        ConnectionSource.DEFAULT == CurrentTenant.get()
+        CurrentTenant.isWithoutTenant()
     }
 
     /**
@@ -359,10 +360,19 @@ class Tenants {
         private static final ThreadLocal<Serializable> currentTenantThreadLocal = new ThreadLocal<>()
 
         /**
-         * @return Obtain the current tenant
+         * @return Obtain the current tenant, which is the default connection source while the thread runs without a tenant
          */
         static Serializable get() {
-            currentTenantThreadLocal.get()
+            Serializable bound = currentTenantThreadLocal.get()
+            bound.is(Binding.WITHOUT_TENANT) ? ConnectionSource.DEFAULT : bound
+        }
+
+        /**
+         * @return Whether the thread runs without a tenant, as inside {@link Tenants#withoutId(Closure)}, rather than
+         * with the name of the default connection source as its tenant id
+         */
+        static boolean isWithoutTenant() {
+            currentTenantThreadLocal.get().is(Binding.WITHOUT_TENANT)
         }
 
         /**
@@ -385,7 +395,7 @@ class Tenants {
          * @return The result of the closure
          */
         static <T> T withTenant(Serializable tenantId, Closure<T> callable) {
-            def previous = get()
+            Serializable previous = currentTenantThreadLocal.get()
             try {
                 set(tenantId)
                 callable.call(tenantId)
@@ -406,9 +416,9 @@ class Tenants {
          * @return The result of the closure
          */
         static <T> T withoutTenant(Closure<T> callable) {
-            def previous = get()
+            Serializable previous = currentTenantThreadLocal.get()
             try {
-                set(ConnectionSource.DEFAULT)
+                set(Binding.WITHOUT_TENANT)
                 callable.call()
             } finally {
                 if (previous == null) {
@@ -418,6 +428,16 @@ class Tenants {
                 }
             }
         }
+
+        /**
+         * Bound to the thread in place of a tenant id while it runs without a tenant, so that
+         * {@link #isWithoutTenant()} tells that apart from the name of the default connection source bound as the
+         * tenant id, and so that a nested {@link #withTenant(Serializable, Closure)} replaces and restores it like a
+         * tenant id.
+         */
+        private static enum Binding {
+            WITHOUT_TENANT
+        }
     }
 
 }
diff --git a/grails-doc/src/en/guide/upgrading/upgrading60x.adoc b/grails-doc/src/en/guide/upgrading/upgrading60x.adoc
index f26ab68618..238fc1dc6c 100644
--- a/grails-doc/src/en/guide/upgrading/upgrading60x.adoc
+++ b/grails-doc/src/en/guide/upgrading/upgrading60x.adoc
@@ -1176,5 +1176,5 @@ With `DISCRIMINATOR` multi-tenancy, GORM for MongoDB and GORM's in-memory datast
 
 * The id of another tenant's instance is treated like an id that does not exist: `get` and `read` return `null`, `exists` returns `false`, `getAll` returns `null` in its place, and the proxy returned by `load` or `proxy` throws when it is initialized.
 * Without a current tenant, these methods throw `TenantNotFoundException`, as a query does. `getAll` without ids still returns an empty list.
-* Inside `Tenants.withoutId { }` a lookup by id is still not restricted to a tenant, and neither is a proxy returned by `load` or `proxy` that is initialized there.
+* Inside `Tenants.withoutId { }` a lookup by id is still not restricted to a tenant, and neither is a proxy returned by `load` or `proxy` that is initialized there. Only `withoutId` lifts the restriction: a tenant id of `DEFAULT`, whether a tenant resolver resolves it or `withId` or `withCurrent` binds it, restricts a lookup by id to that tenant as it restricts a query.
 * A lookup by id still finds an instance that the session holds for the current tenant, including one that has been saved but not flushed, and it does not flush the session.