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: address Qodo review findings on security PR (numpy/JSON, relative redirects, SPARQL 500)
KaifAhmad13e9ba1b7fb92
diff --git a/semantica/explorer/routes/ontology.py b/semantica/explorer/routes/ontology.pyindex ca9101fc..5c1fa8d0 100644--- a/semantica/explorer/routes/ontology.py+++ b/semantica/explorer/routes/ontology.py@@ -11,7 +11,7 @@ import uuidfrom datetime import datetime, UTCfrom difflib import SequenceMatcherfrom typing import Any, Dict, List, Optional, Tuple-from urllib.parse import urlparse+from urllib.parse import urlparse, urljoinfrom typing_extensions import Literalfrom fastapi import APIRouter, Depends, HTTPException, Query, Request@@ -1017,23 +1017,30 @@ def _fetch_url_sync(url: str) -> bytes:allow_redirects=False, # SECURITY: follow redirects manually)if resp.is_redirect or resp.is_permanent_redirect:- redirect_url = resp.headers.get("Location")- if not redirect_url:+ location = resp.headers.get("Location")+ resp.close()+ if not location:raise HTTPException(status_code=502, detail="Redirect without Location header.")+ # Location may be relative (e.g. "/ontology.ttl"); resolve it+ # against the current URL before validating.+ redirect_url = urljoin(current_url, location)# Re-validate the redirect target to prevent SSRF via# open-redirect to internal/cloud-metadata endpoints._validate_fetch_url(redirect_url)current_url = redirect_urlcontinue- resp.raise_for_status()- chunks: List[bytes] = []- total = 0- for chunk in resp.iter_content(65536):- total += len(chunk)- if total > _MAX_FETCH_BYTES:- raise HTTPException(status_code=413, detail="Remote resource exceeds 20 MB limit.")- chunks.append(chunk)- return b"".join(chunks)+ try:+ resp.raise_for_status()+ chunks: List[bytes] = []+ total = 0+ for chunk in resp.iter_content(65536):+ total += len(chunk)+ if total > _MAX_FETCH_BYTES:+ raise HTTPException(status_code=413, detail="Remote resource exceeds 20 MB limit.")+ chunks.append(chunk)+ return b"".join(chunks)+ finally:+ resp.close()raise HTTPException(status_code=502, detail=f"Too many redirects (max {_MAX_REDIRECTS}).")except HTTPException:raisediff --git a/semantica/explorer/routes/sparql.py b/semantica/explorer/routes/sparql.pyindex c110d023..5bab58e4 100644--- a/semantica/explorer/routes/sparql.py+++ b/semantica/explorer/routes/sparql.py@@ -147,7 +147,15 @@ async def execute_sparql(error="Only SELECT, ASK, CONSTRUCT, and DESCRIBE queries are permitted.",)- graph = await asyncio.to_thread(_build_rdflib_graph, session)+ try:+ graph = await asyncio.to_thread(_build_rdflib_graph, session)+ except ValueError as exc:+ return SparqlResponse(+ columns=[],+ rows=[],+ total=0,+ error=str(exc),+ )async with _sparql_semaphore:try:diff --git a/semantica/vector_store/vector_store.py b/semantica/vector_store/vector_store.pyindex 02f21d09..c1f9b53e 100644--- a/semantica/vector_store/vector_store.py+++ b/semantica/vector_store/vector_store.py@@ -590,7 +590,7 @@ class VectorStore:# pickle is intentionally avoided to prevent arbitrary code execution# if a malicious .pkl file is placed in the store directory.data = {- "vectors": {k: list(v) if hasattr(v, "tolist") else v+ "vectors": {k: v.tolist() if hasattr(v, "tolist") else vfor k, v in getattr(self, "vectors", {}).items()},"metadata": getattr(self, "metadata", {}),"config": self.config,diff --git a/tests/explorer/test_ontology_ssrf.py b/tests/explorer/test_ontology_ssrf.pynew file mode 100644index 00000000..fe9de35b--- /dev/null+++ b/tests/explorer/test_ontology_ssrf.py@@ -0,0 +1,93 @@+"""Regression tests for outbound URL fetching in ontology.py (SSRF hardening).++`_fetch_url_sync` disables `requests`' automatic redirect following and+re-validates every hop with `_validate_fetch_url` (see GHSA-8c7v-62gr-hj6g:+unvalidated redirect targets previously let a public first hop 302 the+server into fetching cloud metadata / loopback services).++These tests cover the redirect-handling logic itself: relative `Location`+headers must resolve correctly instead of being rejected outright, redirect+targets that resolve to private/loopback addresses must still be blocked,+and every response must be closed (no leaked connections across hops).+"""++import socket+from unittest.mock import MagicMock, patch++import pytest++from semantica.explorer.routes import ontology as ontology_mod+++def _fake_getaddrinfo(host, *args, **kwargs):+ # These tests are about the redirect-handling logic, not the address+ # classifier itself, so every host resolves to a public IP unless a+ # test overrides the side_effect to simulate an internal target.+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 0))]+++def _make_response(is_redirect=False, is_permanent=False, location=None, body=b"ok"):+ resp = MagicMock()+ resp.is_redirect = is_redirect+ resp.is_permanent_redirect = is_permanent+ resp.headers = {"Location": location} if location else {}+ resp.raise_for_status = MagicMock()+ resp.iter_content = MagicMock(return_value=iter([body]))+ resp.close = MagicMock()+ return resp++[email protected](ontology_mod.socket, "getaddrinfo", side_effect=_fake_getaddrinfo)+def test_relative_redirect_location_is_resolved(mock_getaddrinfo):+ """A relative Location header (e.g. '/ontology.ttl') must resolve against+ the current URL via urljoin, not be rejected as a malformed URL."""+ redirect_resp = _make_response(is_redirect=True, location="/ontology.ttl")+ final_resp = _make_response(body=b"final content")++ with patch("requests.get", side_effect=[redirect_resp, final_resp]) as mock_get:+ result = ontology_mod._fetch_url_sync("http://example.org/start")++ assert result == b"final content"+ second_call_url = mock_get.call_args_list[1].args[0]+ assert second_call_url == "http://example.org/ontology.ttl"+ redirect_resp.close.assert_called_once()+ final_resp.close.assert_called_once()++[email protected](ontology_mod.socket, "getaddrinfo", side_effect=_fake_getaddrinfo)+def test_redirect_to_private_ip_is_rejected(mock_getaddrinfo):+ """Re-validation must reject a redirect target resolving to a private+ address even though the first hop was a validated public URL — this is+ the exact GHSA-8c7v scenario: public first hop, malicious redirect."""+ def getaddrinfo_side_effect(host, *a, **k):+ if host == "internal.example":+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("169.254.169.254", 0))]+ return _fake_getaddrinfo(host, *a, **k)++ mock_getaddrinfo.side_effect = getaddrinfo_side_effect+ redirect_resp = _make_response(is_redirect=True, location="http://internal.example/latest/meta-data/")++ with patch("requests.get", side_effect=[redirect_resp]):+ with pytest.raises(ontology_mod.HTTPException) as exc_info:+ ontology_mod._fetch_url_sync("http://example.org/start")++ assert exc_info.value.status_code == 422+ redirect_resp.close.assert_called_once()++[email protected](ontology_mod.socket, "getaddrinfo", side_effect=_fake_getaddrinfo)+def test_final_response_is_closed(mock_getaddrinfo):+ final_resp = _make_response(body=b"content")+ with patch("requests.get", side_effect=[final_resp]):+ ontology_mod._fetch_url_sync("http://example.org/start")+ final_resp.close.assert_called_once()++[email protected](ontology_mod.socket, "getaddrinfo", side_effect=_fake_getaddrinfo)+def test_redirect_chain_exceeding_cap_is_rejected(mock_getaddrinfo):+ responses = [_make_response(is_redirect=True, location=f"/hop{i}") for i in range(10)]+ with patch("requests.get", side_effect=responses):+ with pytest.raises(ontology_mod.HTTPException) as exc_info:+ ontology_mod._fetch_url_sync("http://example.org/start")+ assert exc_info.value.status_code == 502+ assert all(r.close.called for r in responses[:6])diff --git a/tests/explorer/test_sparql_route.py b/tests/explorer/test_sparql_route.pyindex 36dacce5..77cc5b71 100644--- a/tests/explorer/test_sparql_route.py+++ b/tests/explorer/test_sparql_route.py@@ -290,6 +290,20 @@ def test_query_timeout_returns_clean_error_not_a_crash(client):assert payload["rows"] == []+def test_oversized_graph_returns_clean_error_not_a_crash(client):+ """The DoS-prevention node cap (GHSA-8c7v-adjacent hardening) must return+ a normal SparqlResponse error, not an unhandled 500. Regression test for+ a bug where _build_rdflib_graph's ValueError was raised outside of+ execute_sparql's try/except, before the semaphore block."""+ with patch.object(sparql_mod, "_SPARQL_MAX_GRAPH_NODES", 1):+ resp = _post(client, "SELECT ?s WHERE { ?s a <http://semantica.local/entity/language> }")+ assert resp.status_code == 200+ payload = resp.json()+ assert payload["error"] is not None+ assert "more than" in payload["error"].lower()+ assert payload["rows"] == []++# ---------------------------------------------------------------------------# Data-mapping fidelity: does the graph->RDF projection reflect session state?# ---------------------------------------------------------------------------diff --git a/tests/vector_store/test_vector_store.py b/tests/vector_store/test_vector_store.pyindex 5badcf24..c4001606 100644--- a/tests/vector_store/test_vector_store.py+++ b/tests/vector_store/test_vector_store.py@@ -1,3 +1,6 @@+import json+import shutil+import tempfileimport unittestfrom unittest.mock import MagicMock, patchimport numpy as np@@ -134,5 +137,48 @@ class TestVectorStore(unittest.TestCase):self.assertTrue(mock_backend.called)+ def test_save_load_roundtrip_numpy_vectors(self):+ """save()/load() must handle numpy float32 vectors without raising.++ Regression test: json.dump() rejects numpy scalar types, so a naive+ `list(v)` conversion (which yields np.float32 elements, not native+ floats) raises TypeError. `v.tolist()` converts recursively to+ native Python floats and must be used instead.+ """+ store = VectorStore(backend="inmemory", dimension=3)+ store.vectors = {"v1": np.array([0.1, 0.2, 0.3], dtype=np.float32)}+ store.metadata = {"v1": {"id": "1"}}++ tmpdir = tempfile.mkdtemp()+ try:+ store.save(tmpdir) # must not raise TypeError++ # The JSON file itself must be valid and free of numpy types.+ with open(f"{tmpdir}/store_data.json", "r", encoding="utf-8") as f:+ data = json.load(f)+ self.assertTrue(all(isinstance(x, float) for x in data["vectors"]["v1"]))++ loaded = VectorStore(backend="inmemory", dimension=3)+ loaded.load(tmpdir)+ np.testing.assert_allclose(+ loaded.vectors["v1"], [0.1, 0.2, 0.3], rtol=1e-6+ )+ self.assertEqual(loaded.metadata["v1"], {"id": "1"})+ finally:+ shutil.rmtree(tmpdir, ignore_errors=True)++ def test_load_rejects_legacy_pickle(self):+ """load() must refuse legacy .pkl stores rather than deserializing them."""+ store = VectorStore(backend="inmemory", dimension=3)+ tmpdir = tempfile.mkdtemp()+ try:+ with open(f"{tmpdir}/store_data.pkl", "wb") as f:+ f.write(b"not a real pickle, just needs to exist")+ with self.assertRaises(RuntimeError):+ store.load(tmpdir)+ finally:+ shutil.rmtree(tmpdir, ignore_errors=True)++if __name__ == '__main__':unittest.main()