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
fix(export): escape IRI-valued metadata to close a Turtle/N-Triples injection gap
KaifAhmad1220fb10e5c16
diff --git a/semantica/export/rdf_exporter.py b/semantica/export/rdf_exporter.pyindex bcd89140..dffd4951 100644--- a/semantica/export/rdf_exporter.py+++ b/semantica/export/rdf_exporter.py@@ -193,6 +193,24 @@ def _escape_literal(value: str) -> str:)+#: Turtle/N-Triples IRIREF grammar excludes these unescaped between `<` and+#: `>`: control characters, space, and <>"{}|^`\. An IRI-valued metadata+#: value (currently only sem:sourceUri, from the caller-controlled "uri"+#: metadata key) is written as `<{value}>` with no other quoting, so a value+#: containing one of these characters — a ">" followed by a full triple, for+#: instance — closes the IRIREF early and lets the rest of the string be+#: parsed as further RDF statements. This is the same shape of defect the+#: entity/relationship IRIs were hardened against; that hardening resolves+#: prefixes as well, which a metadata value never needs, so this stays a+#: narrower, dedicated guard rather than reusing _as_turtle_iri.+_IRI_REF_UNSAFE_RE = re.compile(r'[\x00-\x20<>"{}|^`\\]')+++def _safe_iri_ref(value: str) -> str:+ """Percent-encode the characters an IRIREF may not contain unescaped."""+ return _IRI_REF_UNSAFE_RE.sub(lambda m: quote(m.group(0), safe=""), value)++def _escape_xml(value: str) -> str:"""Escape a string for either XML element text or an attribute value.@@ -328,7 +346,7 @@ def _typed_literal_parts(term: str, value: Any) -> tuple:def _turtle_object(term: str, value: Any) -> str:kind, lexical, datatype = _typed_literal_parts(term, value)if kind == "iri":- return f"<{lexical}>"+ return f"<{_safe_iri_ref(lexical)}>"if datatype is None:return f'"{_escape_literal(lexical)}"'return f'"{lexical}"^^<{datatype}>'diff --git a/tests/export/test_metadata_passthrough.py b/tests/export/test_metadata_passthrough.pyindex cdb73227..ff4c3ddc 100644--- a/tests/export/test_metadata_passthrough.py+++ b/tests/export/test_metadata_passthrough.py@@ -351,3 +351,51 @@ def test_a_quote_in_an_attribute_value_cannot_break_the_document():from xml.dom.minidom import parseStringparseString(xml) # well-formedness is the assertion+++# --- Finding from review of PR #1165 ----------------------------------------++[email protected]("fmt", ["turtle", "ntriples"])+def test_an_iri_valued_metadata_value_cannot_inject_a_second_triple(fmt):+ """`sem:sourceUri` (the "uri" key) is the one metadata term written as a+ node, ``<{value}>``, with no other quoting. Turtle/N-Triples IRIREFs+ exclude '>' (among other characters) unescaped, so a value shaped like+ ``<goodIRI> . <injected> <p> <o>`` closed the reference early and let the+ rest of the string be parsed as an unrelated, attacker-chosen triple.+ """+ payload = (+ "https://evil.example/x> . <https://evil.example/injected> "+ "<https://evil.example/p> <https://evil.example/o"+ )+ data = {+ "entities": [+ {"id": ENTITY_IRI, "text": "Acme", "metadata": {"uri": payload}}+ ],+ "relationships": [],+ }+ g = _serialize(RDFSerializer(), fmt, data)+ # Exactly the entity's own four statements: type, text, confidence, and+ # the one metadata triple. No extra subject/triple was injected — the+ # payload survives only as (a mangled but harmless part of) the single+ # sourceUri value, never as a standalone subject of its own.+ assert len(g) == 4+ assert not list(g.subjects(None, URIRef("https://evil.example/injected")))+ assert not list(g.subjects(URIRef("https://evil.example/p"), None))++[email protected]("fmt", ["turtle", "ntriples"])+def test_an_iri_valued_metadata_value_with_control_characters_still_parses(fmt):+ """A newline or tab in an IRI-valued metadata value is just as+ unescaped-IRIREF-breaking as '>' — cover the control-character half of+ the grammar, not only the delimiter characters.+ """+ payload = "https://evil.example/x\ninjected line\ttabbed"+ data = {+ "entities": [+ {"id": ENTITY_IRI, "text": "Acme", "metadata": {"uri": payload}}+ ],+ "relationships": [],+ }+ g = _serialize(RDFSerializer(), fmt, data)+ assert len(g) == 4