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
feat(ingest): add ServiceNow Table API ingestor (#1577) (#1658)
Vladimir Babin5eedbb4e5e4d
diff --git a/README.md b/README.mdindex 395309c4..0fe05567 100644--- a/README.md+++ b/README.md@@ -1548,6 +1548,7 @@ pip install "semantica[tripletstore-oxigraph]" # Embedded in-memory/on-disk RDFpip install "semantica[db-snowflake]" # Snowflakepip install "semantica[db-databricks]" # Databricks (SDK + SQL connector)pip install "semantica[ingest-sap]" # SAP OData+pip install "semantica[ingest-servicenow]" # ServiceNow Table APIpip install "semantica[ingest-parquet]" # Parquet / PyArrowpip install "semantica[ingest-arrow]" # Apache Arrow, Feather, IPCpip install "semantica[watch]" # Directory file watcherdiff --git a/docs/docs.json b/docs/docs.jsonindex 1fc129fe..48a07d27 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -112,6 +112,7 @@"integrations/airflow","integrations/redshift","integrations/powerbi",+ "integrations/servicenow","integrations/looker"]},diff --git a/docs/integrations/servicenow.md b/docs/integrations/servicenow.mdnew file mode 100644index 00000000..679bf8ab--- /dev/null+++ b/docs/integrations/servicenow.md@@ -0,0 +1,97 @@+---+title: "ServiceNow Integration"+description: "Ingest CMDB configuration items, incidents, changes and any other ServiceNow table into Semantica's KG pipeline via the Table API."+icon: "server"+---++> Pull ServiceNow table records into Semantica using the Table API with Basic or OAuth2 authentication.+++## Installation++```bash+pip install "semantica[ingest-servicenow]"+```++The connector only needs `requests`, which already ships with Semantica's core, so the extra is a no-op today; it exists so the dependency is declared explicitly. The module is a lazy export: `import semantica.ingest` does not load it until you first touch `ServiceNowIngestor`.+++## Basic Usage++```python+import os+from semantica.ingest import ServiceNowIngestor++ingestor = ServiceNowIngestor(+ instance_url=os.getenv("SERVICENOW_INSTANCE_URL"),+ username=os.getenv("SERVICENOW_USERNAME"),+ password=os.getenv("SERVICENOW_PASSWORD"),+)++data = ingestor.ingest_table("cmdb_ci_server", query="operational_status=1")+documents = ingestor.export_as_documents(data)++print(f"{data.count} record(s) from {data.table}")+```++<Tip>+Use environment variables (or a `.env` file with `python-dotenv`) to keep credentials out of source code. `ServiceNowIngestor()` with no arguments reads from `SERVICENOW_*` environment variables automatically.+</Tip>+++## Authentication++| Setting | Argument | Environment variable |+| --- | --- | --- |+| Instance URL (`https://<instance>.service-now.com`) | `instance_url` | `SERVICENOW_INSTANCE_URL` |+| Auth flow (`basic` or `oauth2`, optional) | `auth` | `SERVICENOW_AUTH` |+| Username | `username` | `SERVICENOW_USERNAME` |+| Password | `password` | `SERVICENOW_PASSWORD` |+| OAuth2 client ID | `client_id` | `SERVICENOW_CLIENT_ID` |+| OAuth2 client secret | `client_secret` | `SERVICENOW_CLIENT_SECRET` |++- **Basic** — the default when only `username`/`password` are set.+- **OAuth2** — selected automatically when `client_id` is set. The token is fetched from `<instance_url>/oauth_token.do` with the `password` grant when `username`/`password` are also present, otherwise with `client_credentials`.++Missing configuration raises `ValidationError` before any network call is made.+++## Querying a Table++`ingest_table` maps directly onto the Table API query parameters:++```python+data = ingestor.ingest_table(+ "incident",+ query="active=true^priority=1", # sysparm_query (encoded query)+ fields=["sys_id", "number", "short_description", "cmdb_ci"],+ limit=500, # stop after 500 rows+ batch_size=200, # sysparm_limit per request+ display_value="all", # raw + display values per field+)+```++Pagination is offset based (`sysparm_limit` / `sysparm_offset`) and is followed until the table is exhausted or `limit` rows have been collected. Reference-field `link` objects are dropped by default (`sysparm_exclude_reference_link=true`); pass `exclude_reference_link=False` to keep them.++CMDB relationships live in `cmdb_rel_ci`:++```python+rels = ingestor.ingest_table("cmdb_rel_ci", fields=["parent", "child", "type"])+```+++## Document Output++`export_as_documents` flattens each record to a dict with `id` (the record's `sys_id`), `name` (resolved from `name`, `number` or `short_description`), `source` (the instance URL) and `table`, plus every field returned by the API, so the output feeds directly into `GraphBuilder`:++```python+from semantica.kg import GraphBuilder++documents = ingestor.export_as_documents(data)+graph = GraphBuilder().build(documents)+```+++## Security++Every outbound HTTP call — including the OAuth2 token request — goes through Semantica's shared SSRF guard, so a user-supplied instance URL cannot reach private, loopback or link-local address space. Set `allow_private_ips=True` only for self-hosted deployments that genuinely need it.diff --git a/pyproject.toml b/pyproject.tomlindex 6024b1bd..7b0ecfde 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -132,6 +132,7 @@ ingest-looker = ["looker-sdk>=24.0.0"]ingest-parquet = ["pyarrow>=24.0.0"]ingest-arrow = ["pyarrow>=24.0.0"]ingest-sap = ["requests>=2.28.0"]+ingest-servicenow = ["requests>=2.28.0"]ingest-airflow = ["requests>=2.28.0"]ingest-git = ["GitPython>=3.1.58"]diff --git a/semantica/ingest/__init__.py b/semantica/ingest/__init__.pyindex 4440750a..e1018462 100644--- a/semantica/ingest/__init__.py+++ b/semantica/ingest/__init__.py@@ -148,6 +148,11 @@ if TYPE_CHECKING:SalesforceData,SalesforceIngestor,)+ from .servicenow_ingestor import (+ ServiceNowConnector,+ ServiceNowData,+ ServiceNowIngestor,+ )from .config import IngestConfig, ingest_configfrom .file_ingestor import (@@ -240,6 +245,10 @@ _LAZY_EXPORTS: Dict[str, Tuple[str, str]] = {"SAPIngestor": (".sap_ingestor", "SAPIngestor"),"SAPODataEntity": (".sap_ingestor", "SAPODataEntity"),"SAPODataConnector": (".sap_ingestor", "SAPODataConnector"),+ # ServiceNow Table API ingestion+ "ServiceNowIngestor": (".servicenow_ingestor", "ServiceNowIngestor"),+ "ServiceNowData": (".servicenow_ingestor", "ServiceNowData"),+ "ServiceNowConnector": (".servicenow_ingestor", "ServiceNowConnector"),# Apache Airflow ingestion"AirflowIngestor": (".airflow_ingestor", "AirflowIngestor"),"AirflowData": (".airflow_ingestor", "AirflowData"),@@ -505,6 +514,10 @@ __all__ = ["SAPIngestor","SAPODataEntity","SAPODataConnector",+ # ServiceNow Table API ingestion+ "ServiceNowIngestor",+ "ServiceNowData",+ "ServiceNowConnector",# Apache Airflow ingestion"AirflowIngestor","AirflowData",diff --git a/semantica/ingest/servicenow_ingestor.py b/semantica/ingest/servicenow_ingestor.pynew file mode 100644index 00000000..023007a7--- /dev/null+++ b/semantica/ingest/servicenow_ingestor.py@@ -0,0 +1,497 @@+"""ServiceNow Table API ingestion module.++Pulls records from a ServiceNow table (CMDB configuration items, relationships,+incidents, changes, ...) and flattens them into document dicts that the+pipeline can feed to ``GraphBuilder``.++Design notes+------------+Three classes, matching the SAP OData ingestor:+ - ``ServiceNowData``: the rows pulled from one table (``records``,+ ``count``, ``instance``, ``table``), flattened to document dicts for+ ``GraphBuilder`` via ``export_as_documents``.+ - ``ServiceNowConnector``: auth (Basic or OAuth2) + the shared,+ SSRF-guarded :mod:`requests` session. *Every* outbound request,+ including the OAuth2 token exchange, goes through+ ``request_with_ssrf_guard``.+ - ``ServiceNowIngestor``: ``ingest_table`` and ``export_as_documents``+ (plus ``close`` for symmetry with the SQL connectors).++Pagination+----------+The Table API is offset based: ``sysparm_limit`` / ``sysparm_offset``.+``ingest_table`` walks the table in ``batch_size`` pages until a short page+comes back (or ``limit`` rows have been collected).+"""++from __future__ import annotations++import base64+import os+from dataclasses import dataclass, field+from datetime import datetime+from typing import Any, Dict, List, Optional, Sequence, Union+from urllib.parse import urlparse++import requests+from requests.adapters import HTTPAdapter++try:+ from urllib3.util.retry import Retry+except (ImportError, OSError): # pragma: no cover - old urllib3 layout+ from requests.packages.urllib3.util.retry import Retry # type: ignore++from ..utils.exceptions import ProcessingError, ValidationError+from ..utils.logging import get_logger+from .ssrf import parse_bool, request_with_ssrf_guard++__all__ = [+ "ServiceNowData",+ "ServiceNowConnector",+ "ServiceNowIngestor",+]++_logger = get_logger("servicenow_ingestor")++_TABLE_API = "/api/now/table/"+_TOKEN_PATH = "/oauth_token.do"++# Record columns whose names collide with the discriminators GraphBuilder+# uses (``source``/``target`` mark a relationship; ``id``/``table`` are+# canonical provenance). A raw ServiceNow value under any of these would+# either clobber connector provenance or flip an entity row into a+# relationship, so they are relocated into ``_RAW_RECORD_KEY``.+_RESERVED_RECORD_KEYS = ("id", "source", "target", "table")+_RAW_RECORD_KEY = "servicenow_fields"+++@dataclass+class ServiceNowData:+ """Records fetched from one ServiceNow table."""++ records: List[Dict[str, Any]]+ table: str+ count: int+ instance: str+ ingested_at: datetime = field(default_factory=datetime.now)++ def to_documents(self) -> List[Dict[str, Any]]:+ """Flatten each record to a document dict ``GraphBuilder`` can consume.++ GraphBuilder only treats a dict as an entity when it carries+ ``id``/``entity_id``/``name`` (or ``text``+``type``), and treats one+ carrying both ``source`` and ``target`` as a *relationship*. Every+ ServiceNow record has a ``sys_id``; that becomes ``id``, and ``name``+ is resolved from the record's own ``name``, ``number`` or+ ``short_description`` (falling back to ``table:index``).++ ServiceNow columns whose names collide with those discriminators or+ with the connector provenance keys (``id``/``source``/``target``/+ ``table``) are moved into the nested ``servicenow_fields`` mapping, so+ a row that happens to have a ``target`` column still builds as an+ entity rather than a spurious relationship, and canonical provenance+ (``source`` = instance, ``table`` = table) is never overwritten.+ """+ docs: List[Dict[str, Any]] = []+ for index, record in enumerate(self.records):+ doc: Dict[str, Any] = {}+ raw: Dict[str, Any] = {}+ for key, value in record.items():+ if key in _RESERVED_RECORD_KEYS:+ raw[key] = value+ else:+ doc[key] = value+ sys_id = _scalar(record.get("sys_id"))+ doc["id"] = sys_id or f"{self.table}:{index}"+ if isinstance(doc.get("name"), dict):+ doc["name"] = _scalar(doc["name"])+ doc.setdefault("name", self._name_value(record) or sys_id or self.table)+ doc["source"] = self.instance+ doc["table"] = self.table+ if raw:+ doc[_RAW_RECORD_KEY] = raw+ docs.append(doc)+ return docs++ @staticmethod+ def _name_value(record: Dict[str, Any]) -> str:+ for key in ("name", "number", "short_description"):+ value = _scalar(record.get(key))+ if value:+ return value+ return ""+++def _scalar(value: Any) -> str:+ """Unwrap ``sysparm_display_value=all`` objects to their display string."""+ if isinstance(value, dict):+ value = value.get("display_value") or value.get("value")+ if value in (None, ""):+ return ""+ return str(value)+++class ServiceNowConnector:+ """Connection + authentication management for a ServiceNow instance.++ - **Basic**: ``username``/``password`` attached as an+ ``Authorization: Basic`` header.+ - **OAuth2**: ``client_id``/``client_secret`` exchanged at+ ``<instance_url>/oauth_token.do``. ServiceNow's inbound OAuth issues+ tokens for the *resource owner password* grant when ``username`` and+ ``password`` are also set, otherwise ``client_credentials`` is used.++ Example usage::++ >>> connector = ServiceNowConnector(+ ... instance_url="https://snow.example",+ ... username="u", password="p",+ ... )+ >>> session = connector.get_session()+ """++ def __init__(+ self,+ instance_url: Optional[str] = None,+ *,+ auth: Optional[str] = None,+ username: Optional[str] = None,+ password: Optional[str] = None,+ client_id: Optional[str] = None,+ client_secret: Optional[str] = None,+ allow_private_ips: bool = False,+ **config: Any,+ ) -> None:+ """Initialize the ServiceNow connector.++ Args:+ instance_url: Instance root, e.g. ``https://snow.example``.+ auth: Explicit auth flow, ``"basic"`` or ``"oauth2"``. When+ omitted, ``oauth2`` is used if ``client_id`` is set.+ username: Basic-auth user (also the OAuth2 password-grant user).+ password: Basic-auth password.+ client_id: OAuth2 client id.+ client_secret: OAuth2 client secret.+ allow_private_ips: Opt into private/loopback/link-local endpoints.+ Defaults to False (SSRF-safe).+ **config: Extra options, notably ``timeout``, ``max_retries``,+ ``backoff_factor``, ``headers``.+ """+ self.logger = _logger+ self.instance_url = (+ instance_url or os.getenv("SERVICENOW_INSTANCE_URL") or ""+ ).rstrip("/")+ self.auth = (auth or os.getenv("SERVICENOW_AUTH") or "").lower()+ self.username = username or os.getenv("SERVICENOW_USERNAME")+ self.password = password or os.getenv("SERVICENOW_PASSWORD")+ self.client_id = client_id or os.getenv("SERVICENOW_CLIENT_ID")+ self.client_secret = client_secret or os.getenv("SERVICENOW_CLIENT_SECRET")+ self.allow_private_ips = parse_bool(+ config.pop("allow_private_ips", allow_private_ips), default=False+ )+ self.config = config++ if not self.instance_url:+ raise ValidationError(+ "ServiceNow instance_url is required. Provide via 'instance_url' "+ "or SERVICENOW_INSTANCE_URL environment variable."+ )+ parsed = urlparse(self.instance_url)+ if parsed.scheme not in ("http", "https") or not parsed.hostname:+ raise ValidationError(+ f"ServiceNow instance_url must be an absolute http(s) URL, "+ f"got {self.instance_url!r}."+ )+ if parsed.query or parsed.fragment:+ raise ValidationError(+ f"ServiceNow instance_url must not carry a query or fragment "+ f"component, got {self.instance_url!r}."+ )++ if not self.auth:+ self.auth = "oauth2" if self.client_id else "basic"+ if self.auth in ("oauth2", "oauth"):+ self.auth = "oauth2"+ if not (self.client_id and self.client_secret):+ raise ValidationError(+ "ServiceNow OAuth2 flow requires client_id and client_secret."+ )+ elif self.auth == "basic":+ if not (self.username and self.password):+ raise ValidationError(+ "ServiceNow Basic flow requires username and password."+ )+ else:+ raise ValidationError(+ f"ServiceNow auth must be 'basic' or 'oauth2', got {self.auth!r}."+ )++ self.session = requests.Session()+ retry_strategy = Retry(+ total=self.config.get("max_retries", 3),+ backoff_factor=self.config.get("backoff_factor", 1),+ status_forcelist=[429, 500, 502, 503, 504],+ )+ adapter = HTTPAdapter(max_retries=retry_strategy)+ self.session.mount("http://", adapter)+ self.session.mount("https://", adapter)+ self.session.headers["Accept"] = "application/json"+ default_headers = self.config.get("headers", {})+ if default_headers:+ self.session.headers.update(default_headers)++ self._token: Optional[str] = None+ self.logger.debug(+ "ServiceNow connector initialized (instance=%s, auth=%s, "+ "allow_private_ips=%s)",+ self.instance_url,+ self.auth,+ self.allow_private_ips,+ )++ @property+ def token_url(self) -> str:+ return self.instance_url + _TOKEN_PATH++ def get_session(self) -> requests.Session:+ """Return an authenticated session for Table API requests.++ Basic credentials are attached eagerly; for OAuth2 a token is+ fetched (and cached) on first use. The token is not refreshed, so a+ job that runs past its TTL will fail with 401 -- re-create the+ connector instead.+ """+ if self.auth == "basic":+ self.session.headers["Authorization"] = "Basic " + self._basic_header()+ return self.session+ if self._token is None:+ self._token = self._fetch_token()+ self.session.headers["Authorization"] = "Bearer " + self._token+ return self.session++ def _basic_header(self) -> str:+ pair = f"{self.username}:{self.password or ''}".encode("utf-8")+ return base64.b64encode(pair).decode("ascii")++ def _fetch_token(self) -> str:+ """Perform the OAuth2 token exchange (SSRF-guarded)."""+ body: Dict[str, str] = {+ "client_id": self.client_id or "",+ "client_secret": self.client_secret or "",+ }+ if self.username and self.password:+ body["grant_type"] = "password"+ body["username"] = self.username+ body["password"] = self.password+ else:+ body["grant_type"] = "client_credentials"+ resp = request_with_ssrf_guard(+ "POST",+ self.token_url,+ session=self.session,+ allow_private_ips=self.allow_private_ips,+ allow_private_ips_on_redirect=False,+ data=body,+ timeout=self.config.get("timeout", 30),+ )+ try:+ resp.raise_for_status()+ except requests.exceptions.RequestException as exc:+ raise ProcessingError(+ f"ServiceNow OAuth2 token exchange failed: {exc}"+ ) from exc+ try:+ payload = resp.json()+ except ValueError as exc:+ raise ProcessingError(+ "ServiceNow OAuth2 token endpoint did not return JSON."+ ) from exc+ token = payload.get("access_token") if isinstance(payload, dict) else None+ if not token:+ raise ProcessingError(+ "ServiceNow OAuth2 token response missing 'access_token'."+ )+ return str(token)++ def close(self) -> None:+ """Close the underlying :mod:`requests` session."""+ self.session.close()+++class ServiceNowIngestor:+ """Ingest records from a ServiceNow table.++ Example usage::++ >>> from semantica.ingest import ServiceNowIngestor+ >>> ing = ServiceNowIngestor(+ ... instance_url="https://snow.example",+ ... username="u", password="p", # or client_id/client_secret+ ... )+ >>> data = ing.ingest_table("cmdb_ci_server", query="operational_status=1")+ >>> docs = ing.export_as_documents(data)+ """++ def __init__(+ self,+ instance_url: Optional[str] = None,+ connector: Optional[ServiceNowConnector] = None,+ **config: Any,+ ) -> None:+ """Initialize the ServiceNow ingestor.++ Args:+ instance_url: Instance root URL. Ignored if ``connector`` is given.+ connector: An existing :class:`ServiceNowConnector`.+ **config: Passed to :class:`ServiceNowConnector` when one is+ created.+ """+ self.logger = _logger+ self.connector = connector or ServiceNowConnector(+ instance_url=instance_url, **config+ )++ def ingest_table(+ self,+ table: Optional[str] = None,+ *,+ query: Optional[str] = None,+ fields: Optional[Union[str, Sequence[str]]] = None,+ limit: Optional[int] = None,+ offset: int = 0,+ batch_size: int = 100,+ display_value: Union[bool, str] = False,+ exclude_reference_link: bool = True,+ ) -> ServiceNowData:+ """Fetch pages of *table* from the Table API.++ Args:+ table: Table name, e.g. ``"incident"`` or ``"cmdb_ci_server"``.+ query: Encoded query for ``sysparm_query``+ (e.g. ``"active=true^priority=1"``).+ fields: Field names for ``sysparm_fields`` (list or comma string).+ limit: Maximum number of rows to return.+ offset: Number of leading rows to skip.+ batch_size: ``sysparm_limit`` per request.+ display_value: ``sysparm_display_value`` -- ``False`` (raw+ values), ``True`` (display values) or ``"all"`` (both).+ exclude_reference_link: Drop ``link`` objects from reference+ fields (``sysparm_exclude_reference_link``).++ Returns:+ A single :class:`ServiceNowData` holding every fetched record.+ """+ if not table:+ raise ValidationError("ServiceNow 'table' is required.")+ if limit is not None and limit < 0:+ raise ValidationError("ServiceNow 'limit' must be >= 0 (got %r)" % limit)+ if offset < 0:+ raise ValidationError("ServiceNow 'offset' must be >= 0 (got %r)" % offset)+ if batch_size <= 0:+ raise ValidationError(+ "ServiceNow 'batch_size' must be > 0 (got %r)" % batch_size+ )+ instance = self.connector.instance_url+ if limit == 0:+ return ServiceNowData(records=[], table=table, count=0, instance=instance)++ url = instance + _TABLE_API + table+ session = self.connector.get_session()+ records: List[Dict[str, Any]] = []+ current_offset = offset+ base_params = self._query_params(+ query, fields, display_value, exclude_reference_link+ )++ while True:+ page_size = batch_size+ if limit is not None:+ page_size = min(batch_size, limit - len(records))+ params = dict(base_params)+ params["sysparm_limit"] = str(page_size)+ params["sysparm_offset"] = str(current_offset)++ resp = request_with_ssrf_guard(+ "GET",+ url,+ session=session,+ allow_private_ips=self.connector.allow_private_ips,+ allow_private_ips_on_redirect=False,+ params=params,+ timeout=self.connector.config.get("timeout", 30),+ )+ try:+ resp.raise_for_status()+ except requests.exceptions.RequestException as exc:+ self.logger.error("Failed to fetch ServiceNow table %s: %s", table, exc)+ raise ProcessingError(+ f"Failed to fetch ServiceNow table {table}: {exc}"+ ) from exc++ rows = self._parse_page(resp)+ for raw_row in rows:+ records.append(+ raw_row if isinstance(raw_row, dict) else {"value": raw_row}+ )++ self.logger.debug(+ "Fetched %d rows from %s (offset=%d)", len(rows), table, current_offset+ )+ if len(rows) < page_size:+ break+ if limit is not None and len(records) >= limit:+ break+ current_offset += len(rows)++ return ServiceNowData(+ records=records, table=table, count=len(records), instance=instance+ )++ @staticmethod+ def _query_params(+ query: Optional[str],+ fields: Optional[Union[str, Sequence[str]]],+ display_value: Union[bool, str],+ exclude_reference_link: bool,+ ) -> Dict[str, str]:+ params: Dict[str, str] = {}+ if query:+ params["sysparm_query"] = query+ if fields:+ if not isinstance(fields, str):+ fields = ",".join(fields)+ selected = [f.strip() for f in fields.split(",") if f.strip()]+ if "sys_id" not in selected:+ selected.insert(0, "sys_id")+ params["sysparm_fields"] = ",".join(selected)+ if isinstance(display_value, str):+ params["sysparm_display_value"] = display_value+ else:+ params["sysparm_display_value"] = "true" if display_value else "false"+ if exclude_reference_link:+ params["sysparm_exclude_reference_link"] = "true"+ return params++ @staticmethod+ def _parse_page(resp: requests.Response) -> List[Any]:+ try:+ payload = resp.json()+ except ValueError as exc:+ raise ProcessingError(+ f"ServiceNow Table API response is not JSON: {exc}"+ ) from exc+ rows = payload.get("result") if isinstance(payload, dict) else payload+ if not isinstance(rows, list):+ raise ProcessingError(+ "ServiceNow Table API payload has no 'result' list (got %s)"+ % type(rows).__name__+ )+ return rows++ def export_as_documents(self, data: ServiceNowData) -> List[Dict[str, Any]]:+ """Convert ingested records to flat document dicts for ``GraphBuilder``."""+ return data.to_documents()++ def close(self) -> None:+ """Close the underlying connector's session."""+ self.connector.close()diff --git a/tests/ingest/test_servicenow_ingestor.py b/tests/ingest/test_servicenow_ingestor.pynew file mode 100644index 00000000..f85d3cea--- /dev/null+++ b/tests/ingest/test_servicenow_ingestor.py@@ -0,0 +1,485 @@+"""Tests for the ServiceNow Table API ingestor.++The connector never touches a live instance: every outbound request goes+through ``semantica.ingest.ssrf.request_with_ssrf_guard``, so these tests+patch that single entry point and drive the connector / ingestor with canned+responses.++Covered:+- Basic and OAuth2 (client-credentials and password grant) credential flows+- SSRF guard is used for data *and* token-exchange requests+- ``sysparm_limit``/``sysparm_offset`` pagination, ``limit``/``offset``+- query / fields / display_value passthrough+- error paths (HTTP error, non-JSON body, malformed payload, bad arguments)+- ``export_as_documents`` yields the flat document shape GraphBuilder expects+"""++import base64+from unittest.mock import MagicMock, patch++import pytest+import requests++from semantica.ingest import (+ ServiceNowConnector,+ ServiceNowData,+ ServiceNowIngestor,+)+from semantica.utils.exceptions import ProcessingError, ValidationError++GUARD = "semantica.ingest.servicenow_ingestor.request_with_ssrf_guard"+INSTANCE = "https://snow.example"+++def _json_resp(payload, url=INSTANCE, status_code=200):+ resp = MagicMock()+ resp.status_code = status_code+ resp.headers = {"content-type": "application/json"}+ resp.text = ""+ resp.url = url+ if payload is None:+ resp.json.side_effect = ValueError("not json")+ else:+ resp.json.return_value = payload+ if status_code >= 400:+ resp.raise_for_status.side_effect = requests.exceptions.HTTPError(+ f"{status_code} error"+ )+ return resp+++def _result(*rows):+ return {"result": list(rows)}+++def _basic_ingestor(**kw):+ return ServiceNowIngestor(instance_url=INSTANCE, username="u", password="p", **kw)+++class TestConnectorAuth:+ def test_requires_instance_url(self, monkeypatch):+ monkeypatch.delenv("SERVICENOW_INSTANCE_URL", raising=False)+ with pytest.raises(ValidationError):+ ServiceNowConnector(username="u", password="p")++ def test_rejects_non_http_instance_url(self):+ with pytest.raises(ValidationError):+ ServiceNowConnector(instance_url="snow.example", username="u", password="p")++ def test_requires_credentials(self, monkeypatch):+ for var in (+ "SERVICENOW_USERNAME",+ "SERVICENOW_PASSWORD",+ "SERVICENOW_CLIENT_ID",+ "SERVICENOW_CLIENT_SECRET",+ ):+ monkeypatch.delenv(var, raising=False)+ with pytest.raises(ValidationError):+ ServiceNowConnector(instance_url=INSTANCE)++ def test_oauth2_requires_client_secret(self):+ with pytest.raises(ValidationError):+ ServiceNowConnector(instance_url=INSTANCE, client_id="cid")++ def test_unknown_auth_rejected(self):+ with pytest.raises(ValidationError):+ ServiceNowConnector(+ instance_url=INSTANCE, auth="token", username="u", password="p"+ )++ def test_trailing_slash_stripped(self):+ conn = ServiceNowConnector(+ instance_url=INSTANCE + "/", username="u", password="p"+ )+ assert conn.instance_url == INSTANCE+ assert conn.token_url == INSTANCE + "/oauth_token.do"++ def test_rejects_instance_url_with_query(self):+ with pytest.raises(ValidationError):+ ServiceNowConnector(+ instance_url=INSTANCE + "/?x=1", username="u", password="p"+ )++ def test_rejects_instance_url_with_fragment(self):+ with pytest.raises(ValidationError):+ ServiceNowConnector(+ instance_url=INSTANCE + "/#x", username="u", password="p"+ )++ def test_env_configuration(self, monkeypatch):+ monkeypatch.setenv("SERVICENOW_INSTANCE_URL", INSTANCE)+ monkeypatch.setenv("SERVICENOW_USERNAME", "eu")+ monkeypatch.setenv("SERVICENOW_PASSWORD", "ep")+ conn = ServiceNowConnector()+ assert conn.auth == "basic"+ assert conn.username == "eu"++ def test_basic_auth_header_attached(self):+ conn = ServiceNowConnector(instance_url=INSTANCE, username="u", password="p")+ session = conn.get_session()+ expected = base64.b64encode(b"u:p").decode("ascii")+ assert session.headers["Authorization"] == "Basic " + expected+ assert session.headers["Accept"] == "application/json"++ def test_allow_private_ips_string_false_is_false(self):+ conn = ServiceNowConnector(+ instance_url=INSTANCE,+ username="u",+ password="p",+ allow_private_ips="false",+ )+ assert conn.allow_private_ips is False++ def test_oauth_client_credentials_exchange_goes_through_ssrf(self):+ with patch(GUARD) as guard:+ guard.return_value = _json_resp({"access_token": "tok-123"})+ conn = ServiceNowConnector(+ instance_url=INSTANCE, client_id="cid", client_secret="sec"+ )+ session = conn.get_session()+ session = conn.get_session()++ assert guard.call_count == 1+ method, url = guard.call_args[0]+ assert method == "POST"+ assert url == INSTANCE + "/oauth_token.do"+ body = guard.call_args[1]["data"]+ assert body["grant_type"] == "client_credentials"+ assert body["client_id"] == "cid"+ assert session.headers["Authorization"] == "Bearer tok-123"++ def test_token_exchange_pins_private_ip_trust_to_original_host(self):+ with patch(GUARD) as guard:+ guard.return_value = _json_resp({"access_token": "tok-123"})+ conn = ServiceNowConnector(+ instance_url=INSTANCE, client_id="cid", client_secret="sec"+ )+ conn.get_session()+ assert guard.call_args[1]["allow_private_ips_on_redirect"] is False++ def test_oauth_password_grant_when_user_credentials_present(self):+ with patch(GUARD) as guard:+ guard.return_value = _json_resp({"access_token": "tok"})+ conn = ServiceNowConnector(+ instance_url=INSTANCE,+ client_id="cid",+ client_secret="sec",+ username="u",+ password="p",+ )+ conn.get_session()++ body = guard.call_args[1]["data"]+ assert body["grant_type"] == "password"+ assert body["username"] == "u"+ assert body["password"] == "p"++ def test_oauth_token_http_error_raises_processing_error(self):+ with patch(GUARD, return_value=_json_resp({}, status_code=401)):+ conn = ServiceNowConnector(+ instance_url=INSTANCE, client_id="cid", client_secret="sec"+ )+ with pytest.raises(ProcessingError):+ conn.get_session()++ def test_oauth_token_missing_access_token(self):+ with patch(GUARD, return_value=_json_resp({"error": "invalid"})):+ conn = ServiceNowConnector(+ instance_url=INSTANCE, client_id="cid", client_secret="sec"+ )+ with pytest.raises(ProcessingError):+ conn.get_session()++ def test_oauth_token_non_json(self):+ with patch(GUARD, return_value=_json_resp(None)):+ conn = ServiceNowConnector(+ instance_url=INSTANCE, client_id="cid", client_secret="sec"+ )+ with pytest.raises(ProcessingError):+ conn.get_session()+++class TestIngestTable:+ def test_single_page_routes_via_ssrf(self):+ with patch(GUARD) as guard:+ guard.return_value = _json_resp(_result({"sys_id": "1", "number": "INC1"}))+ data = _basic_ingestor().ingest_table("incident")++ assert guard.call_count == 1+ method, url = guard.call_args[0]+ assert method == "GET"+ assert url == INSTANCE + "/api/now/table/incident"+ kwargs = guard.call_args[1]+ assert kwargs["allow_private_ips"] is False+ assert kwargs["params"]["sysparm_limit"] == "100"+ assert kwargs["params"]["sysparm_offset"] == "0"+ assert data.count == 1+ assert data.table == "incident"+ assert data.instance == INSTANCE+ assert data.records == [{"sys_id": "1", "number": "INC1"}]++ def test_offset_pagination_walks_until_short_page(self):+ pages = [+ _result({"sys_id": "1"}, {"sys_id": "2"}),+ _result({"sys_id": "3"}, {"sys_id": "4"}),+ _result({"sys_id": "5"}),+ ]+ offsets = []++ def fake_guard(method, url, **kw):+ offsets.append(kw["params"]["sysparm_offset"])+ return _json_resp(pages[len(offsets) - 1], url)++ with patch(GUARD, side_effect=fake_guard):+ data = _basic_ingestor().ingest_table("cmdb_ci", batch_size=2)++ assert offsets == ["0", "2", "4"]+ assert [r["sys_id"] for r in data.records] == ["1", "2", "3", "4", "5"]+ assert data.count == 5++ def test_exact_multiple_stops_on_empty_page(self):+ pages = [_result({"sys_id": "1"}, {"sys_id": "2"}), _result()]+ calls = []++ def fake_guard(method, url, **kw):+ calls.append(url)+ return _json_resp(pages[len(calls) - 1], url)++ with patch(GUARD, side_effect=fake_guard):+ data = _basic_ingestor().ingest_table("cmdb_ci", batch_size=2)++ assert len(calls) == 2+ assert data.count == 2++ def test_limit_caps_rows_and_page_size(self):+ sizes = []++ def fake_guard(method, url, **kw):+ sizes.append(kw["params"]["sysparm_limit"])+ n = int(kw["params"]["sysparm_limit"])+ return _json_resp(_result(*({"sys_id": str(i)} for i in range(n))), url)++ with patch(GUARD, side_effect=fake_guard):+ data = _basic_ingestor().ingest_table("incident", limit=5, batch_size=2)++ assert sizes == ["2", "2", "1"]+ assert data.count == 5++ def test_offset_passthrough(self):+ with patch(GUARD) as guard:+ guard.return_value = _json_resp(_result({"sys_id": "9"}))+ _basic_ingestor().ingest_table("incident", offset=40)+ assert guard.call_args[1]["params"]["sysparm_offset"] == "40"++ def test_limit_zero_returns_no_rows_and_makes_no_request(self):+ with patch(GUARD) as guard:+ data = _basic_ingestor().ingest_table("incident", limit=0)+ assert guard.call_count == 0+ assert data.count == 0+ assert data.records == []++ def test_query_fields_display_value_passthrough(self):+ with patch(GUARD) as guard:+ guard.return_value = _json_resp(_result())+ _basic_ingestor().ingest_table(+ "incident",+ query="active=true^priority=1",+ fields=["sys_id", "number"],+ display_value="all",+ exclude_reference_link=False,+ )+ params = guard.call_args[1]["params"]+ assert params["sysparm_query"] == "active=true^priority=1"+ assert params["sysparm_fields"] == "sys_id,number"+ assert params["sysparm_display_value"] == "all"+ assert "sysparm_exclude_reference_link" not in params++ def test_default_params(self):+ with patch(GUARD) as guard:+ guard.return_value = _json_resp(_result())+ _basic_ingestor().ingest_table("incident", fields="sys_id,name")+ params = guard.call_args[1]["params"]+ assert params["sysparm_display_value"] == "false"+ assert params["sysparm_exclude_reference_link"] == "true"+ assert params["sysparm_fields"] == "sys_id,name"+ assert "sysparm_query" not in params++ def test_field_selection_always_includes_sys_id(self):+ with patch(GUARD) as guard:+ guard.return_value = _json_resp(_result())+ _basic_ingestor().ingest_table("incident", fields=["number", "priority"])+ selected = guard.call_args[1]["params"]["sysparm_fields"].split(",")+ assert "sys_id" in selected+ assert selected == ["sys_id", "number", "priority"]++ def test_field_selection_keeps_sys_id_once_when_already_requested(self):+ with patch(GUARD) as guard:+ guard.return_value = _json_resp(_result())+ _basic_ingestor().ingest_table("incident", fields="number,sys_id")+ selected = guard.call_args[1]["params"]["sysparm_fields"].split(",")+ assert selected.count("sys_id") == 1+ assert selected == ["number", "sys_id"]++ def test_data_request_pins_private_ip_trust_to_original_host(self):+ with patch(GUARD) as guard:+ guard.return_value = _json_resp(_result())+ _basic_ingestor().ingest_table("incident")+ assert guard.call_args[1]["allow_private_ips_on_redirect"] is False++ def test_requires_table(self):+ with pytest.raises(ValidationError):+ _basic_ingestor().ingest_table()++ def test_negative_limit_rejected(self):+ with pytest.raises(ValidationError):+ _basic_ingestor().ingest_table("incident", limit=-1)++ def test_negative_offset_rejected(self):+ with pytest.raises(ValidationError):+ _basic_ingestor().ingest_table("incident", offset=-1)++ def test_zero_batch_size_rejected(self):+ with pytest.raises(ValidationError):+ _basic_ingestor().ingest_table("incident", batch_size=0)++ def test_http_error_raises_processing_error(self):+ with patch(GUARD, return_value=_json_resp({}, status_code=403)):+ with pytest.raises(ProcessingError):+ _basic_ingestor().ingest_table("incident")++ def test_non_json_response_raises_processing_error(self):+ with patch(GUARD, return_value=_json_resp(None)):+ with pytest.raises(ProcessingError):+ _basic_ingestor().ingest_table("incident")++ def test_malformed_result_rejected(self):+ with patch(GUARD, return_value=_json_resp({"result": {"sys_id": "1"}})):+ with pytest.raises(ProcessingError):+ _basic_ingestor().ingest_table("incident")++ def test_close_closes_session(self):+ ing = _basic_ingestor()+ with patch.object(ing.connector.session, "close") as close:+ ing.close()+ close.assert_called_once()+++class TestExportAsDocuments:+ def test_export_flattens_to_graph_builder_shape(self):+ data = ServiceNowData(+ records=[+ {"sys_id": "abc", "number": "INC0001", "short_description": "Down"},+ {"sys_id": "def", "name": "web-01", "sys_class_name": "cmdb_ci_server"},+ ],+ table="incident",+ count=2,+ instance=INSTANCE,+ )+ docs = ServiceNowIngestor(+ connector=MagicMock(instance_url=INSTANCE)+ ).export_as_documents(data)++ assert docs[0]["id"] == "abc"+ assert docs[0]["name"] == "INC0001"+ assert docs[0]["source"] == INSTANCE+ assert docs[0]["table"] == "incident"+ assert docs[0]["short_description"] == "Down"+ assert docs[1]["id"] == "def"+ assert docs[1]["name"] == "web-01"++ def test_export_unwraps_display_value_objects(self):+ data = ServiceNowData(+ records=[+ {+ "sys_id": {"value": "abc", "display_value": "abc"},+ "name": {"value": "srv", "display_value": "Server 1"},+ }+ ],+ table="cmdb_ci",+ count=1,+ instance=INSTANCE,+ )+ docs = data.to_documents()+ assert docs[0]["id"] == "abc"+ assert docs[0]["name"] == "Server 1"++ def test_export_falls_back_to_table_index(self):+ data = ServiceNowData(+ records=[{"foo": "bar"}], table="incident", count=1, instance=INSTANCE+ )+ docs = data.to_documents()+ assert docs[0]["id"] == "incident:0"+ assert docs[0]["name"] == "incident"++ def test_export_does_not_mutate_records(self):+ record = {"sys_id": "abc"}+ data = ServiceNowData(records=[record], table="t", count=1, instance=INSTANCE)+ data.to_documents()+ assert record == {"sys_id": "abc"}++ def test_record_target_column_stays_an_entity(self):+ data = ServiceNowData(+ records=[{"sys_id": "abc", "name": "rel-row", "target": "cmdb_ci:xyz"}],+ table="cmdb_rel_ci",+ count=1,+ instance=INSTANCE,+ )+ doc = data.to_documents()[0]+ assert "target" not in doc+ assert doc["servicenow_fields"]["target"] == "cmdb_ci:xyz"+ assert doc["id"] == "abc"+ assert doc["name"] == "rel-row"+ assert "source" in doc and "target" not in doc++ def test_record_source_and_table_columns_do_not_override_provenance(self):+ data = ServiceNowData(+ records=[+ {"sys_id": "abc", "source": "email", "table": "sn_customerservice"}+ ],+ table="incident",+ count=1,+ instance=INSTANCE,+ )+ doc = data.to_documents()[0]+ assert doc["source"] == INSTANCE+ assert doc["table"] == "incident"+ assert doc["servicenow_fields"]["source"] == "email"+ assert doc["servicenow_fields"]["table"] == "sn_customerservice"++ def test_record_own_id_column_does_not_override_sys_id(self):+ data = ServiceNowData(+ records=[{"sys_id": "abc", "id": "wrong-id"}],+ table="incident",+ count=1,+ instance=INSTANCE,+ )+ doc = data.to_documents()[0]+ assert doc["id"] == "abc"+ assert doc["servicenow_fields"]["id"] == "wrong-id"++ def test_export_builds_graph_entity_for_row_with_target(self):+ from semantica.kg.graph_builder import GraphBuilder++ data = ServiceNowData(+ records=[{"sys_id": "abc", "name": "srv", "target": "other"}],+ table="cmdb_ci",+ count=1,+ instance=INSTANCE,+ )+ docs = data.to_documents()+ entities: list = []+ relationships: list = []+ GraphBuilder()._process_item(docs[0], entities, relationships)+ assert len(entities) == 1+ assert relationships == []+ assert entities[0]["id"] == "abc"+++class TestLazyExport:+ def test_public_import_through_lazy_export(self):+ import semantica.ingest as ingest++ assert ingest.ServiceNowIngestor is ServiceNowIngestor+ assert ingest.ServiceNowConnector is ServiceNowConnector+ assert ingest.ServiceNowData is ServiceNowData+ assert "ServiceNowIngestor" in ingest.__all__diff --git a/uv.lock b/uv.lockindex e5763913..1730310f 100644--- a/uv.lock+++ b/uv.lock@@ -8382,6 +8382,9 @@ ingest-parquet = [ingest-sap = [{ name = "requests" },]+ingest-servicenow = [+ { name = "requests" },+]langchain = [{ name = "langchain-core" },]@@ -8627,6 +8630,7 @@ requires-dist = [{ name = "requests", specifier = ">=2.34.2" },{ name = "requests", marker = "extra == 'ingest-airflow'", specifier = ">=2.28.0" },{ name = "requests", marker = "extra == 'ingest-sap'", specifier = ">=2.28.0" },+ { name = "requests", marker = "extra == 'ingest-servicenow'", specifier = ">=2.28.0" },{ name = "rich", specifier = ">=12.5.0" },{ name = "scikit-learn", specifier = ">=1.7.2" },{ name = "scipy", specifier = ">=1.13.1" },@@ -8658,7 +8662,7 @@ requires-dist = [{ name = "weaviate-client", marker = "extra == 'vectorstore-weaviate'", specifier = ">=4.0.0" },{ name = "websockets", marker = "extra == 'explorer'", specifier = ">=15.0.1" },]-provides-extras = ["llm-openai", "llm-groq", "llm-gemini", "llm-anthropic", "llm-ollama", "llm-deepseek", "llm-novita", "llm-litellm", "llm-instructor", "llm-all", "documents", "parse-docling", "parse-pdf", "shacl", "db-snowflake", "db-databricks", "db-arrow", "db-salesforce", "db-redshift", "db-bigquery", "ingest-looker", "ingest-parquet", "ingest-arrow", "ingest-sap", "ingest-airflow", "ingest-git", "db-all", "models-huggingface", "embeddings-local", "nlp-spacy", "graph-neo4j", "graph-falkordb", "graph-amazon-neptune", "graph-apache-age", "graph-embeddings", "graph-all", "tripletstore-oxigraph", "vectorstore-faiss", "vectorstore-qdrant", "vectorstore-weaviate", "vectorstore-pinecone", "vectorstore-milvus", "vectorstore-pgvector", "vectorstore-sqlite", "vectorstore-all", "infra", "cloud", "monitoring", "viz", "media", "gpu", "agno", "langchain", "google-adk", "open-ontologies", "watch", "split-tiktoken", "split-community", "split-topic", "split-all", "explorer", "explorer-lite", "all"]+provides-extras = ["llm-openai", "llm-groq", "llm-gemini", "llm-anthropic", "llm-ollama", "llm-deepseek", "llm-novita", "llm-litellm", "llm-instructor", "llm-all", "documents", "parse-docling", "parse-pdf", "shacl", "db-snowflake", "db-databricks", "db-arrow", "db-salesforce", "db-redshift", "db-bigquery", "ingest-looker", "ingest-parquet", "ingest-arrow", "ingest-sap", "ingest-servicenow", "ingest-airflow", "ingest-git", "db-all", "models-huggingface", "embeddings-local", "nlp-spacy", "graph-neo4j", "graph-falkordb", "graph-amazon-neptune", "graph-apache-age", "graph-embeddings", "graph-all", "tripletstore-oxigraph", "vectorstore-faiss", "vectorstore-qdrant", "vectorstore-weaviate", "vectorstore-pinecone", "vectorstore-milvus", "vectorstore-pgvector", "vectorstore-sqlite", "vectorstore-all", "infra", "cloud", "monitoring", "viz", "media", "gpu", "agno", "langchain", "google-adk", "open-ontologies", "watch", "split-tiktoken", "split-community", "split-topic", "split-all", "explorer", "explorer-lite", "all"][package.metadata.requires-dev]dev = [