Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions docs/decisions/2026-09-16-agent-sparql-execution.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@
- **Status:** Accepted for a scoped first implementation (2026-09-16, review 3). Code is
reviewed separately.
- **Revisions:** v1 2026-09-16 (initial) · v2 2026-09-29 (§2a: default grant through Data
Consumer, [OpenMetadata #34231](https://github.com/open-metadata/OpenMetadata/issues/34231)) · v3 2026-10-13 (MCP knowledge-graph tools, #34270; reconciled with current column projection) · v4 2026-10-21 (the test profile runs the published Fuseki image)
Consumer, [OpenMetadata #34231](https://github.com/open-metadata/OpenMetadata/issues/34231)) · v3 2026-10-13 (MCP knowledge-graph tools, #34270; reconciled with current column projection) · v4 2026-10-21 (the test profile runs the published Fuseki image) · v5 2026-11-06 (the inspector and the federation guard share one query walker)
- **Deciders:** OpenMetadata maintainers
- **Guard:** `AgentSparqlResourceIT`, `AgentSparqlServiceTest`, `AgentSparqlQueryValidatorTest`,
`AgentSparqlQueryInspectorTest`, `AgentSparqlTransportTest`
- **Issue:** [OpenMetadata #33384](https://github.com/open-metadata/OpenMetadata/issues/33384)
- **Amended by:** [OpenMetadata #34231](https://github.com/open-metadata/OpenMetadata/issues/34231),
[OpenMetadata #34270](https://github.com/open-metadata/OpenMetadata/issues/34270)
(MCP knowledge-graph tools — see the amendment before the Review log),
ADR:2026-10-14-fuseki-image-of-record (the test profile's image).
(MCP knowledge-graph tools — see "Amendment: MCP knowledge-graph tools"),
ADR:2026-10-14-fuseki-image-of-record (the test profile's image),
[OpenMetadata #33436](https://github.com/open-metadata/OpenMetadata/issues/33436)
(one query walker for the inspector and the federation guard — see the 2026-11-06 amendment).
- **Related:** ai-platform epic #224, ai-platform #1299, ai-platform PR #1310 (design, pinned at
`0056ceb9`); OpenMetadata #33224 (asset-level RBAC — parallel work, explicitly **not** a
prerequisite and **not** provided here).
Expand Down Expand Up @@ -621,6 +623,15 @@ longer describe the tree. With no `rdfContainerImage` set, `TestSuiteBootstrap`
`FUSEKI_UNION_DEFAULT_GRAPH=true`, not `docker/rdf-store/config.ttl`. The requirement is unchanged:
without the union default graph, agent queries succeed with empty results.

## Amendment — 2026-11-06: the inspector and the federation guard share one walker

§4 kept `SparqlFederationGuard` off this path partly because the guard walked only the WHERE
pattern. That reason no longer holds: the guard missed `SERVICE` inside `EXISTS` in every
expression position, the inspector missed a bare `EXISTS { … }` pattern element, and both now walk
queries with `SparqlQueryWalker`, which reaches every element and expression (#33436). The
decision stands on its other reasons: the inspector grants no endpoint allowlist, and it reports
`FEDERATION_NOT_ALLOWED` where the guard, ordered first, would report `QUERY_INVALID`.

## Review log

- 2026-09-16 review 1: design agreed, conditional. Resolved — wildcard authorization (§2a:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ public final class FusekiTestImage {

public static final String IMAGE_PROPERTY = "rdfContainerImage";
public static final int PORT = 3030;

/**
* Fuseki's liveness endpoint as Fuseki itself reaches it from inside its container. A SERVICE
* clause aimed here is one Fuseki can always execute, so a test sees a request Fuseki would make.
*/
public static final String SELF_PING_URL = "http://localhost:" + PORT + "/$/ping";

public static final String ADMIN_USER = "admin";
public static final String ADMIN_PASSWORD = "test-admin";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Isolated;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.openmetadata.it.auth.JwtAuthProvider;
import org.openmetadata.it.bootstrap.FusekiTestImage;
import org.openmetadata.it.util.RdfTestUtils;
import org.openmetadata.it.util.SdkClients;
import org.openmetadata.schema.api.CreateBot;
Expand Down Expand Up @@ -393,6 +396,23 @@ void queryPolicyViolationsHaveDistinctCodes() throws Exception {
AgentSparqlErrorCode.QUERY_LIMIT_EXCEEDED);
}

/**
* A bare EXISTS block is a pattern element, not a FILTER expression, yet Fuseki evaluates the
* SERVICE inside it all the same.
*/
@ParameterizedTest
@ValueSource(
strings = {
"SELECT ?s WHERE { ?s ?p ?o EXISTS { SERVICE <%s> { ?a ?b ?c } } }",
"SELECT ?s WHERE { ?s ?p ?o NOT EXISTS { SERVICE <%s> { ?a ?b ?c } } }"
})
void federationInsideABareExistsBlockIsRefused(String template) throws Exception {
assertError(
post(grantedToken, query(template.formatted(FusekiTestImage.SELF_PING_URL))),
403,
AgentSparqlErrorCode.FEDERATION_NOT_ALLOWED);
}

@Test
void explicitLimitIsCompleteRelativeToTheSubmittedQuery() throws Exception {
AgentSparqlResponse response =
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package org.openmetadata.it.tests;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.fasterxml.jackson.databind.JsonNode;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.openmetadata.it.factories.GlossaryTestFactory;
import org.openmetadata.it.util.SdkClients;
import org.openmetadata.it.util.TestNamespace;
import org.openmetadata.it.util.TestNamespaceExtension;
import org.openmetadata.schema.api.rdf.SparqlQuery;
import org.openmetadata.schema.entity.data.Glossary;
import org.openmetadata.sdk.client.OpenMetadataClient;
import org.openmetadata.sdk.exceptions.OpenMetadataException;
import org.openmetadata.sdk.network.HttpMethod;

/**
* {@code POST /v1/glossaries/{id}/sparql} runs SPARQL inside the OpenMetadata server for any user
* who can view the glossary. It must never make the server send a request on the caller's behalf:
* SERVICE is refused wherever the query places it, and the endpoint it names is never contacted.
*
* <p>The server runs in this JVM, so an endpoint on the loopback interface stands in for an
* internal host only the server can reach.
*
* <p>The tests run one at a time as a user no other SPARQL test uses: the server admits two
* concurrent SPARQL queries per user and answers a third with 429, even one it would refuse.
*/
@Execution(ExecutionMode.SAME_THREAD)
@ExtendWith(TestNamespaceExtension.class)
public class GlossaryOntologyQueryIT {

@Test
void aUserWithNoRolesCanQueryTheGlossaryOntology(TestNamespace ns) {
final Glossary glossary = GlossaryTestFactory.createSimple(ns);

final JsonNode result = query(SdkClients.user3Client(), glossary, "ASK { }");

assertTrue(result.path("boolean").asBoolean(), result.toString());
}

@ParameterizedTest
@ValueSource(
strings = {
"SELECT * WHERE { SERVICE <%s> { ?s ?p ?o } }",
"SELECT (EXISTS { SERVICE <%s> { ?s ?p ?o } } AS ?reachable) WHERE { }",
"ASK { FILTER EXISTS { SERVICE <%s> { ?s ?p ?o } } }",
"SELECT * WHERE { ?s ?p ?o EXISTS { SERVICE <%s> { ?a ?b ?c } } }"
})
void aServiceClauseIsRefusedWithoutContactingItsEndpoint(String template, TestNamespace ns) {
final Glossary glossary = GlossaryTestFactory.createWithName(ns, ns.uniqueShortId());
try (InternalHost internalHost = InternalHost.start()) {
final String sparql = template.formatted(internalHost.uri());

final OpenMetadataException refused =
assertThrows(
OpenMetadataException.class, () -> query(SdkClients.user3Client(), glossary, sparql));

assertEquals(403, refused.getStatusCode(), refused.getMessage());
assertEquals(0, internalHost.requestCount());
}
}

private static JsonNode query(
final OpenMetadataClient client, final Glossary glossary, final String sparql) {
return client
.getHttpClient()
.execute(
HttpMethod.POST,
"/v1/glossaries/" + glossary.getId() + "/sparql",
new SparqlQuery().withQuery(sparql),
JsonNode.class);
}

/** Answers every request with a secret and counts the requests it receives. */
private static final class InternalHost implements AutoCloseable {
private static final byte[] SECRET =
"db_password=internal-only".getBytes(StandardCharsets.UTF_8);

private final HttpServer server;
private final AtomicInteger requests = new AtomicInteger();

private InternalHost(final HttpServer server) {
this.server = server;
}

static InternalHost start() {
try {
final HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
final InternalHost host = new InternalHost(server);
server.createContext("/", host::answer);
server.start();
return host;
} catch (IOException exception) {
throw new UncheckedIOException("Cannot start the internal host stand-in", exception);
}
}

private void answer(final HttpExchange exchange) throws IOException {
requests.incrementAndGet();
exchange.getResponseHeaders().add("Content-Type", "text/plain");
exchange.sendResponseHeaders(200, SECRET.length);
try (OutputStream body = exchange.getResponseBody()) {
body.write(SECRET);
}
}

String uri() {
return "http://127.0.0.1:" + server.getAddress().getPort() + "/internal/config.txt";
}

int requestCount() {
return requests.get();
}

@Override
public void close() {
server.stop(0);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public class OntologyDraftQueryIT extends BaseOntologyApprovalIT {
private static final SparqlQuery CLASSES =
new SparqlQuery()
.withQuery("SELECT ?class WHERE { ?class a <http://www.w3.org/2002/07/owl#Class> }");
private static final String EXTERNAL_ENDPOINT = "http://localhost:9999/";

@Test
void draftScopeSeesAConceptThatTheReleaseScopeDoesNot(TestNamespace ns) {
Expand Down Expand Up @@ -84,7 +85,7 @@ void draftScopeRefusesAnExternalServiceClauseAndAnUnknownScope(TestNamespace ns)
concept(ontology, "First");
final SparqlQuery service =
new SparqlQuery()
.withQuery("SELECT * WHERE { SERVICE <http://localhost:9999/> { ?s ?p ?o } }");
.withQuery("SELECT * WHERE { SERVICE <" + EXTERNAL_ENDPOINT + "> { ?s ?p ?o } }");

assertEquals(
403,
Expand All @@ -100,6 +101,30 @@ void draftScopeRefusesAnExternalServiceClauseAndAnUnknownScope(TestNamespace ns)
.getStatusCode());
}

/**
* EXISTS evaluates its whole graph pattern, SERVICE included, wherever the expression sits. The
* viewer is a user the other tests here do not query as, so concurrent tests cannot push it past
* the server's two concurrent SPARQL queries per user.
*/
@Test
void aViewerIsRefusedAServiceClauseHiddenInsideAnExpression(TestNamespace ns) {
final Ontology ontology = createOntology(ns);
concept(ontology, "First");
final SparqlQuery hidden =
new SparqlQuery()
.withQuery(
"SELECT (EXISTS { SERVICE <"
+ EXTERNAL_ENDPOINT
+ "> { ?s ?p ?o } } AS ?reachable) WHERE { }");

assertEquals(
403,
assertThrows(
OpenMetadataException.class,
() -> run(SdkClients.user1Client(), ontology, null, hidden))
.getStatusCode());
}

private static OntologyConcept concept(final Ontology ontology, final String name) {
return SdkClients.adminClient()
.ontologyConcepts()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import org.junit.jupiter.api.parallel.Isolated;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.openmetadata.it.bootstrap.FusekiTestImage;
import org.openmetadata.it.bootstrap.TestSuiteBootstrap;
import org.openmetadata.it.factories.DatabaseSchemaTestFactory;
import org.openmetadata.it.factories.DatabaseServiceTestFactory;
Expand Down Expand Up @@ -455,20 +457,60 @@ void testSparqlEndpointReportsReasonerLevelsAsUnavailable(SparqlQuery.Inference
assertTrue(response.body().contains("not available"), response.body());
}

/**
* EXISTS carries a whole graph pattern inside an expression, and Fuseki evaluates a SERVICE in it
* like any other SERVICE. The federation policy has to refuse it before the query is forwarded,
* or Fuseki sends the request — here to its own ping endpoint, which it can always reach.
*/
@ParameterizedTest
@ValueSource(
strings = {
"SELECT (EXISTS { SERVICE <%s> { ?s ?p ?o } } AS ?reachable) WHERE { }",
"SELECT * WHERE { ?s ?p ?o FILTER EXISTS { SERVICE <%s> { ?a ?b ?c } } } LIMIT 1",
"SELECT * WHERE { ?s ?p ?o NOT EXISTS { SERVICE <%s> { ?a ?b ?c } } } LIMIT 1",
"SELECT ?s WHERE { ?s ?p ?o } ORDER BY (EXISTS { SERVICE <%s> { ?a ?b ?c } }) LIMIT 2"
})
void testSparqlEndpointRefusesServiceHiddenInsideExists(String template) throws Exception {
HttpResponse<String> response =
postSparql(
template.formatted(FusekiTestImage.SELF_PING_URL), "json", SparqlQuery.Inference.NONE);

assertEquals(403, response.statusCode(), response.body());
assertTrue(response.body().contains(FusekiTestImage.SELF_PING_URL), response.body());
}

@Test
void testSparqlUpdateEndpointRefusesServiceHiddenInsideExists() throws Exception {
String update =
"INSERT { GRAPH <urn:om:it:federation> { <urn:om:it:probe> <urn:om:it:reached> ?x } } "
+ "WHERE { BIND(EXISTS { SERVICE <"
+ FusekiTestImage.SELF_PING_URL
+ "> { ?s ?p ?o } } AS ?x) }";

HttpResponse<String> response =
postAsAdmin("/v1/rdf/sparql/update", new SparqlQuery().withQuery(update));

assertEquals(403, response.statusCode(), response.body());
assertTrue(response.body().contains(FusekiTestImage.SELF_PING_URL), response.body());
}

private static HttpResponse<String> postSparql(
String query, String format, SparqlQuery.Inference inference) throws Exception {
String requestBody =
JsonUtils.pojoToJson(
new SparqlQuery()
.withQuery(query)
.withFormat(SparqlQuery.Format.fromValue(format))
.withInference(inference));
return postAsAdmin(
"/v1/rdf/sparql",
new SparqlQuery()
.withQuery(query)
.withFormat(SparqlQuery.Format.fromValue(format))
.withInference(inference));
}

private static HttpResponse<String> postAsAdmin(String path, SparqlQuery body) throws Exception {
HttpRequest request =
HttpRequest.newBuilder()
.uri(URI.create(SdkClients.getServerUrl() + "/v1/rdf/sparql"))
.uri(URI.create(SdkClients.getServerUrl() + path))
.header("Authorization", "Bearer " + SdkClients.getAdminToken())
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.POST(HttpRequest.BodyPublishers.ofString(JsonUtils.pojoToJson(body)))
.build();
return HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.parallel.Isolated;
import org.openmetadata.it.bootstrap.FusekiTestImage;
import org.openmetadata.it.bootstrap.TestSuiteBootstrap;
import org.openmetadata.it.factories.DatabaseSchemaTestFactory;
import org.openmetadata.it.factories.DatabaseServiceTestFactory;
Expand Down Expand Up @@ -293,10 +294,16 @@ void aServerCappedSelectReportsTruncatedCompleteness() throws Exception {
void queryFormsOutsideTheNonAdminProfileAreRejectedWithTheirCode() throws Exception {
final Map<String, String> expectedFragmentByQuery =
Map.of(
"CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o } LIMIT 1", "QUERY_FORM_NOT_ALLOWED",
"SELECT * WHERE { GRAPH ?g { ?s ?p ?o } } LIMIT 1", "GRAPH_SELECTION_NOT_ALLOWED",
"CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o } LIMIT 1",
"QUERY_FORM_NOT_ALLOWED",
"SELECT * WHERE { GRAPH ?g { ?s ?p ?o } } LIMIT 1",
"GRAPH_SELECTION_NOT_ALLOWED",
"SELECT * WHERE { SERVICE <https://x.example/sparql> { ?s ?p ?o } }",
"FEDERATION_NOT_ALLOWED");
"FEDERATION_NOT_ALLOWED",
"SELECT * WHERE { ?s ?p ?o EXISTS { SERVICE <"
+ FusekiTestImage.SELF_PING_URL
+ "> { ?a ?b ?c } } } LIMIT 1",
"FEDERATION_NOT_ALLOWED");

for (final Map.Entry<String, String> rejected : expectedFragmentByQuery.entrySet()) {
final ToolOutcome outcome =
Expand Down
Loading
Loading