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

sergehuber pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/unomi.git


The following commit(s) were added to refs/heads/master by this push:
     new 892ec2e62 Bound GraphQL query size, depth, and complexity (#953)
892ec2e62 is described below

commit 892ec2e6295f952c070a38b7a7ef1edd1ba1f93f
Author: Serge Huber <[email protected]>
AuthorDate: Thu Nov 12 08:37:27 2026 +0100

    Bound GraphQL query size, depth, and complexity (#953)
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 THREAT_MODEL.md                                    |   1 +
 graphql/cxs-impl/pom.xml                           |  24 ++++
 .../unomi/graphql/limits/GraphQLLimitsConfig.java  | 106 ++++++++++++++++
 .../unomi/graphql/limits/GraphQLRequestLimits.java | 136 ++++++++++++++++++++
 .../unomi/graphql/schema/GraphQLSchemaUpdater.java |  55 +++++++-
 .../unomi/graphql/servlet/GraphQLServlet.java      |  38 +++++-
 .../auth/GraphQLServletSecurityValidator.java      |  66 ++++++----
 .../main/resources/org.apache.unomi.graphql.cfg    |  25 ++++
 .../graphql/limits/GraphQLRequestLimitsTest.java   | 138 +++++++++++++++++++++
 .../schema/GraphQLLimitsInstrumentationTest.java   | 130 +++++++++++++++++++
 .../unomi/graphql/servlet/GraphQLServletTest.java  |  94 ++++++++++++++
 .../auth/GraphQLServletSecurityValidatorTest.java  |  94 +++++++++++++-
 graphql/karaf-feature/src/main/feature/feature.xml |   1 +
 manual/src/main/asciidoc/configuration.adoc        |  20 +++
 .../asciidoc/migrations/migrate-3.0-to-4.0.adoc    |   4 +
 package/pom.xml                                    |   8 ++
 .../main/resources/etc/custom.system.properties    |   5 +
 17 files changed, 913 insertions(+), 32 deletions(-)

diff --git a/THREAT_MODEL.md b/THREAT_MODEL.md
index 0e1a8b660..a02e64403 100644
--- a/THREAT_MODEL.md
+++ b/THREAT_MODEL.md
@@ -129,6 +129,7 @@ Per-surface trust table *(all inferred unless noted):*
 - Restrict who holds condition/rule/scripting authoring authority — it is 
equivalent to server-side code definition. *(inferred)*
 - Put the public endpoint behind rate-limiting / a CDN/WAF appropriate to 
public exposure. *(inferred)*
 - **CORS:** public tracker credentialed CORS (visitor cookie) is opt-in via 
`org.apache.unomi.public.cors.allowedOrigins` (and optional tenant lists). 
Admin REST/GraphQL credentialed CORS (operator Basic auth in the browser) is a 
separate opt-in via `org.apache.unomi.admin.cors.allowedOrigins`; the default 
is empty. Same-origin admin UIs need no entry. CORS response headers alone do 
not stop simple credentialed **writes** from another origin — keep the admin UI 
same-origin or add CSRF controls.
+- **GraphQL bounds:** document length, request body size, query depth, and 
query complexity are capped by `org.apache.unomi.graphql.*` (defaults leave 
GraphiQL introspection and the public `getProfile` / `processEvents` fields 
usable).
 
 ## §11 Known misuse patterns
 
diff --git a/graphql/cxs-impl/pom.xml b/graphql/cxs-impl/pom.xml
index 901da4102..1eb37c207 100644
--- a/graphql/cxs-impl/pom.xml
+++ b/graphql/cxs-impl/pom.xml
@@ -176,6 +176,30 @@
                     </instructions>
                 </configuration>
             </plugin>
+            <plugin>
+                <groupId>org.codehaus.mojo</groupId>
+                <artifactId>build-helper-maven-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <id>attach-artifacts</id>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>attach-artifact</goal>
+                        </goals>
+                        <configuration>
+                            <artifacts>
+                                <artifact>
+                                    <file>
+                                        
src/main/resources/org.apache.unomi.graphql.cfg
+                                    </file>
+                                    <type>cfg</type>
+                                    <classifier>unomicfg</classifier>
+                                </artifact>
+                            </artifacts>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
         </plugins>
     </build>
 
diff --git 
a/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/limits/GraphQLLimitsConfig.java
 
b/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/limits/GraphQLLimitsConfig.java
new file mode 100644
index 000000000..8f9b5a5fa
--- /dev/null
+++ 
b/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/limits/GraphQLLimitsConfig.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.unomi.graphql.limits;
+
+import org.apache.unomi.graphql.schema.GraphQLSchemaUpdater;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Modified;
+import org.osgi.service.component.annotations.Reference;
+import org.osgi.service.component.annotations.ReferenceCardinality;
+import org.osgi.service.component.annotations.ReferencePolicy;
+import org.osgi.service.metatype.annotations.AttributeDefinition;
+import org.osgi.service.metatype.annotations.Designate;
+import org.osgi.service.metatype.annotations.ObjectClassDefinition;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Bound GraphQL query size and analysis cost. Defaults leave GraphiQL 
introspection and the public
+ * {@code getProfile} / {@code processEvents} fields usable.
+ */
+@Component(service = GraphQLLimitsConfig.class, immediate = true, 
configurationPid = "org.apache.unomi.graphql")
+@Designate(ocd = GraphQLLimitsConfig.Config.class)
+public class GraphQLLimitsConfig {
+
+    private static final Logger LOGGER = 
LoggerFactory.getLogger(GraphQLLimitsConfig.class);
+
+    @ObjectClassDefinition(name = "Apache Unomi GraphQL limits")
+    public @interface Config {
+
+        @AttributeDefinition(description = "Maximum GraphQL query string 
length in characters. Zero or less disables the check.")
+        int max_query_length_chars() default 262144;
+
+        @AttributeDefinition(description = "Maximum GraphQL HTTP POST body 
size in bytes. Zero or less disables the check.")
+        int max_request_body_bytes() default 524288;
+
+        @AttributeDefinition(description = "Maximum GraphQL query depth. Zero 
or less disables the check.")
+        int max_query_depth() default 24;
+
+        @AttributeDefinition(description = "Maximum GraphQL query complexity. 
Zero or less disables the check.")
+        int max_query_complexity() default 3000;
+    }
+
+    private volatile int maxQueryLengthChars = 262144;
+    private volatile int maxRequestBodyBytes = 524288;
+    private volatile int maxQueryDepth = 24;
+    private volatile int maxQueryComplexity = 3000;
+
+    private volatile GraphQLSchemaUpdater schemaUpdater;
+
+    @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = 
ReferencePolicy.DYNAMIC, unbind = "unsetSchemaUpdater")
+    protected void setSchemaUpdater(GraphQLSchemaUpdater schemaUpdater) {
+        this.schemaUpdater = schemaUpdater;
+    }
+
+    protected void unsetSchemaUpdater(GraphQLSchemaUpdater schemaUpdater) {
+        if (this.schemaUpdater == schemaUpdater) {
+            this.schemaUpdater = null;
+        }
+    }
+
+    @Activate
+    @Modified
+    public void activate(Config config) {
+        this.maxQueryLengthChars = config.max_query_length_chars();
+        this.maxRequestBodyBytes = config.max_request_body_bytes();
+        this.maxQueryDepth = config.max_query_depth();
+        this.maxQueryComplexity = config.max_query_complexity();
+        LOGGER.info("GraphQL limits: length={}, bodyBytes={}, depth={}, 
complexity={}",
+                maxQueryLengthChars, maxRequestBodyBytes, maxQueryDepth, 
maxQueryComplexity);
+        GraphQLSchemaUpdater updater = this.schemaUpdater;
+        if (updater != null) {
+            updater.updateSchema();
+        }
+    }
+
+    public int getMaxQueryLengthChars() {
+        return maxQueryLengthChars;
+    }
+
+    public int getMaxRequestBodyBytes() {
+        return maxRequestBodyBytes;
+    }
+
+    public int getMaxQueryDepth() {
+        return maxQueryDepth;
+    }
+
+    public int getMaxQueryComplexity() {
+        return maxQueryComplexity;
+    }
+}
diff --git 
a/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/limits/GraphQLRequestLimits.java
 
b/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/limits/GraphQLRequestLimits.java
new file mode 100644
index 000000000..a03a8641c
--- /dev/null
+++ 
b/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/limits/GraphQLRequestLimits.java
@@ -0,0 +1,136 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.unomi.graphql.limits;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Pre-parse guards for GraphQL request size. Call these before the document 
is parsed.
+ */
+public final class GraphQLRequestLimits {
+
+    private GraphQLRequestLimits() {
+    }
+
+    /**
+     * @return {@code true} when the query may be processed; {@code false} 
when a 413 was already sent
+     */
+    public static boolean checkQueryLength(String query, GraphQLLimitsConfig 
limits, HttpServletResponse res)
+            throws IOException {
+        if (limits == null) {
+            return true;
+        }
+        int max = limits.getMaxQueryLengthChars();
+        if (max <= 0 || query == null || query.length() <= max) {
+            return true;
+        }
+        res.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, 
"GraphQL query exceeds the configured size limit");
+        return false;
+    }
+
+    /**
+     * Early refusal of a declared {@code Content-Length}. A body without one 
(chunked, or over 2 GB) is
+     * capped while it is read, see {@link #boundedBody}.
+     *
+     * @return {@code true} when the body may be read; {@code false} when a 
413 was already sent
+     */
+    public static boolean checkContentLength(int contentLength, 
GraphQLLimitsConfig limits, HttpServletResponse res)
+            throws IOException {
+        if (limits == null) {
+            return true;
+        }
+        int max = limits.getMaxRequestBodyBytes();
+        if (max <= 0 || contentLength < 0 || contentLength <= max) {
+            return true;
+        }
+        res.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, 
"GraphQL request body exceeds the configured size limit");
+        return false;
+    }
+
+    /**
+     * Wraps the request body so that reading more than the configured number 
of bytes fails with
+     * {@link BodyTooLargeException}, whatever the request declared.
+     */
+    public static InputStream boundedBody(InputStream body, 
GraphQLLimitsConfig limits) {
+        if (limits == null || limits.getMaxRequestBodyBytes() <= 0) {
+            return body;
+        }
+        return new BoundedInputStream(body, limits.getMaxRequestBodyBytes());
+    }
+
+    /** Sends the 413 for a body found too large while reading it. */
+    public static void sendBodyTooLarge(HttpServletResponse res) throws 
IOException {
+        res.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, 
"GraphQL request body exceeds the configured size limit");
+    }
+
+    /** The request body went over the configured limit while it was being 
read. */
+    public static final class BodyTooLargeException extends IOException {
+        BodyTooLargeException(long max) {
+            super("GraphQL request body exceeds " + max + " bytes");
+        }
+    }
+
+    private static final class BoundedInputStream extends FilterInputStream {
+        private final long max;
+        private long count;
+
+        BoundedInputStream(InputStream in, long max) {
+            super(in);
+            this.max = max;
+        }
+
+        @Override
+        public int read() throws IOException {
+            int b = super.read();
+            if (b >= 0) {
+                count(1);
+            }
+            return b;
+        }
+
+        @Override
+        public int read(byte[] b, int off, int len) throws IOException {
+            int n = super.read(b, off, len);
+            if (n > 0) {
+                count(n);
+            }
+            return n;
+        }
+
+        @Override
+        public long skip(long n) throws IOException {
+            long skipped = super.skip(n);
+            count(skipped);
+            return skipped;
+        }
+
+        @Override
+        public boolean markSupported() {
+            return false;
+        }
+
+        private void count(long n) throws BodyTooLargeException {
+            count += n;
+            if (count > max) {
+                throw new BodyTooLargeException(max);
+            }
+        }
+    }
+}
diff --git 
a/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/schema/GraphQLSchemaUpdater.java
 
b/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/schema/GraphQLSchemaUpdater.java
index 18c5a8913..1e5a11778 100644
--- 
a/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/schema/GraphQLSchemaUpdater.java
+++ 
b/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/schema/GraphQLSchemaUpdater.java
@@ -17,12 +17,17 @@
 package org.apache.unomi.graphql.schema;
 
 import graphql.GraphQL;
+import graphql.analysis.MaxQueryComplexityInstrumentation;
+import graphql.analysis.MaxQueryDepthInstrumentation;
 import graphql.execution.SubscriptionExecutionStrategy;
+import graphql.execution.instrumentation.ChainedInstrumentation;
+import graphql.execution.instrumentation.Instrumentation;
 import graphql.schema.GraphQLCodeRegistry;
 import graphql.schema.GraphQLSchema;
 import org.apache.unomi.api.services.ExecutionContextManager;
 import org.apache.unomi.api.services.ProfileService;
 import org.apache.unomi.graphql.fetchers.event.UnomiEventPublisher;
+import org.apache.unomi.graphql.limits.GraphQLLimitsConfig;
 import org.apache.unomi.graphql.providers.*;
 import org.apache.unomi.graphql.types.output.*;
 import org.apache.unomi.schema.api.SchemaService;
@@ -30,6 +35,7 @@ import org.osgi.service.component.annotations.*;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.*;
 
@@ -76,6 +82,8 @@ public class GraphQLSchemaUpdater {
 
     private ExecutionContextManager contextManager;
 
+    private GraphQLLimitsConfig limitsConfig;
+
     private ScheduledExecutorService executorService;
 
     private ScheduledFuture<?> updateFuture;
@@ -143,6 +151,14 @@ public class GraphQLSchemaUpdater {
         this.contextManager = contextManager;
     }
 
+    @Reference
+    public void setLimitsConfig(GraphQLLimitsConfig limitsConfig) {
+        this.limitsConfig = limitsConfig;
+        if (isActivated) {
+            updateSchema();
+        }
+    }
+
     @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = 
ReferencePolicy.DYNAMIC)
     public void bindProvider(GraphQLProvider provider) {
         if (provider instanceof GraphQLQueryProvider) {
@@ -315,9 +331,7 @@ public class GraphQLSchemaUpdater {
             contextManager.executeAsSystem(() -> {
                 final GraphQLSchema graphQLSchema = createGraphQLSchema();
 
-                this.graphQL = GraphQL.newGraphQL(graphQLSchema)
-                        .subscriptionExecutionStrategy(new 
SubscriptionExecutionStrategy())
-                        .build();
+                this.graphQL = buildGraphQL(graphQLSchema);
                 return null;
             });
 
@@ -328,6 +342,37 @@ public class GraphQLSchemaUpdater {
         }
     }
 
+    private GraphQL buildGraphQL(GraphQLSchema graphQLSchema) {
+        GraphQL.Builder builder = GraphQL.newGraphQL(graphQLSchema)
+                .subscriptionExecutionStrategy(new 
SubscriptionExecutionStrategy());
+        Instrumentation instrumentation = buildInstrumentation(limitsConfig);
+        if (instrumentation != null) {
+            builder.instrumentation(instrumentation);
+        }
+        return builder.build();
+    }
+
+    /** Depth and complexity limits, or {@code null} when none apply. 
Package-private for tests. */
+    static Instrumentation buildInstrumentation(GraphQLLimitsConfig 
limitsConfig) {
+        if (limitsConfig == null) {
+            return null;
+        }
+        List<Instrumentation> parts = new ArrayList<>();
+        if (limitsConfig.getMaxQueryDepth() > 0) {
+            parts.add(new 
MaxQueryDepthInstrumentation(limitsConfig.getMaxQueryDepth()));
+        }
+        if (limitsConfig.getMaxQueryComplexity() > 0) {
+            parts.add(new 
MaxQueryComplexityInstrumentation(limitsConfig.getMaxQueryComplexity()));
+        }
+        if (parts.isEmpty()) {
+            return null;
+        }
+        if (parts.size() == 1) {
+            return parts.get(0);
+        }
+        return new ChainedInstrumentation(parts);
+    }
+
     /**
      * Get the GraphQL instance for a specific tenant
      * @param tenantId The tenant ID
@@ -352,9 +397,7 @@ public class GraphQLSchemaUpdater {
             return contextManager.executeAsTenant(tenantId, () -> {
                 LOGGER.info("Creating GraphQL schema for tenant: {}", 
tenantId);
                 final GraphQLSchema graphQLSchema = 
createGraphQLSchemaForTenant(tenantId);
-                return GraphQL.newGraphQL(graphQLSchema)
-                        .subscriptionExecutionStrategy(new 
SubscriptionExecutionStrategy())
-                        .build();
+                return buildGraphQL(graphQLSchema);
             });
         } catch (Exception e) {
             LOGGER.error("Error creating GraphQL schema for tenant: " + 
tenantId, e);
diff --git 
a/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/servlet/GraphQLServlet.java
 
b/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/servlet/GraphQLServlet.java
index c76aab10c..d08140a60 100644
--- 
a/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/servlet/GraphQLServlet.java
+++ 
b/graphql/cxs-impl/src/main/java/org/apache/unomi/graphql/servlet/GraphQLServlet.java
@@ -27,6 +27,8 @@ import org.apache.unomi.api.services.AdminCorsService;
 import org.apache.unomi.api.services.ExecutionContextManager;
 import org.apache.unomi.api.tenants.AdminTenantConfig;
 import org.apache.unomi.api.tenants.TenantService;
+import org.apache.unomi.graphql.limits.GraphQLLimitsConfig;
+import org.apache.unomi.graphql.limits.GraphQLRequestLimits;
 import org.apache.unomi.graphql.schema.GraphQLSchemaUpdater;
 import org.apache.unomi.graphql.services.ServiceManager;
 import org.apache.unomi.graphql.servlet.auth.GraphQLServletSecurityValidator;
@@ -71,6 +73,8 @@ public class GraphQLServlet extends WebSocketServlet {
 
     private AdminCorsService adminCorsService;
 
+    private GraphQLLimitsConfig limitsConfig;
+
     private GraphQLServletSecurityValidator validator;
 
     @Reference
@@ -110,6 +114,11 @@ public class GraphQLServlet extends WebSocketServlet {
         this.securityService = securityService;
     }
 
+    @Reference
+    public void setLimitsConfig(GraphQLLimitsConfig limitsConfig) {
+        this.limitsConfig = limitsConfig;
+    }
+
     public GraphQLServlet() {
         LOGGER.info("GraphQLServlet created");
     }
@@ -124,7 +133,7 @@ public class GraphQLServlet extends WebSocketServlet {
                 ? adminTenantConfig
                 : () -> AdminTenantConfig.DEFAULT_ADMIN_TENANT_ID;
         this.validator = new GraphQLServletSecurityValidator(
-                tenantService, securityService, executionContextManager, 
tenantConfig);
+                tenantService, securityService, executionContextManager, 
tenantConfig, limitsConfig);
         super.init(config);
     }
 
@@ -328,10 +337,23 @@ public class GraphQLServlet extends WebSocketServlet {
     protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
throws IOException {
         LOGGER.debug("GraphQLServlet doPost called with request: {}", 
req.getRequestURI());
         try {
+            if 
(!GraphQLRequestLimits.checkContentLength(req.getContentLength(), limitsConfig, 
resp)) {
+                return;
+            }
             TypeReference<Map<String, Object>> typeRef = new 
TypeReference<Map<String, Object>>() {
             };
-            Map<String, Object> body = 
GraphQLObjectMapper.getInstance().readValue(req.getInputStream(), typeRef);
-
+            Map<String, Object> body;
+            try {
+                // Capped while read: a chunked body declares no 
Content-Length for the check above.
+                body = GraphQLObjectMapper.getInstance().readValue(
+                        GraphQLRequestLimits.boundedBody(req.getInputStream(), 
limitsConfig), typeRef);
+            } catch (IOException e) {
+                if (!isBodyTooLarge(e)) {
+                    throw e;
+                }
+                GraphQLRequestLimits.sendBodyTooLarge(resp);
+                return;
+            }
 
             String query = (String) body.get("query");
             String operationName = (String) body.get("operationName");
@@ -394,6 +416,16 @@ public class GraphQLServlet extends WebSocketServlet {
         GraphQLObjectMapper.getInstance().writeValue(resp.getWriter(), 
specificationResult);
     }
 
+    /** Jackson may wrap the stream's exception, so look along the cause 
chain. */
+    private static boolean isBodyTooLarge(Throwable e) {
+        for (Throwable t = e; t != null; t = t.getCause()) {
+            if (t instanceof GraphQLRequestLimits.BodyTooLargeException) {
+                return true;
+            }
+        }
+        return false;
+    }
+
     private void setupCORSHeaders(HttpServletRequest httpServletRequest, 
ServletResponse response) {
         if (!(response instanceof HttpServletResponse)) {
             return;
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 67464bccd..7ff1d928a 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
@@ -28,6 +28,8 @@ import org.apache.unomi.api.tenants.AdminTenantSelection;
 import org.apache.unomi.api.tenants.ApiKey;
 import org.apache.unomi.api.tenants.Tenant;
 import org.apache.unomi.api.tenants.TenantService;
+import org.apache.unomi.graphql.limits.GraphQLLimitsConfig;
+import org.apache.unomi.graphql.limits.GraphQLRequestLimits;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -69,17 +71,26 @@ public class GraphQLServletSecurityValidator {
     private final SecurityService securityService;
     private final ExecutionContextManager executionContextManager;
     private final AdminTenantConfig adminTenantConfig;
+    private final GraphQLLimitsConfig limitsConfig;
 
     public GraphQLServletSecurityValidator(TenantService tenantService,
                                          SecurityService securityService,
                                          ExecutionContextManager 
executionContextManager) {
-        this(tenantService, securityService, executionContextManager, () -> 
AdminTenantConfig.DEFAULT_ADMIN_TENANT_ID);
+        this(tenantService, securityService, executionContextManager, () -> 
AdminTenantConfig.DEFAULT_ADMIN_TENANT_ID, null);
     }
 
     public GraphQLServletSecurityValidator(TenantService tenantService,
                                          SecurityService securityService,
                                          ExecutionContextManager 
executionContextManager,
                                          AdminTenantConfig adminTenantConfig) {
+        this(tenantService, securityService, executionContextManager, 
adminTenantConfig, null);
+    }
+
+    public GraphQLServletSecurityValidator(TenantService tenantService,
+                                         SecurityService securityService,
+                                         ExecutionContextManager 
executionContextManager,
+                                         AdminTenantConfig adminTenantConfig,
+                                         GraphQLLimitsConfig limitsConfig) {
         this.parser = new Parser();
         this.tenantService = tenantService;
         this.securityService = securityService;
@@ -87,6 +98,7 @@ public class GraphQLServletSecurityValidator {
         this.adminTenantConfig = adminTenantConfig != null
                 ? adminTenantConfig
                 : () -> AdminTenantConfig.DEFAULT_ADMIN_TENANT_ID;
+        this.limitsConfig = limitsConfig;
     }
 
     /**
@@ -129,35 +141,45 @@ public class GraphQLServletSecurityValidator {
         // subject left behind by earlier work on this thread can never make 
this request trusted.
         securityService.clearCurrentSubject();
 
-        if (isPublicOperation(query, operationName)) {
-            // For public operations, check API key
-            String apiKey = req.getHeader("X-Unomi-Api-Key");
-            if (apiKey != null) {
-                Tenant tenant = tenantService.getTenantByApiKey(apiKey, 
ApiKey.ApiKeyType.PUBLIC);
-                if (tenant != null) {
-                    // Set the security context for public API key
-                    Subject subject = 
securityService.createSubject(tenant.getItemId(), false);
-                    securityService.setCurrentSubject(subject);
-                    
executionContextManager.setCurrentContext(executionContextManager.createContext(tenant.getItemId()));
-                    return true;
-                }
-            }
+        // Refuse oversized documents before any parse (including the 
public-operation classifier).
+        if (!GraphQLRequestLimits.checkQueryLength(query, limitsConfig, res)) {
+            return false;
         }
 
-        if (req.getHeader("Authorization") == null) {
+        // Valid credentials are accepted first, so an admin call never pays 
for a public-operation parse.
+        boolean hasAuthorization = req.getHeader("Authorization") != null;
+        // A failed attempt leaves no subject behind: every refusal in 
authenticateBasic clears it.
+        if (hasAuthorization && isAuthenticatedUser(req)) {
+            return true;
+        }
+
+        // A stray or stale Basic header (a cached browser credential, an 
injecting proxy) must not turn
+        // a public API key call into a 401, as on the REST public endpoints.
+        if (isPublicApiKeyCall(query, operationName, req)) {
+            return true;
+        }
+
+        if (!hasAuthorization || !sendTenantRejection(req, res)) {
             res.addHeader("WWW-Authenticate", "Basic realm=\"karaf\"");
             res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
-            return false;
         }
+        return false;
+    }
 
-        if (isAuthenticatedUser(req)) {
-            return true;
-        } else {
-            if (!sendTenantRejection(req, res)) {
-                res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
-            }
+    /** Sets the tenant context and returns {@code true} for a public 
operation with a valid public API key. */
+    private boolean isPublicApiKeyCall(String query, String operationName, 
HttpServletRequest req) {
+        String apiKey = req.getHeader("X-Unomi-Api-Key");
+        if (apiKey == null || !isPublicOperation(query, operationName)) {
             return false;
         }
+        Tenant tenant = tenantService.getTenantByApiKey(apiKey, 
ApiKey.ApiKeyType.PUBLIC);
+        if (tenant == null) {
+            return false;
+        }
+        Subject subject = securityService.createSubject(tenant.getItemId(), 
false);
+        securityService.setCurrentSubject(subject);
+        
executionContextManager.setCurrentContext(executionContextManager.createContext(tenant.getItemId()));
+        return true;
     }
 
     /**
diff --git a/graphql/cxs-impl/src/main/resources/org.apache.unomi.graphql.cfg 
b/graphql/cxs-impl/src/main/resources/org.apache.unomi.graphql.cfg
new file mode 100644
index 000000000..ad1a495e2
--- /dev/null
+++ b/graphql/cxs-impl/src/main/resources/org.apache.unomi.graphql.cfg
@@ -0,0 +1,25 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Maximum GraphQL query string length in characters (0 disables).
+max.query.length.chars=${org.apache.unomi.graphql.max.query.length.chars:-262144}
+# Maximum GraphQL HTTP POST body size in bytes (0 disables).
+max.request.body.bytes=${org.apache.unomi.graphql.max.request.body.bytes:-524288}
+# Maximum GraphQL query depth (0 disables).
+max.query.depth=${org.apache.unomi.graphql.max.query.depth:-24}
+# Maximum GraphQL query complexity (0 disables).
+max.query.complexity=${org.apache.unomi.graphql.max.query.complexity:-3000}
diff --git 
a/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/limits/GraphQLRequestLimitsTest.java
 
b/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/limits/GraphQLRequestLimitsTest.java
new file mode 100644
index 000000000..ae65a92df
--- /dev/null
+++ 
b/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/limits/GraphQLRequestLimitsTest.java
@@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.unomi.graphql.limits;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+class GraphQLRequestLimitsTest {
+
+    @Mock
+    private GraphQLLimitsConfig limits;
+    @Mock
+    private HttpServletResponse response;
+
+    @Test
+    void checkQueryLength_allowsWhenLimitsMissing() throws IOException {
+        assertTrue(GraphQLRequestLimits.checkQueryLength("query { x }", null, 
response));
+        verify(response, 
never()).sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
+                "GraphQL query exceeds the configured size limit");
+    }
+
+    @Test
+    void checkQueryLength_rejectsWhenOverLimit() throws IOException {
+        when(limits.getMaxQueryLengthChars()).thenReturn(8);
+
+        assertFalse(GraphQLRequestLimits.checkQueryLength("0123456789", 
limits, response));
+        
verify(response).sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
+                "GraphQL query exceeds the configured size limit");
+    }
+
+    @Test
+    void checkQueryLength_allowsWhenAtLimit() throws IOException {
+        when(limits.getMaxQueryLengthChars()).thenReturn(5);
+
+        assertTrue(GraphQLRequestLimits.checkQueryLength("12345", limits, 
response));
+        verify(response, 
never()).sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
+                "GraphQL query exceeds the configured size limit");
+    }
+
+    @Test
+    void checkQueryLength_disabledWhenZero() throws IOException {
+        when(limits.getMaxQueryLengthChars()).thenReturn(0);
+
+        assertTrue(GraphQLRequestLimits.checkQueryLength("anything-long", 
limits, response));
+        verify(response, 
never()).sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
+                "GraphQL query exceeds the configured size limit");
+    }
+
+    @Test
+    void checkContentLength_rejectsWhenOverLimit() throws IOException {
+        when(limits.getMaxRequestBodyBytes()).thenReturn(100);
+
+        assertFalse(GraphQLRequestLimits.checkContentLength(101, limits, 
response));
+        
verify(response).sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
+                "GraphQL request body exceeds the configured size limit");
+    }
+
+    /** No declared length to refuse early; {@link 
GraphQLRequestLimits#boundedBody} caps such a body. */
+    @Test
+    void checkContentLength_skipsWhenContentLengthUnknown() throws IOException 
{
+        when(limits.getMaxRequestBodyBytes()).thenReturn(100);
+
+        assertTrue(GraphQLRequestLimits.checkContentLength(-1, limits, 
response));
+        verify(response, 
never()).sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
+                "GraphQL request body exceeds the configured size limit");
+    }
+
+    /** A body within the limit reads through unchanged. */
+    @Test
+    void boundedBody_readsBodyWithinLimit() throws IOException {
+        when(limits.getMaxRequestBodyBytes()).thenReturn(10);
+        byte[] body = "0123456789".getBytes();
+
+        InputStream in = GraphQLRequestLimits.boundedBody(new 
ByteArrayInputStream(body), limits);
+
+        assertArrayEquals(body, in.readAllBytes());
+    }
+
+    /** A body without Content-Length (chunked) is still capped while it is 
read. */
+    @Test
+    void boundedBody_failsOnceOverLimit() {
+        when(limits.getMaxRequestBodyBytes()).thenReturn(10);
+        InputStream in = GraphQLRequestLimits.boundedBody(new 
ByteArrayInputStream(new byte[11]), limits);
+
+        assertThrows(GraphQLRequestLimits.BodyTooLargeException.class, 
in::readAllBytes);
+    }
+
+    /** Single-byte reads are counted too. */
+    @Test
+    void boundedBody_countsSingleByteReads() throws IOException {
+        when(limits.getMaxRequestBodyBytes()).thenReturn(2);
+        InputStream in = GraphQLRequestLimits.boundedBody(new 
ByteArrayInputStream(new byte[3]), limits);
+
+        in.read();
+        in.read();
+        assertThrows(GraphQLRequestLimits.BodyTooLargeException.class, 
in::read);
+    }
+
+    @Test
+    void boundedBody_unwrappedWhenDisabledOrMissing() {
+        InputStream raw = new ByteArrayInputStream(new byte[0]);
+        assertSame(raw, GraphQLRequestLimits.boundedBody(raw, null));
+
+        when(limits.getMaxRequestBodyBytes()).thenReturn(0);
+        assertSame(raw, GraphQLRequestLimits.boundedBody(raw, limits));
+    }
+}
diff --git 
a/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/schema/GraphQLLimitsInstrumentationTest.java
 
b/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/schema/GraphQLLimitsInstrumentationTest.java
new file mode 100644
index 000000000..898a146fc
--- /dev/null
+++ 
b/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/schema/GraphQLLimitsInstrumentationTest.java
@@ -0,0 +1,130 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.unomi.graphql.schema;
+
+import graphql.ExecutionResult;
+import graphql.GraphQL;
+import graphql.execution.instrumentation.Instrumentation;
+import graphql.introspection.IntrospectionQuery;
+import graphql.schema.GraphQLSchema;
+import graphql.schema.idl.RuntimeWiring;
+import graphql.schema.idl.SchemaGenerator;
+import graphql.schema.idl.SchemaParser;
+import org.apache.unomi.graphql.limits.GraphQLLimitsConfig;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Runs real graphql-java execution with the depth and complexity 
instrumentation that
+ * {@link GraphQLSchemaUpdater} installs, using the shipped default limits.
+ */
+class GraphQLLimitsInstrumentationTest {
+
+    private static final String SDL = "type Query { node: Node }\n"
+            + "type Node { id: ID, child: Node, children: [Node] }";
+
+    /** The shipped defaults (no configuration applied yet). */
+    private final GraphQLLimitsConfig defaults = new GraphQLLimitsConfig();
+
+    private static GraphQL graphQL(Instrumentation instrumentation) {
+        GraphQLSchema schema = new SchemaGenerator().makeExecutableSchema(
+                new SchemaParser().parse(SDL), 
RuntimeWiring.newRuntimeWiring().build());
+        GraphQL.Builder builder = GraphQL.newGraphQL(schema);
+        if (instrumentation != null) {
+            builder.instrumentation(instrumentation);
+        }
+        return builder.build();
+    }
+
+    private ExecutionResult runWithDefaults(String query) {
+        return 
graphQL(GraphQLSchemaUpdater.buildInstrumentation(defaults)).execute(query);
+    }
+
+    /** GraphiQL sends the standard introspection query; the defaults must 
leave it working. */
+    @Test
+    void defaults_allowIntrospection() {
+        ExecutionResult result = 
runWithDefaults(IntrospectionQuery.INTROSPECTION_QUERY);
+
+        assertTrue(result.getErrors().isEmpty(), () -> "introspection refused: 
" + result.getErrors());
+    }
+
+    @Test
+    void defaults_allowOrdinaryQuery() {
+        ExecutionResult result = runWithDefaults("{ node { id child { id 
children { id } } } }");
+
+        assertTrue(result.getErrors().isEmpty(), () -> "query refused: " + 
result.getErrors());
+    }
+
+    @Test
+    void defaults_refuseQueryDeeperThanLimit() {
+        ExecutionResult result = 
runWithDefaults(nested(defaults.getMaxQueryDepth() + 5));
+
+        assertFalse(result.getErrors().isEmpty(), "an over-deep query must be 
refused");
+    }
+
+    /** Many aliased fields at shallow depth: refused by complexity, not by 
depth. */
+    @Test
+    void defaults_refuseQueryMoreComplexThanLimit() {
+        StringBuilder query = new StringBuilder("{");
+        int aliases = defaults.getMaxQueryComplexity() / 2 + 10;  // each 
alias costs 2 (node + id)
+        for (int i = 0; i < aliases; i++) {
+            query.append(" a").append(i).append(": node { id }");
+        }
+        query.append(" }");
+
+        ExecutionResult result = runWithDefaults(query.toString());
+
+        assertFalse(result.getErrors().isEmpty(), "an over-complex query must 
be refused");
+    }
+
+    /** Without the instrumentation the same deep query runs, so the refusal 
above comes from it. */
+    @Test
+    void withoutInstrumentation_deepQueryRuns() {
+        ExecutionResult result = 
graphQL(null).execute(nested(defaults.getMaxQueryDepth() + 5));
+
+        assertTrue(result.getErrors().isEmpty(), () -> "unexpected errors: " + 
result.getErrors());
+    }
+
+    /** Zero disables a check; with both disabled no instrumentation is 
installed. */
+    @Test
+    void zeroDisablesBothLimits() {
+        GraphQLLimitsConfig disabled = mock(GraphQLLimitsConfig.class);
+        when(disabled.getMaxQueryDepth()).thenReturn(0);
+        when(disabled.getMaxQueryComplexity()).thenReturn(0);
+
+        assertNull(GraphQLSchemaUpdater.buildInstrumentation(disabled));
+        assertNull(GraphQLSchemaUpdater.buildInstrumentation(null));
+    }
+
+    /** { node { child { child ... { id } } } } with the given depth of 
selections. */
+    private static String nested(int depth) {
+        StringBuilder query = new StringBuilder("{ node {");
+        for (int i = 1; i < depth; i++) {
+            query.append(" child {");
+        }
+        query.append(" id");
+        for (int i = 0; i < depth; i++) {
+            query.append(" }");
+        }
+        return query.append(" }").toString();
+    }
+}
diff --git 
a/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/GraphQLServletTest.java
 
b/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/GraphQLServletTest.java
index fcf8259b6..b4494292e 100644
--- 
a/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/GraphQLServletTest.java
+++ 
b/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/GraphQLServletTest.java
@@ -19,6 +19,7 @@ package org.apache.unomi.graphql.servlet;
 
 import org.apache.unomi.api.security.SecurityService;
 import org.apache.unomi.api.services.ExecutionContextManager;
+import org.apache.unomi.graphql.limits.GraphQLLimitsConfig;
 import org.apache.unomi.graphql.servlet.auth.GraphQLServletSecurityValidator;
 import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
 import org.apache.unomi.graphql.schema.GraphQLSchemaUpdater;
@@ -30,10 +31,14 @@ import org.mockito.InOrder;
 import org.mockito.Mock;
 import org.mockito.junit.jupiter.MockitoExtension;
 
+import javax.servlet.ReadListener;
 import javax.servlet.ServletException;
+import javax.servlet.ServletInputStream;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import java.io.ByteArrayInputStream;
 import java.io.IOException;
+import java.nio.charset.StandardCharsets;
 import java.util.Collections;
 import java.util.Enumeration;
 import java.util.concurrent.atomic.AtomicBoolean;
@@ -45,6 +50,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.isNull;
 import static org.mockito.ArgumentMatchers.contains;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.inOrder;
@@ -307,6 +313,94 @@ class GraphQLServletTest {
         verify(response, 
never()).setHeader(eq("Access-Control-Allow-Credentials"), anyString());
     }
 
+    private GraphQLLimitsConfig bodyLimit(int maxBytes) {
+        GraphQLLimitsConfig limits = mock(GraphQLLimitsConfig.class);
+        when(limits.getMaxRequestBodyBytes()).thenReturn(maxBytes);
+        return limits;
+    }
+
+    /** A declared Content-Length over the limit is refused before the body is 
read. */
+    @Test
+    void doPost_declaredOversizedBody_is413WithoutReading() throws Exception {
+        servlet.setLimitsConfig(bodyLimit(100));
+        when(request.getContentLength()).thenReturn(101);
+
+        servlet.doPost(request, response);
+
+        
verify(response).sendError(eq(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE), 
anyString());
+        verify(request, never()).getInputStream();
+        verifyNoInteractions(validator);
+    }
+
+    /**
+     * A chunked body declares no Content-Length; it is still refused once it 
goes over the limit, without
+     * reading the rest of it and before authentication.
+     */
+    @Test
+    void doPost_chunkedOversizedBody_is413AndStopsReading() throws Exception {
+        servlet.setLimitsConfig(bodyLimit(1024));
+        when(request.getContentLength()).thenReturn(-1);
+        byte[] body = ("{\"query\":\"" + "a".repeat(1024 * 1024) + 
"\"}").getBytes(StandardCharsets.UTF_8);
+        BodyStream stream = new BodyStream(body);
+        when(request.getInputStream()).thenReturn(stream);
+
+        servlet.doPost(request, response);
+
+        
verify(response).sendError(eq(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE), 
anyString());
+        verifyNoInteractions(validator);
+        assertTrue(stream.remaining() > body.length / 2, "the body must not be 
read to the end");
+    }
+
+    /** A chunked body within the limit is parsed and handed to authentication 
as before. */
+    @Test
+    void doPost_chunkedBodyWithinLimit_reachesValidator() throws Exception {
+        servlet.setLimitsConfig(bodyLimit(1024));
+        when(request.getContentLength()).thenReturn(-1);
+        when(request.getInputStream()).thenReturn(
+                new BodyStream("{\"query\":\"{ __typename 
}\"}".getBytes(StandardCharsets.UTF_8)));
+        when(validator.validate(eq("{ __typename }"), isNull(), eq(request), 
eq(response))).thenReturn(false);
+
+        servlet.doPost(request, response);
+
+        verify(validator).validate(eq("{ __typename }"), isNull(), 
eq(request), eq(response));
+        verify(response, 
never()).sendError(eq(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE), 
anyString());
+    }
+
+    /** A request body as the container hands it over. */
+    private static final class BodyStream extends ServletInputStream {
+        private final ByteArrayInputStream in;
+
+        BodyStream(byte[] body) {
+            this.in = new ByteArrayInputStream(body);
+        }
+
+        int remaining() {
+            return in.available();
+        }
+
+        @Override
+        public int read() {
+            return in.read();
+        }
+
+        @Override
+        public int read(byte[] b, int off, int len) {
+            return in.read(b, off, len);
+        }
+
+        public boolean isFinished() {
+            return in.available() == 0;
+        }
+
+        public boolean isReady() {
+            return true;
+        }
+
+        public void setReadListener(ReadListener readListener) {
+            throw new UnsupportedOperationException();
+        }
+    }
+
     private static final class TrackingGraphQLServlet extends GraphQLServlet {
         private final AtomicBoolean nonUpgradeCalled = new 
AtomicBoolean(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 2def7c0fa..08dd33580 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
@@ -25,6 +25,7 @@ import org.apache.unomi.api.tenants.AdminTenantConfig;
 import org.apache.unomi.api.tenants.ApiKey;
 import org.apache.unomi.api.tenants.Tenant;
 import org.apache.unomi.api.tenants.TenantService;
+import org.apache.unomi.graphql.limits.GraphQLLimitsConfig;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
@@ -84,6 +85,8 @@ class GraphQLServletSecurityValidatorTest {
     private HttpServletRequest request;
     @Mock
     private HttpServletResponse response;
+    @Mock
+    private GraphQLLimitsConfig limitsConfig;
 
     private GraphQLServletSecurityValidator validator;
 
@@ -91,9 +94,10 @@ class GraphQLServletSecurityValidatorTest {
     void setUp() {
         previousConfiguration = Configuration.getConfiguration();
         Configuration.setConfiguration(new 
AlwaysSucceedingKarafConfiguration());
+        
lenient().when(limitsConfig.getMaxQueryLengthChars()).thenReturn(262144);
         validator = new GraphQLServletSecurityValidator(
                 tenantService, securityService, executionContextManager,
-                () -> AdminTenantConfig.DEFAULT_ADMIN_TENANT_ID);
+                () -> AdminTenantConfig.DEFAULT_ADMIN_TENANT_ID, limitsConfig);
         // Back request attributes with a map, as a servlet container does.
         Map<String, Object> attributes = new HashMap<>();
         lenient().doAnswer(invocation -> 
attributes.put(invocation.getArgument(0), invocation.getArgument(1)))
@@ -429,6 +433,7 @@ class GraphQLServletSecurityValidatorTest {
     void validate_legitimatePublicOperation_isAuthenticatedWithPublicApiKey() 
throws IOException {
         Tenant tenant = new Tenant();
         tenant.setItemId("pub-tenant");
+        when(request.getHeader("Authorization")).thenReturn(null);
         
when(request.getHeader("X-Unomi-Api-Key")).thenReturn("public-api-key");
         when(tenantService.getTenantByApiKey("public-api-key", 
ApiKey.ApiKeyType.PUBLIC)).thenReturn(tenant);
         when(securityService.createSubject("pub-tenant", 
false)).thenReturn(new Subject());
@@ -442,6 +447,93 @@ class GraphQLServletSecurityValidatorTest {
         verify(executionContextManager).setCurrentContext(context);
     }
 
+    @Test
+    void validate_rejectsOversizedQueryBeforeAuth() throws IOException {
+        when(limitsConfig.getMaxQueryLengthChars()).thenReturn(16);
+
+        boolean authenticated = validator.validate(
+                "query { cdp { getProfile(profileID:{id:\"x\"}) { id } } }", 
null, request, response);
+
+        assertFalse(authenticated);
+        
verify(response).sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
+                "GraphQL query exceeds the configured size limit");
+        verify(securityService, never()).setCurrentSubject(any());
+        verify(request, never()).getHeader("Authorization");
+        verify(tenantService, never()).getTenantByApiKey(anyString(), any());
+    }
+
+    @Test
+    void validate_withAuthorization_doesNotTryPublicApiKey() throws 
IOException {
+        givenAdministratorRole();
+        givenDefaultTenant();
+        when(securityService.hasSystemAccess()).thenReturn(true);
+        when(request.getHeader("Authorization")).thenReturn(BASIC_AUTH);
+        when(tenantService.getTenantByApiKey(any(), 
eq(ApiKey.ApiKeyType.PRIVATE))).thenReturn(null);
+        
lenient().when(request.getHeader("X-Unomi-Api-Key")).thenReturn("public-api-key");
+
+        boolean authenticated = validator.validate(
+                "query { cdp { getProfile(profileID:{id:\"x\"}) { id } } }", 
null, request, response);
+
+        assertTrue(authenticated);
+        verify(tenantService, never()).getTenantByApiKey(eq("public-api-key"), 
eq(ApiKey.ApiKeyType.PUBLIC));
+    }
+
+    /**
+     * A stray or stale Basic header (cached browser credential, injecting 
proxy) must not turn a valid
+     * public API key call into a 401: the public path is still tried, as on 
the REST public endpoints.
+     */
+    @Test
+    void validate_withFailingAuthorization_fallsBackToPublicApiKey() throws 
IOException {
+        Tenant tenant = new Tenant();
+        tenant.setItemId("pub-tenant");
+        when(request.getHeader("Authorization")).thenReturn("Basic 
not-valid-base64");
+        
when(request.getHeader("X-Unomi-Api-Key")).thenReturn("public-api-key");
+        when(tenantService.getTenantByApiKey("public-api-key", 
ApiKey.ApiKeyType.PUBLIC)).thenReturn(tenant);
+        Subject publicSubject = new Subject();
+        when(securityService.createSubject("pub-tenant", 
false)).thenReturn(publicSubject);
+        ExecutionContext context = new ExecutionContext("pub-tenant", null, 
null);
+        
when(executionContextManager.createContext("pub-tenant")).thenReturn(context);
+
+        boolean authenticated = validator.validate(
+                "query { cdp { getProfile(profileID:{id:\"x\"}) { id } } }", 
null, request, response);
+
+        assertTrue(authenticated);
+        verify(securityService).setCurrentSubject(publicSubject);
+        verify(executionContextManager).setCurrentContext(context);
+        verify(response, never()).sendError(anyInt());
+    }
+
+    /** The fallback only covers public operations: a privileged one with a 
failing Basic header stays 401. */
+    @Test
+    void validate_withFailingAuthorization_andPrivilegedOperation_isRejected() 
throws IOException {
+        when(request.getHeader("Authorization")).thenReturn("Basic 
not-valid-base64");
+        
lenient().when(request.getHeader("X-Unomi-Api-Key")).thenReturn("public-api-key");
+
+        boolean authenticated = validator.validate(
+                "query { cdp { findProfiles(first:10) { edges { node { id } } 
} } }", null, request, response);
+
+        assertFalse(authenticated);
+        verify(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
+        verify(securityService, never()).setCurrentSubject(any());
+        verify(tenantService, never()).getTenantByApiKey(anyString(), 
eq(ApiKey.ApiKeyType.PUBLIC));
+    }
+
+    /** A failing Basic header with an unknown public key is still a 401, 
never public access. */
+    @Test
+    void validate_withFailingAuthorization_andUnknownPublicKey_isRejected() 
throws IOException {
+        when(request.getHeader("Authorization")).thenReturn("Basic 
not-valid-base64");
+        when(request.getHeader("X-Unomi-Api-Key")).thenReturn("unknown-key");
+        when(tenantService.getTenantByApiKey("unknown-key", 
ApiKey.ApiKeyType.PUBLIC)).thenReturn(null);
+
+        boolean authenticated = validator.validate(
+                "query { cdp { getProfile(profileID:{id:\"x\"}) { id } } }", 
null, request, response);
+
+        assertFalse(authenticated);
+        verify(response).addHeader("WWW-Authenticate", "Basic 
realm=\"karaf\"");
+        verify(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
+        verify(securityService, never()).setCurrentSubject(any());
+    }
+
     private void assertNotPublic(String query, String operationName) throws 
IOException {
         assertFalse(validator.validate(query, operationName, request, 
response),
                 "Expected document to be denied for a public API key: " + 
query);
diff --git a/graphql/karaf-feature/src/main/feature/feature.xml 
b/graphql/karaf-feature/src/main/feature/feature.xml
index 20f9aa5f8..870c0bf39 100644
--- a/graphql/karaf-feature/src/main/feature/feature.xml
+++ b/graphql/karaf-feature/src/main/feature/feature.xml
@@ -53,6 +53,7 @@
         <bundle 
start="false">mvn:org.eclipse.jetty.websocket/websocket-client/${jetty.version}</bundle>
         <!-- jetty-util-ajax is not used by GraphQL WebSocket implementation 
-->
         <!-- ${servlet.spec.groupId}/${servlet.spec.artifactId} (servlet-api) 
is already provided by war feature (via Pax Web) in unomi-base, no need to 
redeclare -->
+        <configfile 
finalname="/etc/org.apache.unomi.graphql.cfg">mvn:org.apache.unomi/cdp-graphql-api-impl/${project.version}/cfg/unomicfg</configfile>
         <bundle 
start="false">mvn:org.apache.unomi/cdp-graphql-api-impl/${project.version}</bundle>
         <bundle 
start="false">mvn:org.apache.unomi/unomi-graphql-ui/${project.version}</bundle>
     </feature>
diff --git a/manual/src/main/asciidoc/configuration.adoc 
b/manual/src/main/asciidoc/configuration.adoc
index cef9b3e48..78f886548 100644
--- a/manual/src/main/asciidoc/configuration.adoc
+++ b/manual/src/main/asciidoc/configuration.adoc
@@ -759,6 +759,26 @@ Example: `https://admin.example.com`. Same-origin 
deployments (a reverse proxy s
 
 This list covers HTTP requests only. GraphQL subscriptions over WebSocket 
accept only handshakes from the same host as Unomi (or with no `Origin`), 
whether or not the origin is listed here.
 
+[[_graphql_query_limits]]
+==== GraphQL query limits
+
+GraphQL under `/graphql` bounds document size and analysis cost. Configure 
them in `etc/custom.system.properties` (or the matching environment variables); 
they are applied through `etc/org.apache.unomi.graphql.cfg`. A value of `0` 
turns that check off.
+
+[source]
+----
+org.apache.unomi.graphql.max.query.length.chars=${env:UNOMI_GRAPHQL_MAX_QUERY_LENGTH_CHARS:-262144}
+org.apache.unomi.graphql.max.request.body.bytes=${env:UNOMI_GRAPHQL_MAX_REQUEST_BODY_BYTES:-524288}
+org.apache.unomi.graphql.max.query.depth=${env:UNOMI_GRAPHQL_MAX_QUERY_DEPTH:-24}
+org.apache.unomi.graphql.max.query.complexity=${env:UNOMI_GRAPHQL_MAX_QUERY_COMPLEXITY:-3000}
+----
+
+The defaults leave GraphiQL introspection and the public `getProfile` / 
`processEvents` fields usable. Oversized requests are refused with HTTP 413 
before the document is parsed. Changes to these settings apply to HTTP requests 
as soon as the configuration is updated.
+
+GraphQL subscriptions over WebSocket are handled differently:
+
+* They keep the depth and complexity limits in force when the GraphQL servlet 
started. Restart Unomi (or the GraphQL bundle) to apply new values to them.
+* The length and body size limits do not apply to them. A subscription message 
is limited to 1 MB by the WebSocket buffer, and a socket must authenticate 
before it can run anything.
+
 === Scripting security
 
 ==== Multi-layer scripting filtering system
diff --git a/manual/src/main/asciidoc/migrations/migrate-3.0-to-4.0.adoc 
b/manual/src/main/asciidoc/migrations/migrate-3.0-to-4.0.adoc
index 2eef06f6e..82b5fe67d 100644
--- a/manual/src/main/asciidoc/migrations/migrate-3.0-to-4.0.adoc
+++ b/manual/src/main/asciidoc/migrations/migrate-3.0-to-4.0.adoc
@@ -467,6 +467,10 @@ In addition to tenant API keys, Unomi 4.0 hardens several 
contracts that can bre
 |Admin REST and GraphQL answered any origin with credentialed CORS, so a page 
on another site could reuse the operator's browser credentials to read admin 
responses.
 |Only origins listed in `org.apache.unomi.admin.cors.allowedOrigins` 
(`UNOMI_ADMIN_CORS_ALLOWED_ORIGINS`) get credentialed CORS on admin REST and 
GraphQL. The default is empty. A same-origin admin UI needs no change. See 
<<_admin_cors_origins,Admin UI origins>>.
 
+|GraphQL query limits
+|GraphQL documents had no server-side size, depth, or complexity bound beyond 
container limits.
+|GraphQL under `/graphql` applies configurable length, body size, depth, and 
complexity limits (`org.apache.unomi.graphql.*`). Defaults leave GraphiQL 
introspection and the public `getProfile` / `processEvents` fields usable. See 
<<_graphql_query_limits,GraphQL query limits>>.
+
 |Profile cookie `HttpOnly`
 |Often defaulted to `false` (JS could read `document.cookie`)
 |Default **`true`**. Prefer `profileId` from the JSON response. Opt out with 
`org.apache.unomi.profile.cookie.httpOnly=false` only if you accept the 
tradeoff.
diff --git a/package/pom.xml b/package/pom.xml
index eb3debe16..5632a5bf4 100644
--- a/package/pom.xml
+++ b/package/pom.xml
@@ -294,6 +294,14 @@
                                     
<outputDirectory>${project.build.directory}/assembly/etc</outputDirectory>
                                     
<destFileName>org.apache.unomi.router.cfg</destFileName>
                                 </artifactItem>
+                                <artifactItem>
+                                    <groupId>org.apache.unomi</groupId>
+                                    
<artifactId>cdp-graphql-api-impl</artifactId>
+                                    <classifier>unomicfg</classifier>
+                                    <type>cfg</type>
+                                    
<outputDirectory>${project.build.directory}/assembly/etc</outputDirectory>
+                                    
<destFileName>org.apache.unomi.graphql.cfg</destFileName>
+                                </artifactItem>
                             </artifactItems>
                         </configuration>
                     </execution>
diff --git a/package/src/main/resources/etc/custom.system.properties 
b/package/src/main/resources/etc/custom.system.properties
index 29c4664ee..e82a77336 100644
--- a/package/src/main/resources/etc/custom.system.properties
+++ b/package/src/main/resources/etc/custom.system.properties
@@ -354,6 +354,11 @@ 
org.apache.unomi.public.cors.tenantOrigins=${env:UNOMI_PUBLIC_CORS_TENANT_ORIGIN
 # Example: https://admin.example.com
 # Leave empty (the default) so no other origin may reuse the operator's 
browser credentials cross-origin.
 
org.apache.unomi.admin.cors.allowedOrigins=${env:UNOMI_ADMIN_CORS_ALLOWED_ORIGINS:-}
+# GraphQL document and analysis bounds (0 disables a given check). Defaults 
leave GraphiQL introspection usable.
+org.apache.unomi.graphql.max.query.length.chars=${env:UNOMI_GRAPHQL_MAX_QUERY_LENGTH_CHARS:-262144}
+org.apache.unomi.graphql.max.request.body.bytes=${env:UNOMI_GRAPHQL_MAX_REQUEST_BODY_BYTES:-524288}
+org.apache.unomi.graphql.max.query.depth=${env:UNOMI_GRAPHQL_MAX_QUERY_DEPTH:-24}
+org.apache.unomi.graphql.max.query.complexity=${env:UNOMI_GRAPHQL_MAX_QUERY_COMPLEXITY:-3000}
 #Allowed profile download formats, actually only csv (horizontal and 
vertical), json, text and yaml are allowed.
 
org.apache.unomi.profile.download.formats=${env:UNOMI_PROFILE_DOWNLOAD_FORMATS:-csv,yaml,json,text}
 # This setting allow for request size (Content-length) protection. Checking 
that the requests do not exceed the limit.

Reply via email to