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 06895c2a6 Refuse GraphQL mutations and subscriptions over HTTP GET
(#954)
06895c2a6 is described below
commit 06895c2a60ec9db3c93baa16a604a9ad3a591bbd
Author: Serge Huber <[email protected]>
AuthorDate: Thu Nov 12 08:39:01 2026 +0100
Refuse GraphQL mutations and subscriptions over HTTP GET (#954)
Co-authored-by: Claude Opus 5.5 <[email protected]>
---
THREAT_MODEL.md | 1 +
.../unomi/graphql/servlet/GraphQLServlet.java | 142 ++++++++++++++++
.../GraphQLServletReadOnlyOperationTest.java | 119 +++++++++++++
.../unomi/graphql/servlet/GraphQLServletTest.java | 184 +++++++++++++++++++++
manual/src/main/asciidoc/configuration.adoc | 2 +
.../asciidoc/migrations/migrate-3.0-to-4.0.adoc | 4 +
6 files changed, 452 insertions(+)
diff --git a/THREAT_MODEL.md b/THREAT_MODEL.md
index a02e64403..063168392 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 HTTP methods:** GET may run queries only, and not
`getProfile(createIfMissing: true)`, which saves a profile; mutations,
subscriptions and that query must use POST with `Content-Type:
application/json`.
- **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/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 d08140a60..17c4ffd95 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
@@ -21,6 +21,21 @@ import graphql.ExecutionInput;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.introspection.IntrospectionQuery;
+import graphql.language.Argument;
+import graphql.language.BooleanValue;
+import graphql.language.Document;
+import graphql.language.Field;
+import graphql.language.FragmentDefinition;
+import graphql.language.FragmentSpread;
+import graphql.language.InlineFragment;
+import graphql.language.NullValue;
+import graphql.language.OperationDefinition;
+import graphql.language.Selection;
+import graphql.language.SelectionSet;
+import graphql.language.Value;
+import graphql.language.VariableDefinition;
+import graphql.language.VariableReference;
+import graphql.parser.Parser;
import org.apache.unomi.api.ExecutionContext;
import org.apache.unomi.api.security.SecurityService;
import org.apache.unomi.api.services.AdminCorsService;
@@ -49,15 +64,23 @@ import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
+import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
import java.util.Map;
+import java.util.Set;
@Component(service = GraphQLServlet.class)
public class GraphQLServlet extends WebSocketServlet {
private static final Logger LOGGER =
LoggerFactory.getLogger(GraphQLServlet.class);
+ /** Query argument that saves a profile when it is missing
(cdp.getProfile). */
+ private static final String CREATE_IF_MISSING = "createIfMissing";
+
public static final String SCHEMA_URL = "/schema.json";
private GraphQLSchemaUpdater graphQLSchemaUpdater;
@@ -322,9 +345,18 @@ public class GraphQLServlet extends WebSocketServlet {
variables =
GraphQLObjectMapper.getInstance().readValue(variableStr, typeRef);
}
+ // Authenticate (and apply the size limit) before parsing the
document for the method check.
if (!validator.validate(query, operationName, req, resp)) {
return;
}
+ // GET is easy for a browser to issue cross-origin without a
preflight. Only queries that write
+ // nothing: getProfile(createIfMissing: true) saves a profile, so
it needs POST too.
+ if (!isReadOnlyOperation(query, operationName, variables)) {
+ resp.setHeader("Allow", "POST");
+ resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
+ "GraphQL mutations, subscriptions and createIfMissing
are not allowed over HTTP GET");
+ return;
+ }
setupCORSHeaders(req, resp);
executeGraphQLRequest(resp, query, operationName, variables);
} finally {
@@ -337,6 +369,13 @@ public class GraphQLServlet extends WebSocketServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
LOGGER.debug("GraphQLServlet doPost called with request: {}",
req.getRequestURI());
try {
+ // Require JSON so a simple cross-site form post cannot change
state.
+ final String contentType = req.getContentType();
+ if (contentType == null ||
!contentType.toLowerCase(Locale.ROOT).startsWith("application/json")) {
+ resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
+ "GraphQL requests must use the application/json
content type");
+ return;
+ }
if
(!GraphQLRequestLimits.checkContentLength(req.getContentLength(), limitsConfig,
resp)) {
return;
}
@@ -384,6 +423,109 @@ public class GraphQLServlet extends WebSocketServlet {
}
}
+ static boolean isReadOnlyOperation(final String query, final String
operationName) {
+ return isReadOnlyOperation(query, operationName,
Collections.emptyMap());
+ }
+
+ /**
+ * Whether the operation that would run for this document is a query that
writes nothing. Mutations,
+ * subscriptions, documents that cannot be parsed, and queries that set
{@code createIfMissing}
+ * (which saves a profile) are treated as non-read-only.
+ */
+ static boolean isReadOnlyOperation(final String query, final String
operationName, final Map<String, Object> variables) {
+ if (query == null || query.trim().length() == 0) {
+ return true;
+ }
+ try {
+ final Document document = new Parser().parseDocument(query);
+ final List<OperationDefinition> operations =
document.getDefinitionsOfType(OperationDefinition.class);
+ OperationDefinition operationToExecute = null;
+ if (operationName != null && operationName.trim().length() > 0) {
+ for (OperationDefinition operation : operations) {
+ if (operationName.equals(operation.getName())) {
+ operationToExecute = operation;
+ break;
+ }
+ }
+ } else if (!operations.isEmpty()) {
+ operationToExecute = operations.get(0);
+ }
+ if (operationToExecute == null) {
+ return true;
+ }
+ if
(!OperationDefinition.Operation.QUERY.equals(operationToExecute.getOperation()))
{
+ return false;
+ }
+ final Map<String, FragmentDefinition> fragments = new HashMap<>();
+ for (FragmentDefinition fragment :
document.getDefinitionsOfType(FragmentDefinition.class)) {
+ fragments.put(fragment.getName(), fragment);
+ }
+ return !setsCreateIfMissing(operationToExecute.getSelectionSet(),
operationToExecute,
+ variables != null ? variables : Collections.emptyMap(),
fragments, new HashSet<>());
+ } catch (Exception e) {
+ return false;
+ }
+ }
+
+ /** Whether any field in the selection, fragments included, sets a {@code
createIfMissing} argument to true. */
+ private static boolean setsCreateIfMissing(SelectionSet selectionSet,
OperationDefinition operation,
+ Map<String, Object> variables,
Map<String, FragmentDefinition> fragments,
+ Set<String> visitedFragments) {
+ if (selectionSet == null) {
+ return false;
+ }
+ for (Selection<?> selection : selectionSet.getSelections()) {
+ if (selection instanceof Field) {
+ Field field = (Field) selection;
+ for (Argument argument : field.getArguments()) {
+ if (CREATE_IF_MISSING.equals(argument.getName()) &&
isTrue(argument.getValue(), operation, variables)) {
+ return true;
+ }
+ }
+ if (setsCreateIfMissing(field.getSelectionSet(), operation,
variables, fragments, visitedFragments)) {
+ return true;
+ }
+ } else if (selection instanceof InlineFragment) {
+ if (setsCreateIfMissing(((InlineFragment)
selection).getSelectionSet(), operation, variables, fragments,
+ visitedFragments)) {
+ return true;
+ }
+ } else if (selection instanceof FragmentSpread) {
+ FragmentDefinition fragment = fragments.get(((FragmentSpread)
selection).getName());
+ if (fragment != null &&
visitedFragments.add(fragment.getName())
+ && setsCreateIfMissing(fragment.getSelectionSet(),
operation, variables, fragments, visitedFragments)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /** A literal {@code true}, or a variable that is (or defaults to) true.
Anything not provably false counts as true. */
+ private static boolean isTrue(Value<?> value, OperationDefinition
operation, Map<String, Object> variables) {
+ if (value instanceof BooleanValue) {
+ return ((BooleanValue) value).isValue();
+ }
+ if (value instanceof NullValue) {
+ return false;
+ }
+ if (value instanceof VariableReference) {
+ String name = ((VariableReference) value).getName();
+ if (variables.containsKey(name)) {
+ Object provided = variables.get(name);
+ return provided != null && !Boolean.FALSE.equals(provided) &&
!"false".equalsIgnoreCase(String.valueOf(provided));
+ }
+ for (VariableDefinition definition :
operation.getVariableDefinitions()) {
+ if (name.equals(definition.getName())) {
+ return definition.getDefaultValue() != null
+ && isTrue(definition.getDefaultValue(), operation,
Collections.emptyMap());
+ }
+ }
+ return false;
+ }
+ return true;
+ }
+
private void executeGraphQLRequest(
HttpServletResponse resp, String query, String operationName,
Map<String, Object> variables) throws IOException {
LOGGER.debug("Executing GraphQL request with query: {}, operationName:
{}, variables: {}", query, operationName, variables);
diff --git
a/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/GraphQLServletReadOnlyOperationTest.java
b/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/GraphQLServletReadOnlyOperationTest.java
new file mode 100644
index 000000000..3664756fd
--- /dev/null
+++
b/graphql/cxs-impl/src/test/java/org/apache/unomi/graphql/servlet/GraphQLServletReadOnlyOperationTest.java
@@ -0,0 +1,119 @@
+/*
+ * 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.servlet;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.Collections;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * GET may only execute operations positively identified as queries.
+ */
+class GraphQLServletReadOnlyOperationTest {
+
+ @Test
+ void allowsQueries() {
+ assertTrue(GraphQLServlet.isReadOnlyOperation("query { cdp {
getProfile } }", null));
+ assertTrue(GraphQLServlet.isReadOnlyOperation("{ cdp { getProfile }
}", null));
+ }
+
+ @Test
+ void refusesMutations() {
+ assertFalse(GraphQLServlet.isReadOnlyOperation("mutation { cdp {
deleteProfile } }", null));
+ }
+
+ @Test
+ void refusesSubscriptions() {
+ assertFalse(GraphQLServlet.isReadOnlyOperation("subscription { cdp {
eventListener } }", null));
+ }
+
+ @Test
+ void selectsOperationByName() {
+ final String document = "query readIt { cdp { getProfile } } mutation
writeIt { cdp { deleteProfile } }";
+ assertTrue(GraphQLServlet.isReadOnlyOperation(document, "readIt"));
+ assertFalse(GraphQLServlet.isReadOnlyOperation(document, "writeIt"));
+ }
+
+ @Test
+ void refusesMutationAsFirstAnonymousChoice() {
+ assertFalse(GraphQLServlet.isReadOnlyOperation(
+ "mutation writeIt { cdp { deleteProfile } } query readIt { cdp
{ getProfile } }", null));
+ }
+
+ @Test
+ void refusesUnparsableDocuments() {
+ assertFalse(GraphQLServlet.isReadOnlyOperation("mutation {
unterminated", null));
+ }
+
+ @Test
+ void allowsEmptyQueryToFailDownstream() {
+ assertTrue(GraphQLServlet.isReadOnlyOperation(null, null));
+ assertTrue(GraphQLServlet.isReadOnlyOperation(" ", null));
+ }
+
+ // getProfile(createIfMissing: true) saves a profile, so a query setting
it is not read-only.
+
+ private static final String CREATE = "query { cdp { getProfile(profileID:
{id: \"x\"}, createIfMissing: true) { id } } }";
+
+ @Test
+ void refusesCreateIfMissingLiteralTrue() {
+ assertFalse(GraphQLServlet.isReadOnlyOperation(CREATE, null));
+ }
+
+ @Test
+ void allowsCreateIfMissingFalseOrAbsent() {
+ assertTrue(GraphQLServlet.isReadOnlyOperation(CREATE.replace("true",
"false"), null));
+ assertTrue(GraphQLServlet.isReadOnlyOperation(
+ "query { cdp { getProfile(profileID: {id: \"x\"},
createIfMissing: null) { id } } }", null));
+ assertTrue(GraphQLServlet.isReadOnlyOperation("query { cdp {
getProfile(profileID: {id: \"x\"}) { id } } }", null));
+ }
+
+ @Test
+ void refusesCreateIfMissingThroughVariable() {
+ final String document = "query q($c: Boolean) { cdp {
getProfile(profileID: {id: \"x\"}, createIfMissing: $c) { id } } }";
+ assertFalse(GraphQLServlet.isReadOnlyOperation(document, null,
Map.of("c", true)));
+ assertTrue(GraphQLServlet.isReadOnlyOperation(document, null,
Map.of("c", false)));
+ assertTrue(GraphQLServlet.isReadOnlyOperation(document, null,
Collections.emptyMap()));
+ }
+
+ @Test
+ void refusesCreateIfMissingThroughVariableDefault() {
+ final String document = "query q($c: Boolean = true) { cdp {
getProfile(profileID: {id: \"x\"}, createIfMissing: $c) { id } } }";
+ assertFalse(GraphQLServlet.isReadOnlyOperation(document, null,
Collections.emptyMap()));
+ assertTrue(GraphQLServlet.isReadOnlyOperation(document, null,
Map.of("c", false)));
+ }
+
+ @Test
+ void refusesCreateIfMissingInsideFragments() {
+ assertFalse(GraphQLServlet.isReadOnlyOperation(
+ "query { cdp { ...p } } fragment p on CDP_Query {
getProfile(profileID: {id: \"x\"}, createIfMissing: true) { id } }",
+ null));
+ assertFalse(GraphQLServlet.isReadOnlyOperation(
+ "query { cdp { ... on CDP_Query { getProfile(profileID: {id:
\"x\"}, createIfMissing: true) { id } } } }", null));
+ }
+
+ @Test
+ void cyclicFragmentsDoNotLoop() {
+ assertTrue(GraphQLServlet.isReadOnlyOperation(
+ "query { cdp { ...a } } fragment a on CDP_Query { ...b }
fragment b on CDP_Query { ...a }", null));
+ }
+}
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 b4494292e..8f9929004 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,10 @@ package org.apache.unomi.graphql.servlet;
import org.apache.unomi.api.security.SecurityService;
import org.apache.unomi.api.services.ExecutionContextManager;
+import graphql.GraphQL;
+import graphql.schema.idl.RuntimeWiring;
+import graphql.schema.idl.SchemaGenerator;
+import graphql.schema.idl.SchemaParser;
import org.apache.unomi.graphql.limits.GraphQLLimitsConfig;
import org.apache.unomi.graphql.servlet.auth.GraphQLServletSecurityValidator;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
@@ -38,6 +42,8 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Enumeration;
@@ -323,6 +329,7 @@ class GraphQLServletTest {
@Test
void doPost_declaredOversizedBody_is413WithoutReading() throws Exception {
servlet.setLimitsConfig(bodyLimit(100));
+ when(request.getContentType()).thenReturn("application/json");
when(request.getContentLength()).thenReturn(101);
servlet.doPost(request, response);
@@ -339,6 +346,7 @@ class GraphQLServletTest {
@Test
void doPost_chunkedOversizedBody_is413AndStopsReading() throws Exception {
servlet.setLimitsConfig(bodyLimit(1024));
+ when(request.getContentType()).thenReturn("application/json");
when(request.getContentLength()).thenReturn(-1);
byte[] body = ("{\"query\":\"" + "a".repeat(1024 * 1024) +
"\"}").getBytes(StandardCharsets.UTF_8);
BodyStream stream = new BodyStream(body);
@@ -355,6 +363,7 @@ class GraphQLServletTest {
@Test
void doPost_chunkedBodyWithinLimit_reachesValidator() throws Exception {
servlet.setLimitsConfig(bodyLimit(1024));
+ when(request.getContentType()).thenReturn("application/json");
when(request.getContentLength()).thenReturn(-1);
when(request.getInputStream()).thenReturn(
new BodyStream("{\"query\":\"{ __typename
}\"}".getBytes(StandardCharsets.UTF_8)));
@@ -366,6 +375,181 @@ class GraphQLServletTest {
verify(response,
never()).sendError(eq(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE),
anyString());
}
+ // --- HTTP method and content type rules
-------------------------------------------------------
+
+ private static final String QUERY = "{ ping }";
+ private static final String MUTATION = "mutation { touch }";
+
+ /** A real graphql-java instance behind the schema updater: queries answer
"pong", the mutation "touched". */
+ private StringWriter givenExecutableSchema() throws IOException {
+ GraphQL graphQL = GraphQL.newGraphQL(new
SchemaGenerator().makeExecutableSchema(
+ new SchemaParser().parse("type Query { ping: String,
profile(createIfMissing: Boolean): String }"
+ + " type Mutation { touch: String }"),
+ RuntimeWiring.newRuntimeWiring()
+ .type("Query", t -> t.dataFetcher("ping", env ->
"pong").dataFetcher("profile", env -> "loaded"))
+ .type("Mutation", t -> t.dataFetcher("touch", env ->
"touched"))
+ .build())).build();
+ GraphQLSchemaUpdater updater = mock(GraphQLSchemaUpdater.class);
+ when(updater.getGraphQL()).thenReturn(graphQL);
+ servlet.setGraphQLSchemaUpdater(updater);
+ StringWriter out = new StringWriter();
+ when(response.getWriter()).thenReturn(new PrintWriter(out));
+ return out;
+ }
+
+ private void givenGet(String query) {
+ when(request.getParameter("query")).thenReturn(query);
+ }
+
+ /** An authenticated GET query still runs. */
+ @Test
+ void doGet_query_runs() throws Exception {
+ StringWriter out = givenExecutableSchema();
+ givenGet(QUERY);
+ when(validator.validate(eq(QUERY), isNull(), eq(request),
eq(response))).thenReturn(true);
+
+ servlet.doGet(request, response);
+
+ assertTrue(out.toString().contains("pong"), out.toString());
+ verify(response,
never()).sendError(eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED), anyString());
+ }
+
+ /** A mutation over GET is refused with 405 and Allow: POST, and never
executed. */
+ @Test
+ void doGet_mutation_is405AndNeverRuns() throws Exception {
+ GraphQLSchemaUpdater updater = mock(GraphQLSchemaUpdater.class);
+ servlet.setGraphQLSchemaUpdater(updater);
+ givenGet(MUTATION);
+ when(validator.validate(eq(MUTATION), isNull(), eq(request),
eq(response))).thenReturn(true);
+
+ servlet.doGet(request, response);
+
+ verify(response).setHeader("Allow", "POST");
+
verify(response).sendError(eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED),
anyString());
+ verifyNoInteractions(updater);
+ }
+
+ /** A query document whose selected operation is a mutation is refused
too. */
+ @Test
+ void doGet_mutationSelectedByOperationName_is405() throws Exception {
+ String document = "query readIt { ping } mutation writeIt { touch }";
+ givenGet(document);
+ when(request.getParameter("operationName")).thenReturn("writeIt");
+ when(validator.validate(eq(document), eq("writeIt"), eq(request),
eq(response))).thenReturn(true);
+
+ servlet.doGet(request, response);
+
+
verify(response).sendError(eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED),
anyString());
+ }
+
+ /**
+ * Authentication (with its size limit) runs before the document is parsed
for the method check:
+ * an unauthenticated GET mutation gets the validator's answer, not 405.
+ */
+ @Test
+ void doGet_unauthenticatedMutation_isRejectedByValidatorFirst() throws
Exception {
+ givenGet(MUTATION);
+ when(validator.validate(eq(MUTATION), isNull(), eq(request),
eq(response))).thenReturn(false);
+
+ servlet.doGet(request, response);
+
+ verify(validator).validate(eq(MUTATION), isNull(), eq(request),
eq(response));
+ verify(response,
never()).sendError(eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED), anyString());
+ verify(response, never()).setHeader(eq("Allow"), anyString());
+ }
+
+ /** getProfile(createIfMissing: true) saves a profile: refused over GET
like a mutation, never executed. */
+ @Test
+ void doGet_createIfMissingTrue_is405AndNeverRuns() throws Exception {
+ GraphQLSchemaUpdater updater = mock(GraphQLSchemaUpdater.class);
+ servlet.setGraphQLSchemaUpdater(updater);
+ String query = "{ profile(createIfMissing: true) }";
+ givenGet(query);
+ when(validator.validate(eq(query), isNull(), eq(request),
eq(response))).thenReturn(true);
+
+ servlet.doGet(request, response);
+
+ verify(response).setHeader("Allow", "POST");
+
verify(response).sendError(eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED),
anyString());
+ verifyNoInteractions(updater);
+ }
+
+ /** The same through a GET variables parameter. */
+ @Test
+ void doGet_createIfMissingTrueThroughVariables_is405() throws Exception {
+ String query = "query q($c: Boolean) { profile(createIfMissing: $c) }";
+ givenGet(query);
+ when(request.getParameter("operationName")).thenReturn(null);
+ when(request.getParameter("variables")).thenReturn("{\"c\": true}");
+ when(validator.validate(eq(query), isNull(), eq(request),
eq(response))).thenReturn(true);
+
+ servlet.doGet(request, response);
+
+
verify(response).sendError(eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED),
anyString());
+ }
+
+ /** Reading a profile without creating it still works over GET. */
+ @Test
+ void doGet_createIfMissingFalse_runs() throws Exception {
+ StringWriter out = givenExecutableSchema();
+ String query = "{ profile(createIfMissing: false) }";
+ givenGet(query);
+ when(validator.validate(eq(query), isNull(), eq(request),
eq(response))).thenReturn(true);
+
+ servlet.doGet(request, response);
+
+ assertTrue(out.toString().contains("loaded"), out.toString());
+ verify(response,
never()).sendError(eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED), anyString());
+ }
+
+ /** A cross-site form can post text/plain without a preflight: refused
before the body is read. */
+ @Test
+ void doPost_textPlain_is415WithoutReading() throws Exception {
+ when(request.getContentType()).thenReturn("text/plain");
+
+ servlet.doPost(request, response);
+
+
verify(response).sendError(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE),
anyString());
+ verify(request, never()).getInputStream();
+ verifyNoInteractions(validator);
+ }
+
+ @Test
+ void doPost_formEncoded_is415() throws Exception {
+
when(request.getContentType()).thenReturn("application/x-www-form-urlencoded");
+
+ servlet.doPost(request, response);
+
+
verify(response).sendError(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE),
anyString());
+ verifyNoInteractions(validator);
+ }
+
+ @Test
+ void doPost_missingContentType_is415() throws Exception {
+ when(request.getContentType()).thenReturn(null);
+
+ servlet.doPost(request, response);
+
+
verify(response).sendError(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE),
anyString());
+ verifyNoInteractions(validator);
+ }
+
+ /** Mutations still run over POST with JSON; a charset parameter and any
letter case are accepted. */
+ @Test
+ void doPost_jsonWithCharset_runsMutation() throws Exception {
+ StringWriter out = givenExecutableSchema();
+ when(request.getContentType()).thenReturn("Application/JSON;
charset=UTF-8");
+ when(request.getContentLength()).thenReturn(-1);
+ when(request.getInputStream()).thenReturn(
+ new BodyStream(("{\"query\":\"" + MUTATION +
"\"}").getBytes(StandardCharsets.UTF_8)));
+ when(validator.validate(eq(MUTATION), isNull(), eq(request),
eq(response))).thenReturn(true);
+
+ servlet.doPost(request, response);
+
+ assertTrue(out.toString().contains("touched"), out.toString());
+ verify(response,
never()).sendError(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE),
anyString());
+ }
+
/** A request body as the container hands it over. */
private static final class BodyStream extends ServletInputStream {
private final ByteArrayInputStream in;
diff --git a/manual/src/main/asciidoc/configuration.adoc
b/manual/src/main/asciidoc/configuration.adoc
index 78f886548..45c9362c2 100644
--- a/manual/src/main/asciidoc/configuration.adoc
+++ b/manual/src/main/asciidoc/configuration.adoc
@@ -779,6 +779,8 @@ 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.
+HTTP GET may run query operations only. Mutations, subscriptions, and queries
that set `createIfMissing: true` on `getProfile` (which saves a profile) must
use HTTP POST with `Content-Type: application/json` (a charset parameter is
fine).
+
=== 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 82b5fe67d..96c6c75cf 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
@@ -471,6 +471,10 @@ In addition to tenant API keys, Unomi 4.0 hardens several
contracts that can bre
|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>>.
+|GraphQL over HTTP
+|`GET /graphql` ran any operation, mutations included, and `POST /graphql`
parsed a JSON body whatever its `Content-Type`.
+|`GET` runs queries only (`405` for mutations, subscriptions, and `getProfile`
with `createIfMissing: true`). `POST` requires `Content-Type: application/json`
(`415` otherwise); a charset parameter is fine. Clients that send JSON without
that header must add it: for example `curl -d` alone sends
`application/x-www-form-urlencoded`. 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.