Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
security: validate triplet IRIs before SPARQL interpolation (GHSA-8vgg-8mr4-r236)
KaifAhmad19ecae47a8ac0
diff --git a/semantica/triplet_store/blazegraph_store.py b/semantica/triplet_store/blazegraph_store.pyindex 73ebf0da..9a18faf3 100644--- a/semantica/triplet_store/blazegraph_store.py+++ b/semantica/triplet_store/blazegraph_store.py@@ -312,7 +312,7 @@ class BlazegraphStore:try:# Use SPARQL INSERT for bulk loadinggraph = options.get("graph", "")- graph_clause = f"GRAPH <{graph}>" if graph else ""+ graph_clause = f"GRAPH <{sparql_escaping.validate_uri(graph)}>" if graph else ""# Build INSERT queryinsert_data = self._build_insert_data(triplets)@@ -344,8 +344,10 @@ class BlazegraphStore:if format == "turtle":lines = []for triplet in triplets:+ subject = sparql_escaping.validate_uri(triplet.subject)+ predicate = sparql_escaping.validate_uri(triplet.predicate)lines.append(- f"<{triplet.subject}> <{triplet.predicate}> {self._format_object_for_sparql(triplet)} ."+ f"<{subject}> <{predicate}> {self._format_object_for_sparql(triplet)} .")return "\n".join(lines)else:@@ -353,11 +355,20 @@ class BlazegraphStore:return self._triplets_to_rdf(triplets, "turtle")def _build_insert_data(self, triplets: List[Triplet]) -> str:- """Build SPARQL INSERT DATA clause."""+ """Build SPARQL INSERT DATA clause.++ Validates subject/predicate as safe IRIs via+ sparql_escaping.validate_uri before interpolation — unlike the+ object (handled by _format_object_for_sparql), subject/predicate+ can't be parameterized in a raw HTTP SPARQL Update POST, so an+ unvalidated value is a direct injection point (GHSA-8vgg-8mr4-r236).+ """lines = []for triplet in triplets:+ subject = sparql_escaping.validate_uri(triplet.subject)+ predicate = sparql_escaping.validate_uri(triplet.predicate)lines.append(- f"<{triplet.subject}> <{triplet.predicate}> {self._format_object_for_sparql(triplet)} ."+ f"<{subject}> <{predicate}> {self._format_object_for_sparql(triplet)} .")return " ".join(lines)@@ -460,9 +471,9 @@ class BlazegraphStore:# Build SPARQL querywhere_clauses = []if subject:- where_clauses.append(f"?s = <{subject}>")+ where_clauses.append(f"?s = <{sparql_escaping.validate_uri(subject)}>")if predicate:- where_clauses.append(f"?p = <{predicate}>")+ where_clauses.append(f"?p = <{sparql_escaping.validate_uri(predicate)}>")if object:where_clauses.append(f"?o = {self._format_object_for_sparql(Triplet(subject='', predicate='', object=object))}"@@ -494,8 +505,10 @@ class BlazegraphStore:update_endpoint = self._get_update_endpoint()+ subject = sparql_escaping.validate_uri(triplet.subject)+ predicate = sparql_escaping.validate_uri(triplet.predicate)query = (- f"DELETE DATA {{ <{triplet.subject}> <{triplet.predicate}> "+ f"DELETE DATA {{ <{subject}> <{predicate}> "f"{self._format_object_for_sparql(triplet)} }}")diff --git a/semantica/triplet_store/jena_store.py b/semantica/triplet_store/jena_store.pyindex dadeb71c..df3c1452 100644--- a/semantica/triplet_store/jena_store.py+++ b/semantica/triplet_store/jena_store.py@@ -319,11 +319,11 @@ class JenaStore:# Build SPARQL queryquery_parts = []if subject:- query_parts.append(f"?s = <{subject}>")+ query_parts.append(f"?s = <{sparql_escaping.validate_uri(subject)}>")if predicate:- query_parts.append(f"?p = <{predicate}>")+ query_parts.append(f"?p = <{sparql_escaping.validate_uri(predicate)}>")if object:- query_parts.append(f"?o = <{object}>")+ query_parts.append(f"?o = <{sparql_escaping.validate_uri(object)}>")where_clause = " ".join(query_parts) if query_parts else ""query = f"SELECT ?s ?p ?o WHERE {{ ?s ?p ?o {where_clause} }}"diff --git a/semantica/triplet_store/rdf4j_store.py b/semantica/triplet_store/rdf4j_store.pyindex 005c22bc..cdf05061 100644--- a/semantica/triplet_store/rdf4j_store.py+++ b/semantica/triplet_store/rdf4j_store.py@@ -452,11 +452,11 @@ class RDF4JStore:# Build SPARQL querywhere_clauses = []if subject:- where_clauses.append(f"?s = <{subject}>")+ where_clauses.append(f"?s = <{sparql_escaping.validate_uri(subject)}>")if predicate:- where_clauses.append(f"?p = <{predicate}>")+ where_clauses.append(f"?p = <{sparql_escaping.validate_uri(predicate)}>")if object:- where_clauses.append(f"?o = <{object}>")+ where_clauses.append(f"?o = <{sparql_escaping.validate_uri(object)}>")where_clause = " ".join(where_clauses) if where_clauses else ""query = f"SELECT ?s ?p ?o WHERE {{ ?s ?p ?o {where_clause} }}"@@ -485,7 +485,10 @@ class RDF4JStore:update_endpoint = self._get_update_endpoint()# Use SPARQL DELETE- query = f"DELETE DATA {{ <{triplet.subject}> <{triplet.predicate}> <{triplet.object}> }}"+ subject = sparql_escaping.validate_uri(triplet.subject)+ predicate = sparql_escaping.validate_uri(triplet.predicate)+ object_ = sparql_escaping.validate_uri(triplet.object)+ query = f"DELETE DATA {{ <{subject}> <{predicate}> <{object_}> }}"try:response = requests.post(@@ -550,9 +553,17 @@ class RDF4JStore:return f'"{escaped}"'def _triplets_to_ntriples(self, triplets: List[Triplet]) -> str:- """Convert triplets to N-Triples format."""+ """Convert triplets to N-Triples format.++ Validates subject/predicate via sparql_escaping.validate_uri: an+ unvalidated value containing '>' or a newline could terminate the+ current triple line early and splice extra triples into the+ upload stream (GHSA-8vgg-8mr4-r236).+ """lines = []for triplet in triplets:+ subject = sparql_escaping.validate_uri(triplet.subject)+ predicate = sparql_escaping.validate_uri(triplet.predicate)obj_str = self._format_object_for_ntriples(triplet)- lines.append(f"<{triplet.subject}> <{triplet.predicate}> {obj_str} .")+ lines.append(f"<{subject}> <{predicate}> {obj_str} .")return "\n".join(lines)diff --git a/tests/triplet_store/test_sparql_injection.py b/tests/triplet_store/test_sparql_injection.pynew file mode 100644index 00000000..863efa85--- /dev/null+++ b/tests/triplet_store/test_sparql_injection.py@@ -0,0 +1,150 @@+"""Regression tests for GHSA-8vgg-8mr4-r236: unvalidated triplet IRIs+allowed arbitrary SPARQL update injection in the Blazegraph and RDF4J+stores, and query-filter injection on the Jena read path.++Triplet.subject/predicate (and, in some builders, .object) are document+text in the normal ingest pipeline — entity names extracted from ingested+content. A subject containing '>' closes the '<...>' IRI token early, so+the rest of the value is parsed as more SPARQL, letting an attacker+append operations like CLEAR ALL that run with the application's store+credentials.++Mirrors the advisory's own PoC payload: a subject/predicate crafted to+close the current triple pattern and append a destructive `; CLEAR ALL ;`+statement. After the fix, sparql_escaping.validate_uri (already used by+anzo_store.py, the one backend that was already hardened) rejects it+before any query/update text is built.+"""++import unittest+from unittest.mock import MagicMock, patch++from semantica.semantic_extract.triplet_extractor import Triplet+from semantica.triplet_store.blazegraph_store import BlazegraphStore+from semantica.triplet_store.rdf4j_store import RDF4JStore+from semantica.triplet_store.jena_store import JenaStore+from semantica.utils.exceptions import ProcessingError, ValidationError++# The advisory's own injection payload: closes the <...> token, then the+# triple pattern, then appends a store-wide wipe and a rogue insert.+EVIL_SUBJECT = (+ "http://example.com/a> <http://example.com/b> <http://example.com/c> . } "+ "; CLEAR ALL ; INSERT DATA { <http://evil.example/owned"+)+++class TestBlazegraphSparqlInjection(unittest.TestCase):+ @patch.object(BlazegraphStore, "_connect", autospec=True)+ def _make_store(self, _mock_connect):+ return BlazegraphStore(endpoint="http://localhost:9999/blazegraph")++ def test_build_insert_data_rejects_malicious_subject(self):+ store = self._make_store()+ triplet = Triplet(subject=EVIL_SUBJECT, predicate="http://p", object="x")+ with self.assertRaises(ValidationError):+ store._build_insert_data([triplet])++ def test_triplets_to_rdf_rejects_malicious_subject(self):+ store = self._make_store()+ triplet = Triplet(subject=EVIL_SUBJECT, predicate="http://p", object="x")+ with self.assertRaises(ValidationError):+ store._triplets_to_rdf([triplet])++ def test_delete_triplet_rejects_malicious_subject(self):+ store = self._make_store()+ store.connected = True+ triplet = Triplet(subject=EVIL_SUBJECT, predicate="http://p", object="x")+ with self.assertRaises(ValidationError):+ store.delete_triplet(triplet)++ def test_get_triplets_rejects_malicious_subject_filter(self):+ store = self._make_store()+ with self.assertRaises(ValidationError):+ store.get_triplets(subject=EVIL_SUBJECT)++ def test_bulk_load_rejects_malicious_graph_option(self):+ # bulk_load() wraps its whole body in except Exception: raise+ # ProcessingError(...) (pre-existing, unrelated to this fix), so the+ # ValidationError sanitize_uri raises surfaces as ProcessingError.+ # The security property that matters — the malicious query is never+ # sent — holds either way.+ store = self._make_store()+ store.connected = True+ triplet = Triplet(subject="http://s", predicate="http://p", object="x")+ with self.assertRaises(ProcessingError) as ctx:+ store.bulk_load([triplet], graph=EVIL_SUBJECT)+ self.assertIn("Invalid URI", str(ctx.exception))++ def test_legitimate_triplet_still_builds_correct_query(self):+ store = self._make_store()+ triplet = Triplet(subject="http://s", predicate="http://p", object="x")+ insert_data = store._build_insert_data([triplet])+ self.assertIn("<http://s> <http://p>", insert_data)+ self.assertNotIn("CLEAR ALL", insert_data)+++class TestRDF4JSparqlInjection(unittest.TestCase):+ def _make_store(self):+ return RDF4JStore(endpoint="http://localhost:9999/rdf4j", repository_id="mem")++ def test_triplets_to_ntriples_rejects_malicious_subject(self):+ store = self._make_store()+ triplet = Triplet(subject=EVIL_SUBJECT, predicate="http://p", object="x")+ with self.assertRaises(ValidationError):+ store._triplets_to_ntriples([triplet])++ def test_delete_triplet_rejects_malicious_subject(self):+ store = self._make_store()+ store.connected = True+ triplet = Triplet(subject=EVIL_SUBJECT, predicate="http://p", object="http://o")+ with self.assertRaises(ValidationError):+ store.delete_triplet(triplet)++ def test_get_triplets_rejects_malicious_subject_filter(self):+ store = self._make_store()+ with self.assertRaises(ValidationError):+ store.get_triplets(subject=EVIL_SUBJECT)++ def test_legitimate_triplet_still_builds_correct_ntriples(self):+ store = self._make_store()+ triplet = Triplet(subject="http://s", predicate="http://p", object="x")+ ntriples = store._triplets_to_ntriples([triplet])+ self.assertIn("<http://s> <http://p>", ntriples)+ self.assertNotIn("CLEAR ALL", ntriples)+++class TestJenaSparqlInjection(unittest.TestCase):+ def setUp(self):+ from rdflib import Graph++ self.store = JenaStore()+ self.store.graph = Graph()++ def test_get_triplets_never_queries_with_malicious_subject_filter(self):+ """get_triplets() catches all exceptions and returns [] (pre-existing,+ broad error-handling behavior unrelated to this fix), so the+ observable contract is: the malicious filter must never reach+ graph.query() at all."""+ with patch.object(self.store.graph, "query", wraps=self.store.graph.query) as spy:+ result = self.store.get_triplets(subject=EVIL_SUBJECT)+ self.assertEqual(result, [])+ spy.assert_not_called()++ def test_get_triplets_with_legitimate_filter_still_reaches_query(self):+ """A validated identifier must not be rejected by the sanitizer —+ it should reach graph.query(). (Whether the WHERE-clause filter+ syntax jena_store.py builds is itself correct SPARQL is a separate,+ pre-existing question this test doesn't assert on: the query here+ is `{ ?s ?p ?o ?s = <http://s> }`, missing a FILTER()/separator,+ and unrelated to sanitize_uri.)"""+ self.store.graph.parse(+ data='<http://s> <http://p> "x" .', format="ntriples"+ )+ with patch.object(self.store.graph, "query", wraps=self.store.graph.query) as spy:+ self.store.get_triplets(subject="http://s")+ spy.assert_called_once()+ self.assertIn("http://s", spy.call_args[0][0])+++if __name__ == "__main__":+ unittest.main()