You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@unomi.apache.org by sh...@apache.org on 2026/09/24 10:50:01 UTC

(unomi) branch graphql-authenticated-role-tenant-checks updated (61ba340c0 -> 3cf6ced0b)

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

asf-gitbox-commits pushed a change to branch graphql-authenticated-role-tenant-checks
in repository https://gitbox.apache.org/repos/asf/unomi.git


    omit 61ba340c0 Challenge on every WebSocket 401, compare the Basic scheme case-insensitively, restore idle timeout (#881)
    omit a56fa2ad2 Grant the JAAS success-path unit test the role and system access it now needs.
    omit c62897a46 Check roles and tenant authority after a realm login
    omit 4a41fd898 Cover public-operation authorization with integration tests
    omit b4dfdaf7d Authorize the executed GraphQL operation, not the first definition
     add ab028177a UNOMI-982: Drop a condition whose optional parameter the context does not supply (#864)
     add aab6c9e5e Keep Jetty client types out of GraphQLWebSocketIT method signatures (#882)
     add 668a15fbf UNOMI-976: Restrict Groovy action upload to system administrators (#852)
     add ce3eff265 UNOMI-978: Gate cross-profile merge and systemProperties writes on a trusted caller (#854)
     add a51bf3c9e Write filtered personalization contents back onto the request (#876)
     add cf52160eb Deny public MVEL eval APIs from the scripting class loader (#877)
     add 60edd20c9 Drop credentialed CORS on the public tracker endpoints (#878)
     add be15fd61a Bound diagnostic type tracking and the MVEL expression cache (#879)
     add 11edea0a3 UNOMI-977: Restrict router import/export configuration to system administrators (#853)
     add 4bbad657d Combine the profile scope with client event filters instead of replacing it (#871)
     add 58c7aebb6 Bound regular-expression evaluation in the matchesRegex operator (#872)
     add 5edd1e9b7 Authorize the executed GraphQL operation, not the first definition (#874)
     new f1b248e66 Check roles and tenant authority after a realm login
     new 091bad592 Grant the JAAS success-path unit test the role and system access it now needs.
     new 3cf6ced0b Challenge on every WebSocket 401, compare the Basic scheme case-insensitively, restore idle timeout (#881)

This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version.  This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:

 * -- * -- B -- O -- O -- O   (61ba340c0)
            \
             N -- N -- N   refs/heads/graphql-authenticated-role-tenant-checks (3cf6ced0b)

You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.

Any revisions marked "omit" are not gone; other references still
refer to them.  Any revisions marked "discard" are gone forever.

The 3 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 THREAT_MODEL.md                                    |   5 +-
 .../karaf-kar/src/main/feature/feature.xml         |   2 +
 extensions/groovy-actions/rest/pom.xml             |  10 +
 .../groovy/actions/rest/GroovyActionsEndPoint.java |   5 +
 .../rest/GroovyActionsEndPointRoleTest.java}       |  28 +-
 .../services/impl/GroovyActionsServiceImpl.java    |  23 +-
 .../impl/GroovyActionsServiceImplTest.java         |  49 ++
 ...Action.groovy => fieldInitializerAction.groovy} |  22 +-
 .../src/main/feature/feature.xml                   |   2 +
 extensions/router/router-rest/pom.xml              |  10 +
 .../rest/ExportConfigurationServiceEndPoint.java   |   3 +
 .../rest/ImportConfigurationServiceEndPoint.java   |   3 +
 .../rest/RouterConfigurationEndPointRoleTest.java  |  44 ++
 .../ProfileAllEventsConnectionDataFetcher.java     |  11 +-
 .../test/java/org/apache/unomi/itests/AllITs.java  |   4 +
 .../test/java/org/apache/unomi/itests/BaseIT.java  |  17 +
 .../test/java/org/apache/unomi/itests/BasicIT.java |  36 +-
 .../unomi/itests/ConditionRegexSafetyIT.java       | 110 +++++
 .../org/apache/unomi/itests/ContextServletIT.java  | 237 ++++++++++
 .../apache/unomi/itests/CorePersistenceITs.java    |   2 +
 .../GroovyActionsEndpointRoleSecurityIT.java       | 113 +++++
 .../org/apache/unomi/itests/InputValidationIT.java |  28 ++
 .../org/apache/unomi/itests/ProfileMergeIT.java    |  57 +++
 .../unomi/itests/PropertiesUpdateActionIT.java     | 101 +++++
 .../unomi/itests/RouterEndpointRoleSecurityIT.java | 136 ++++++
 .../graphql/GraphQLProfileEventsScopeIT.java       |  78 ++++
 .../unomi/itests/graphql/GraphQLWebSocketIT.java   |  29 +-
 .../graphql/security/profile-events-scope.json     |   8 +
 .../mvel-payload-personalization-mixed.json        |  32 ++
 ..._valid.json => eventcollector_noSessionId.json} |   3 +-
 manual/src/main/asciidoc/builtin-event-types.adoc  |  11 +-
 manual/src/main/asciidoc/configuration.adoc        |  29 +-
 .../asciidoc/migrations/migrate-3.0-to-3.1.adoc    |   3 +-
 manual/src/main/asciidoc/recipes.adoc              |   6 +-
 manual/src/main/asciidoc/samples/login-sample.adoc | 207 ++++++++-
 .../main/resources/etc/custom.system.properties    |   7 +-
 package/src/main/resources/etc/mvel-forbid.json    |   2 +-
 .../ConditionESQueryBuilderDispatcher.java         |  18 +-
 .../ConditionOSQueryBuilderDispatcher.java         |  18 +-
 .../spi/conditions/ConditionContextHelper.java     |  28 +-
 .../impl/ConditionEvaluatorDispatcherImpl.java     |  15 +-
 .../spi/conditions/ConditionContextHelperTest.java |  33 +-
 .../impl/ConditionEvaluatorDispatcherImplTest.java |  48 ++
 .../plugins/baseplugin/actions/IdentityTrust.java  |  44 ++
 .../actions/MergeProfilesOnPropertyAction.java     |  30 ++
 .../baseplugin/actions/UpdatePropertiesAction.java |  81 +++-
 .../conditions/PropertyConditionEvaluator.java     |  98 +++-
 .../resources/OSGI-INF/blueprint/blueprint.xml     |   1 +
 .../actions/ActionIdentityIntrusionTest.java       | 271 +++++++++++
 .../actions/MergeProfilesOnPropertyActionTest.java | 174 +++++++
 .../actions/UpdatePropertiesActionTest.java        | 281 ++++++++++++
 .../conditions/PropertyConditionEvaluatorTest.java |  41 ++
 .../request/actions/SetRemoteHostInfoAction.java   | 110 ++++-
 .../resources/OSGI-INF/blueprint/blueprint.xml     |   3 +
 .../resources/org.apache.unomi.plugins.request.cfg |   5 +
 .../actions/SetRemoteHostInfoActionTest.java       |  86 ++++
 .../unomi/rest/endpoints/ClientEndpoint.java       |   2 +-
 .../unomi/rest/endpoints/ContextJsonEndpoint.java  |   3 +-
 .../rest/endpoints/EventsCollectorEndpoint.java    |   8 +-
 .../rest/service/RequestIdentifierValidator.java   |  50 ++
 .../rest/endpoints/ContextJsonEndpointTest.java    |  28 ++
 .../rest/endpoints/PublicTrackerCorsTest.java      |  52 +++
 .../service/RequestIdentifierValidatorTest.java    |  57 +++
 samples/login-integration/pom.xml                  |  44 +-
 samples/login-integration/setup.sh                 | 297 ++++++++++++
 .../unomi/samples/login/LoginSampleResources.java  |  29 +-
 .../apache/unomi/samples/login/LoginServlet.java   | 399 ++++++++++++++++
 .../src/main/resources/static/index.html           |  75 +++
 .../resources/static/javascript/login-example.js   |  58 +++
 .../src/main/webapp/WEB-INF/web.xml                |  24 -
 .../login-integration/src/main/webapp/index.html   |  70 ---
 .../src/main/webapp/javascript/login-example.js    | 139 ------
 .../unomi/samples/login/LoginServletTest.java      | 502 +++++++++++++++++++++
 .../apache/unomi/scripting/ExpressionFilter.java   |  15 +-
 .../apache/unomi/scripting/MvelScriptExecutor.java |  83 ++--
 .../scripting/SecureFilteringClassLoader.java      | 130 ++++--
 .../internal/ExpressionFilterFactoryImpl.java      |  19 +-
 .../unomi/scripting/ExpressionFilterTest.java      |  46 ++
 .../unomi/scripting/MvelScriptExecutorTest.java    | 146 +++++-
 .../scripting/SecureFilteringClassLoaderTest.java  | 118 +++++
 .../internal/ExpressionFilterFactoryImplTest.java  |  87 ++++
 .../services/impl/TypeResolutionServiceImpl.java   |  34 +-
 .../services/impl/events/EventServiceImpl.java     |   5 +-
 .../impl/TypeResolutionServiceImplTest.java        |  22 +
 84 files changed, 4926 insertions(+), 474 deletions(-)
 copy extensions/{json-schema/services/src/main/java/org/apache/unomi/schema/api/ValidationException.java => groovy-actions/rest/src/test/java/org/apache/unomi/groovy/actions/rest/GroovyActionsEndPointRoleTest.java} (51%)
 copy extensions/groovy-actions/services/src/test/resources/META-INF/cxs/actions/{testSaveAction.groovy => fieldInitializerAction.groovy} (64%)
 create mode 100644 extensions/router/router-rest/src/test/java/org/apache/unomi/router/rest/RouterConfigurationEndPointRoleTest.java
 create mode 100644 itests/src/test/java/org/apache/unomi/itests/ConditionRegexSafetyIT.java
 create mode 100644 itests/src/test/java/org/apache/unomi/itests/GroovyActionsEndpointRoleSecurityIT.java
 create mode 100644 itests/src/test/java/org/apache/unomi/itests/RouterEndpointRoleSecurityIT.java
 create mode 100644 itests/src/test/java/org/apache/unomi/itests/graphql/GraphQLProfileEventsScopeIT.java
 create mode 100644 itests/src/test/resources/graphql/security/profile-events-scope.json
 create mode 100644 itests/src/test/resources/security/mvel-payload-personalization-mixed.json
 copy itests/src/test/resources/validation/{eventcollector_valid.json => eventcollector_noSessionId.json} (83%)
 create mode 100644 plugins/baseplugin/src/main/java/org/apache/unomi/plugins/baseplugin/actions/IdentityTrust.java
 create mode 100644 plugins/baseplugin/src/test/java/org/apache/unomi/plugins/baseplugin/actions/ActionIdentityIntrusionTest.java
 create mode 100644 plugins/baseplugin/src/test/java/org/apache/unomi/plugins/baseplugin/actions/MergeProfilesOnPropertyActionTest.java
 create mode 100644 plugins/baseplugin/src/test/java/org/apache/unomi/plugins/baseplugin/actions/UpdatePropertiesActionTest.java
 create mode 100644 plugins/request/src/test/java/org/apache/unomi/plugins/request/actions/SetRemoteHostInfoActionTest.java
 create mode 100644 rest/src/main/java/org/apache/unomi/rest/service/RequestIdentifierValidator.java
 create mode 100644 rest/src/test/java/org/apache/unomi/rest/endpoints/PublicTrackerCorsTest.java
 create mode 100644 rest/src/test/java/org/apache/unomi/rest/service/RequestIdentifierValidatorTest.java
 create mode 100755 samples/login-integration/setup.sh
 copy rest/src/main/java/org/apache/unomi/rest/server/RestServerBus.java => samples/login-integration/src/main/java/org/apache/unomi/samples/login/LoginSampleResources.java (59%)
 create mode 100644 samples/login-integration/src/main/java/org/apache/unomi/samples/login/LoginServlet.java
 create mode 100644 samples/login-integration/src/main/resources/static/index.html
 create mode 100644 samples/login-integration/src/main/resources/static/javascript/login-example.js
 delete mode 100644 samples/login-integration/src/main/webapp/WEB-INF/web.xml
 delete mode 100644 samples/login-integration/src/main/webapp/index.html
 delete mode 100644 samples/login-integration/src/main/webapp/javascript/login-example.js
 create mode 100644 samples/login-integration/src/test/java/org/apache/unomi/samples/login/LoginServletTest.java
 create mode 100644 scripting/src/test/java/org/apache/unomi/scripting/ExpressionFilterTest.java
 create mode 100644 scripting/src/test/java/org/apache/unomi/scripting/SecureFilteringClassLoaderTest.java
 create mode 100644 scripting/src/test/java/org/apache/unomi/scripting/internal/ExpressionFilterFactoryImplTest.java


(unomi) 03/03: Challenge on every WebSocket 401, compare the Basic scheme case-insensitively, restore idle timeout (#881)

Posted by sh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch graphql-authenticated-role-tenant-checks
in repository https://gitbox.apache.org/repos/asf/unomi.git

commit 3cf6ced0ba37db36e97550543587494a63aae0f0
Author: Serge Huber <sh...@apache.org>
AuthorDate: Tue Sep 22 15:59:26 2026 +0200

    Challenge on every WebSocket 401, compare the Basic scheme case-insensitively, restore idle timeout (#881)
    
    Co-authored-by: Claude Opus 4.8 <no...@anthropic.com>
---
 .../servlet/auth/GraphQLServletSecurityValidator.java   |  5 ++++-
 .../servlet/websocket/SubscriptionWebSocket.java        |  8 ++++++--
 .../auth/GraphQLServletSecurityValidatorTest.java       | 17 +++++++++++++++++
 .../servlet/websocket/SubscriptionWebSocketTest.java    |  4 +++-
 4 files changed, 30 insertions(+), 4 deletions(-)

diff --git a/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidator.java b/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidator.java
index 199f6394a..97624d7f1 100644
--- a/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidator.java
+++ b/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidator.java
@@ -87,6 +87,8 @@ public class GraphQLServletSecurityValidator {
         if (isAuthenticatedUser(req)) {
             return true;
         }
+        // A 401 carries a challenge whether the header was missing or its credential was refused.
+        res.addHeader("WWW-Authenticate", "Basic realm=\"karaf\"");
         res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
         return false;
     }
@@ -290,7 +292,8 @@ public class GraphQLServletSecurityValidator {
      *            (WebSocket {@code connection_init}); when null, no tenant header is consulted.
      */
     private boolean authenticateBasic(String authHeader, HttpServletRequest req) {
-        if (authHeader == null || !authHeader.startsWith("Basic ")) {
+        // The scheme token is case-insensitive (RFC 7235).
+        if (authHeader == null || !authHeader.regionMatches(true, 0, "Basic ", 0, 6)) {
             return false;
         }
 
diff --git a/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/servlet/websocket/SubscriptionWebSocket.java b/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/servlet/websocket/SubscriptionWebSocket.java
index 71299eb19..cf0a0c852 100644
--- a/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/servlet/websocket/SubscriptionWebSocket.java
+++ b/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/servlet/websocket/SubscriptionWebSocket.java
@@ -69,6 +69,9 @@ public class SubscriptionWebSocket extends WebSocketAdapter {
 
     private volatile ScheduledFuture<?> deadlineTask;
 
+    /** The session's configured idle timeout, shortened while unauthenticated and restored on authentication. */
+    private volatile long configuredIdleTimeout;
+
     private boolean deadlineExpired;
 
     private final SecurityService securityService;
@@ -101,6 +104,7 @@ public class SubscriptionWebSocket extends WebSocketAdapter {
         LOGGER.info("Opening web socket");
         super.onWebSocketConnect(sess);
         if (!authenticated) {
+            configuredIdleTimeout = sess.getIdleTimeout();
             // Bound how long an unauthenticated socket may sit open. The idle timeout alone is not a
             // deadline: Jetty resets it on any frame, including ping/pong control frames that never reach
             // onWebSocketText, so a client could hold an unauthenticated socket open just by pinging.
@@ -265,8 +269,8 @@ public class SubscriptionWebSocket extends WebSocketAdapter {
         cancelAuthenticationDeadline();
         final Session session = getSession();
         if (session != null) {
-            // Authenticated: drop the short unauthenticated deadline.
-            session.setIdleTimeout(0);
+            // Authenticated: back to the idle timeout the session was configured with, not "none".
+            session.setIdleTimeout(configuredIdleTimeout);
         }
         return true;
     }
diff --git a/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidatorTest.java b/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidatorTest.java
index 8a664a98f..a05d09193 100644
--- a/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidatorTest.java
+++ b/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidatorTest.java
@@ -240,6 +240,21 @@ class GraphQLServletSecurityValidatorTest {
         verify(response, never()).sendError(any(Integer.class));
     }
 
+    /** HTTP authentication scheme names are case-insensitive. */
+    @Test
+    void validateWebSocketUpgrade_withLowercaseScheme_isAccepted() throws IOException {
+        givenAdministratorRole();
+        when(securityService.hasSystemAccess()).thenReturn(true);
+        when(request.getHeader("Authorization")).thenReturn(BASIC_AUTH.replaceFirst("Basic", "basic"));
+        when(tenantService.getTenantByApiKey(any(), eq(ApiKey.ApiKeyType.PRIVATE))).thenReturn(null);
+
+        boolean authenticated = validator.validateWebSocketUpgrade(request, response);
+
+        assertTrue(authenticated);
+        verify(securityService).setCurrentSubject(any(Subject.class));
+        verify(response, never()).sendError(any(Integer.class));
+    }
+
     @Test
     void validateWebSocketUpgrade_rejectsPublicApiKeyOnly() throws IOException {
         // No Authorization header — public API key alone must not open subscriptions.
@@ -261,6 +276,8 @@ class GraphQLServletSecurityValidatorTest {
 
         assertFalse(authenticated);
         verify(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
+        // A 401 must carry a challenge whichever branch produced it.
+        verify(response).addHeader("WWW-Authenticate", "Basic realm=\"karaf\"");
         verify(securityService, never()).setCurrentSubject(any());
     }
 
diff --git a/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/websocket/SubscriptionWebSocketTest.java b/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/websocket/SubscriptionWebSocketTest.java
index c874f2a7a..895d422c2 100644
--- a/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/websocket/SubscriptionWebSocketTest.java
+++ b/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/websocket/SubscriptionWebSocketTest.java
@@ -151,6 +151,7 @@ class SubscriptionWebSocketTest {
         when(validator.authenticateBasicCredential(anyString())).thenReturn(true);
         when(securityService.getCurrentSubject()).thenReturn(subject);
         when(executionContextManager.getCurrentContext()).thenReturn(executionContext);
+        when(session.getIdleTimeout()).thenReturn(30_000L);
         SubscriptionWebSocket unauth = new SubscriptionWebSocket(graphQL, serviceManager, null, null,
                 securityService, executionContextManager, validator, deadlineScheduler);
         unauth.onWebSocketConnect(session);
@@ -161,7 +162,8 @@ class SubscriptionWebSocketTest {
         // Identity captured onto the socket, and not left bound to this shared IO thread.
         verify(securityService).clearCurrentSubject();
         verify(session, never()).close(anyInt(), anyString());
-        verify(session).setIdleTimeout(0);
+        // Back to the session's configured idle timeout, not disabled.
+        verify(session).setIdleTimeout(30_000L);
     }
 
     @Test


(unomi) 01/03: Check roles and tenant authority after a realm login

Posted by sh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch graphql-authenticated-role-tenant-checks
in repository https://gitbox.apache.org/repos/asf/unomi.git

commit f1b248e66c3fc717768bfb670067133474652b87
Author: Serge Huber <sh...@apache.org>
AuthorDate: Fri Aug 21 12:09:47 2026 +0200

    Check roles and tenant authority after a realm login
    
    A successful karaf realm login was treated as sufficient authorization for
    the GraphQL API: no role was inspected, the X-Unomi-Tenant-Id header was
    honoured without checking the subject's authority over the named tenant,
    and a request without that header fell back to the system context.
    
    Require an administrator role after login, honour the tenant header only
    for a subject with authority over that tenant, and reserve the system
    context for subjects that hold system access, refusing the request
    otherwise instead of falling back to it.
    
    Co-Authored-By: Claude Opus 4.8 <no...@anthropic.com>
---
 .../auth/GraphQLServletSecurityValidator.java      | 74 ++++++++++++------
 .../auth/GraphQLServletSecurityValidatorTest.java  | 87 +++++++++++++++++++++-
 2 files changed, 133 insertions(+), 28 deletions(-)

diff --git a/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidator.java b/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidator.java
index d6ef91881..199f6394a 100644
--- a/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidator.java
+++ b/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidator.java
@@ -21,6 +21,7 @@ import graphql.language.*;
 import graphql.parser.Parser;
 import org.apache.unomi.api.ExecutionContext;
 import org.apache.unomi.api.security.SecurityService;
+import org.apache.unomi.api.security.UnomiRoles;
 import org.apache.unomi.api.services.ExecutionContextManager;
 import org.apache.unomi.api.tenants.ApiKey;
 import org.apache.unomi.api.tenants.Tenant;
@@ -353,33 +354,58 @@ public class GraphQLServletSecurityValidator {
             });
             loginContext.login();
             Subject loginSubject = loginContext.getSubject();
-            boolean success = loginSubject != null;
-            if (success) {
-                if (req != null) {
-                    req.setAttribute(REMOTE_USER, username);
+            if (loginSubject == null) {
+                return false;
+            }
+
+            // Set the security context for JAAS authentication
+            securityService.setCurrentSubject(loginSubject);
+
+            // A successful realm login is not by itself an authorization to use this API: the realm
+            // can carry accounts that hold no Unomi role at all. Require the same administrator roles
+            // the REST admin surface requires.
+            if (!securityService.hasRole(UnomiRoles.ADMINISTRATOR)
+                    && !securityService.hasRole(UnomiRoles.TENANT_ADMINISTRATOR)) {
+                LOG.warn("Refusing GraphQL access to '{}': the account holds no Unomi administrator role", username);
+                securityService.clearCurrentSubject();
+                return false;
+            }
+
+            // Check for tenant ID header (only present when the credential arrived on a request;
+            // the connection_init route carries none, so it can never select a tenant this way)
+            String tenantId = req != null ? req.getHeader(UNOMI_TENANT_ID_HEADER) : null;
+            if (tenantId != null && !tenantId.trim().isEmpty()) {
+                // Validate tenant exists
+                Tenant tenant = tenantService.getTenant(tenantId);
+                if (tenant == null) {
+                    LOG.warn("Invalid tenant ID provided in header: {}", tenantId);
+                    securityService.clearCurrentSubject();
+                    return false;
                 }
-                // Set the security context for JAAS authentication
-                securityService.setCurrentSubject(loginSubject);
-
-                // Check for tenant ID header (only meaningful when the credential arrived on a request)
-                String tenantId = req != null ? req.getHeader(UNOMI_TENANT_ID_HEADER) : null;
-                if (tenantId != null && !tenantId.trim().isEmpty()) {
-                    // Validate tenant exists
-                    Tenant tenant = tenantService.getTenant(tenantId);
-                    if (tenant != null) {
-                        executionContextManager.setCurrentContext(executionContextManager.createContext(tenantId));
-                    } else {
-                        LOG.warn("Invalid tenant ID provided in header: {}", tenantId);
-                        // Same fallback as the "no tenant header" branch below: the thread-local
-                        // execution context must always be set explicitly here, otherwise a stale
-                        // context from a previous request on this pooled thread could leak in.
-                        executionContextManager.setCurrentContext(ExecutionContext.systemContext());
-                    }
-                } else {
-                    executionContextManager.setCurrentContext(ExecutionContext.systemContext());
+                // Naming a tenant is not the same as having authority over it.
+                if (!securityService.hasSystemAccess() && !securityService.hasTenantAccess(tenantId)) {
+                    LOG.warn("Refusing GraphQL access to '{}': no authority over tenant {}", username, tenantId);
+                    securityService.clearCurrentSubject();
+                    return false;
                 }
+                executionContextManager.setCurrentContext(executionContextManager.createContext(tenantId));
+            } else {
+                // No tenant header. The system context is inherited by every tenant, so it is reserved
+                // for subjects that actually hold system access rather than being the default.
+                if (!securityService.hasSystemAccess()) {
+                    LOG.warn("Refusing GraphQL access to '{}': no tenant specified and no system access", username);
+                    securityService.clearCurrentSubject();
+                    return false;
+                }
+                // The thread-local execution context must always be set explicitly here, otherwise a
+                // stale context from a previous request on this pooled thread could leak in.
+                executionContextManager.setCurrentContext(ExecutionContext.systemContext());
+            }
+
+            if (req != null) {
+                req.setAttribute(REMOTE_USER, username);
             }
-            return success;
+            return true;
         } catch (LoginException e) {
             LOG.debug("Login failed", e);
             return false;
diff --git a/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidatorTest.java b/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidatorTest.java
index 0f842f220..fbf5feac2 100644
--- a/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidatorTest.java
+++ b/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidatorTest.java
@@ -19,6 +19,7 @@ package org.apache.unomi.graphql.servlet.auth;
 
 import org.apache.unomi.api.ExecutionContext;
 import org.apache.unomi.api.security.SecurityService;
+import org.apache.unomi.api.security.UnomiRoles;
 import org.apache.unomi.api.services.ExecutionContextManager;
 import org.apache.unomi.api.tenants.ApiKey;
 import org.apache.unomi.api.tenants.Tenant;
@@ -94,8 +95,16 @@ class GraphQLServletSecurityValidatorTest {
         Configuration.setConfiguration(previousConfiguration);
     }
 
+    /** Grants the administrator role the JAAS branch now requires before it will authorize anything. */
+    private void givenAdministratorRole() {
+        lenient().when(securityService.hasRole(UnomiRoles.ADMINISTRATOR)).thenReturn(true);
+    }
+
     @Test
-    void validate_withInvalidTenantHeader_fallsBackToSystemContext() throws IOException {
+    void validate_withInvalidTenantHeader_isRejected() throws IOException {
+        // A tenant header that names no known tenant is refused; it must not fall back to the system
+        // context, which is inherited by every tenant.
+        givenAdministratorRole();
         when(request.getHeader("Authorization")).thenReturn(BASIC_AUTH);
         when(request.getHeader(TENANT_HEADER)).thenReturn("not-a-real-tenant");
         when(tenantService.getTenantByApiKey(any(), eq(ApiKey.ApiKeyType.PRIVATE))).thenReturn(null);
@@ -103,9 +112,60 @@ class GraphQLServletSecurityValidatorTest {
 
         boolean authenticated = validator.validate(null, null, request, response);
 
-        assertTrue(authenticated);
-        verify(executionContextManager).setCurrentContext(refEq(ExecutionContext.systemContext()));
-        verify(response, never()).sendError(any(Integer.class));
+        assertFalse(authenticated);
+        verify(executionContextManager, never()).setCurrentContext(refEq(ExecutionContext.systemContext()));
+        verify(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
+    }
+
+    @Test
+    void validate_withoutUnomiRole_isRejected() throws IOException {
+        // A realm account that carries no Unomi role (the shipped health-check account, for one) must
+        // not obtain access, even though the realm login itself succeeds.
+        when(request.getHeader("Authorization")).thenReturn(BASIC_AUTH);
+        when(tenantService.getTenantByApiKey(any(), eq(ApiKey.ApiKeyType.PRIVATE))).thenReturn(null);
+
+        boolean authenticated = validator.validate(null, null, request, response);
+
+        assertFalse(authenticated);
+        verify(executionContextManager, never()).setCurrentContext(any());
+        verify(securityService).clearCurrentSubject();
+        verify(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
+    }
+
+    @Test
+    void validate_withTenantHeaderButNoAuthorityOverIt_isRejected() throws IOException {
+        Tenant tenant = new Tenant();
+        tenant.setItemId("someone-elses-tenant");
+
+        givenAdministratorRole();
+        when(request.getHeader("Authorization")).thenReturn(BASIC_AUTH);
+        when(request.getHeader(TENANT_HEADER)).thenReturn("someone-elses-tenant");
+        when(tenantService.getTenantByApiKey(any(), eq(ApiKey.ApiKeyType.PRIVATE))).thenReturn(null);
+        when(tenantService.getTenant("someone-elses-tenant")).thenReturn(tenant);
+        when(securityService.hasSystemAccess()).thenReturn(false);
+        when(securityService.hasTenantAccess("someone-elses-tenant")).thenReturn(false);
+
+        boolean authenticated = validator.validate(null, null, request, response);
+
+        assertFalse(authenticated);
+        verify(executionContextManager, never()).createContext("someone-elses-tenant");
+        verify(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
+    }
+
+    @Test
+    void validate_withoutTenantHeaderAndNoSystemAccess_isRejected() throws IOException {
+        // The system context is not the default for an authenticated caller.
+        givenAdministratorRole();
+        when(request.getHeader("Authorization")).thenReturn(BASIC_AUTH);
+        when(request.getHeader(TENANT_HEADER)).thenReturn(null);
+        when(tenantService.getTenantByApiKey(any(), eq(ApiKey.ApiKeyType.PRIVATE))).thenReturn(null);
+        when(securityService.hasSystemAccess()).thenReturn(false);
+
+        boolean authenticated = validator.validate(null, null, request, response);
+
+        assertFalse(authenticated);
+        verify(executionContextManager, never()).setCurrentContext(refEq(ExecutionContext.systemContext()));
+        verify(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
     }
 
     @Test
@@ -113,10 +173,12 @@ class GraphQLServletSecurityValidatorTest {
         Tenant tenant = new Tenant();
         tenant.setItemId("known-tenant");
 
+        givenAdministratorRole();
         when(request.getHeader("Authorization")).thenReturn(BASIC_AUTH);
         when(request.getHeader(TENANT_HEADER)).thenReturn("known-tenant");
         when(tenantService.getTenantByApiKey(any(), eq(ApiKey.ApiKeyType.PRIVATE))).thenReturn(null);
         when(tenantService.getTenant("known-tenant")).thenReturn(tenant);
+        when(securityService.hasTenantAccess("known-tenant")).thenReturn(true);
         ExecutionContext tenantContext = new ExecutionContext("known-tenant", null, null);
         when(executionContextManager.createContext("known-tenant")).thenReturn(tenantContext);
 
@@ -128,6 +190,21 @@ class GraphQLServletSecurityValidatorTest {
         verify(executionContextManager, never()).setCurrentContext(refEq(ExecutionContext.systemContext()));
     }
 
+    @Test
+    void validate_withSystemAccessAndNoTenantHeader_usesSystemContext() throws IOException {
+        givenAdministratorRole();
+        when(request.getHeader("Authorization")).thenReturn(BASIC_AUTH);
+        when(request.getHeader(TENANT_HEADER)).thenReturn(null);
+        when(tenantService.getTenantByApiKey(any(), eq(ApiKey.ApiKeyType.PRIVATE))).thenReturn(null);
+        when(securityService.hasSystemAccess()).thenReturn(true);
+
+        boolean authenticated = validator.validate(null, null, request, response);
+
+        assertTrue(authenticated);
+        verify(executionContextManager).setCurrentContext(refEq(ExecutionContext.systemContext()));
+        verify(response, never()).sendError(any(Integer.class));
+    }
+
     @Test
     void validate_withoutAuthorizationHeader_isRejected() throws IOException {
         when(request.getHeader("Authorization")).thenReturn(null);
@@ -151,6 +228,8 @@ class GraphQLServletSecurityValidatorTest {
 
     @Test
     void validateWebSocketUpgrade_withBasicAuth_isAccepted() throws IOException {
+        givenAdministratorRole();
+        when(securityService.hasSystemAccess()).thenReturn(true);
         when(request.getHeader("Authorization")).thenReturn(BASIC_AUTH);
         when(tenantService.getTenantByApiKey(any(), eq(ApiKey.ApiKeyType.PRIVATE))).thenReturn(null);
 


(unomi) 02/03: Grant the JAAS success-path unit test the role and system access it now needs.

Posted by sh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch graphql-authenticated-role-tenant-checks
in repository https://gitbox.apache.org/repos/asf/unomi.git

commit 091bad592a72f11e32a8f517eaacc0c5bc2a6b69
Author: Serge Huber <sh...@apache.org>
AuthorDate: Mon Sep 21 21:39:20 2026 +0200

    Grant the JAAS success-path unit test the role and system access it now needs.
---
 .../graphql/servlet/auth/GraphQLServletSecurityValidatorTest.java      | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidatorTest.java b/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidatorTest.java
index fbf5feac2..8a664a98f 100644
--- a/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidatorTest.java
+++ b/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/auth/GraphQLServletSecurityValidatorTest.java
@@ -377,6 +377,9 @@ class GraphQLServletSecurityValidatorTest {
     /** Control: a non-blank credential still reaches the realm and is accepted by it. */
     @Test
     void validate_withNonBlankPassword_reachesJaas() throws IOException {
+        // Role + system access are required after JAAS succeeds when no tenant header is present.
+        givenAdministratorRole();
+        when(securityService.hasSystemAccess()).thenReturn(true);
         when(request.getHeader("Authorization")).thenReturn(BASIC_AUTH);
         when(tenantService.getTenantByApiKey(any(), eq(ApiKey.ApiKeyType.PRIVATE))).thenReturn(null);