Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(ingest): add Microsoft Dynamics 365 connector (#1695)

Karunasagar Mohansundar57972a08226c
diff --git a/docs/docs.json b/docs/docs.json
index cb014a4d..7afc267b 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -109,6 +109,7 @@
"integrations/databricks",
"integrations/bigquery",
"integrations/salesforce",
+ "integrations/dynamics365",
"integrations/airflow",
"integrations/tableau",
"integrations/redshift",
diff --git a/docs/integrations/dynamics365.md b/docs/integrations/dynamics365.md
new file mode 100644
index 00000000..5eb348db
--- /dev/null
+++ b/docs/integrations/dynamics365.md
@@ -0,0 +1,117 @@
+---
+title: "Microsoft Dynamics 365 Integration"
+description: "Ingest entity records from Microsoft Dynamics 365 into Semantica's KG pipeline using the Dataverse Web API."
+icon: "microsoft"
+---
+
+> Pull accounts, contacts, opportunities, and any custom entity from Dynamics 365 into Semantica using Azure AD client-credentials authentication.
+
+## Installation
+
+```bash
+# Install with Dynamics 365 support
+pip install "semantica[ingest-dynamics365]"
+
+# Or install the dependency separately
+pip install msal>=1.20
+```
+
+## Basic Usage
+
+```python
+import os
+from semantica.ingest import Dynamics365Ingestor
+
+ingestor = Dynamics365Ingestor(
+ tenant_id=os.getenv("DYNAMICS_TENANT_ID"),
+ client_id=os.getenv("DYNAMICS_CLIENT_ID"),
+ client_secret=os.getenv("DYNAMICS_CLIENT_SECRET"),
+ org_url=os.getenv("DYNAMICS_ORG_URL"), # e.g. https://myorg.crm.dynamics.com
+)
+
+data = ingestor.ingest_entity("accounts", select=["accountid", "name", "statecode"])
+print(f"Retrieved {data.row_count} records")
+
+docs = ingestor.export_as_documents(data)
+```
+
+<Tip>
+Use environment variables (or a `.env` file with `python-dotenv`) to keep credentials out of source code. `Dynamics365Ingestor()` with no arguments reads from `DYNAMICS_*` environment variables automatically.
+</Tip>
+
+## Authentication
+
+Dynamics 365 uses Azure AD client-credentials (app-to-app) authentication via MSAL. You need an **Azure AD app registration** with the Dynamics 365 `user_impersonation` (or `Dynamics CRM` API) permission granted via admin consent.
+
+```python
+ingestor = Dynamics365Ingestor(
+ tenant_id="your-azure-tenant-id",
+ client_id="your-app-client-id",
+ client_secret=os.getenv("DYNAMICS_CLIENT_SECRET"),
+ org_url="https://myorg.crm.dynamics.com",
+)
+```
+
+## Environment Variables
+
+| Variable | Description |
+|---|---|
+| `DYNAMICS_TENANT_ID` | Azure AD tenant ID |
+| `DYNAMICS_CLIENT_ID` | Azure AD app (client) ID |
+| `DYNAMICS_CLIENT_SECRET` | Azure AD app client secret |
+| `DYNAMICS_ORG_URL` | Dynamics 365 org base URL (e.g. `https://myorg.crm.dynamics.com`) |
+
+## Ingestion Methods
+
+### Ingest an Entity
+
+```python
+# Basic — all fields
+data = ingestor.ingest_entity("accounts")
+
+# With OData $select, $filter, $top
+data = ingestor.ingest_entity(
+ "contacts",
+ select=["contactid", "fullname", "emailaddress1"],
+ filter="statecode eq 0",
+ top=500,
+)
+```
+
+### List Available Entities
+
+```python
+entity_names = ingestor.list_entities()
+print(entity_names[:10])
+```
+
+## Export to Documents
+
+```python
+docs = ingestor.export_as_documents(data)
+# Each doc: {"id": str, "text": str, "metadata": {"source": "dynamics365", "entity_name": ..., ...}}
+```
+
+## Context Manager
+
+```python
+with Dynamics365Ingestor(
+ tenant_id=os.getenv("DYNAMICS_TENANT_ID"),
+ client_id=os.getenv("DYNAMICS_CLIENT_ID"),
+ client_secret=os.getenv("DYNAMICS_CLIENT_SECRET"),
+ org_url=os.getenv("DYNAMICS_ORG_URL"),
+) as d:
+ accounts = d.ingest_entity("accounts")
+ contacts = d.ingest_entity("contacts")
+```
+
+## Dynamics365Data Reference
+
+| Field | Type | Description |
+|---|---|---|
+| `records` | `list[dict]` | Raw record dicts from the Web API |
+| `entity_name` | `str` | Logical name of the entity set |
+| `row_count` | `int` | Number of records |
+| `columns` | `list[str]` | Field names present across records |
+| `org_url` | `str` | Dynamics 365 org base URL |
+| `ingested_at` | `datetime` | Timestamp of ingestion |
diff --git a/pyproject.toml b/pyproject.toml
index 8925e0c5..840bba4f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -131,6 +131,7 @@ db-databricks = ["databricks-sdk>=0.60.0", "databricks-sql-connector>=4.0.0"]
db-arrow = ["pyarrow>=24.0.0"]
db-salesforce = ["simple-salesforce>=1.12.0"]
db-redshift = ["redshift-connector>=2.0.0"]
+ingest-dynamics365 = ["msal>=1.20"]
db-cassandra = ["cassandra-driver>=3.29.0"]
db-bigquery = ["google-cloud-bigquery>=3.0.0"]
ingest-looker = ["looker-sdk>=24.0.0"]
diff --git a/semantica/ingest/__init__.py b/semantica/ingest/__init__.py
index 07f40c4c..47d5b6b2 100644
--- a/semantica/ingest/__init__.py
+++ b/semantica/ingest/__init__.py
@@ -138,6 +138,11 @@ if TYPE_CHECKING:
BigQueryData,
BigQueryIngestor,
)
+ from .dynamics365_ingestor import (
+ Dynamics365Connector,
+ Dynamics365Data,
+ Dynamics365Ingestor,
+ )
from .powerbi_ingestor import (
PowerBIConnector,
PowerBIData,
@@ -275,6 +280,10 @@ _LAZY_EXPORTS: Dict[str, Tuple[str, str]] = {
"TableauIngestor": (".tableau_ingestor", "TableauIngestor"),
"TableauData": (".tableau_ingestor", "TableauData"),
"TableauConnector": (".tableau_ingestor", "TableauConnector"),
+ # Dynamics 365 ingestion
+ "Dynamics365Ingestor": (".dynamics365_ingestor", "Dynamics365Ingestor"),
+ "Dynamics365Data": (".dynamics365_ingestor", "Dynamics365Data"),
+ "Dynamics365Connector": (".dynamics365_ingestor", "Dynamics365Connector"),
# Redshift ingestion
"RedshiftIngestor": (".redshift_ingestor", "RedshiftIngestor"),
"RedshiftData": (".redshift_ingestor", "RedshiftData"),
@@ -346,6 +355,10 @@ _OPTIONAL_DEPENDENCY_MESSAGES = {
"Tableau ingestion requires optional dependency 'tableauserverclient'. "
"Install it with: pip install 'semantica[ingest-tableau]'"
),
+ ".dynamics365_ingestor": (
+ "Dynamics 365 ingestion requires optional dependency 'msal'. "
+ "Install it with: pip install 'semantica[ingest-dynamics365]'"
+ ),
".redshift_ingestor": (
"Redshift ingestion requires optional dependency 'redshift-connector'. "
"Install it with: pip install 'semantica[db-redshift]'"
@@ -440,6 +453,15 @@ def __getattr__(name: str) -> Any:
if message:
raise ImportError(message)
+ if module_name == ".dynamics365_ingestor" and name in {
+ "Dynamics365Ingestor",
+ "Dynamics365Connector",
+ }:
+ if not getattr(module, "DYNAMICS_AVAILABLE", True):
+ message = _OPTIONAL_DEPENDENCY_MESSAGES.get(module_name)
+ if message:
+ raise ImportError(message)
+
if module_name == ".redshift_ingestor" and name in {
"RedshiftIngestor",
"RedshiftConnector",
@@ -579,6 +601,10 @@ __all__ = [
"TableauIngestor",
"TableauData",
"TableauConnector",
+ # Dynamics 365 ingestion
+ "Dynamics365Ingestor",
+ "Dynamics365Data",
+ "Dynamics365Connector",
# Redshift ingestion
"RedshiftIngestor",
"RedshiftData",
diff --git a/semantica/ingest/dynamics365_ingestor.py b/semantica/ingest/dynamics365_ingestor.py
new file mode 100644
index 00000000..f49b5261
--- /dev/null
+++ b/semantica/ingest/dynamics365_ingestor.py
@@ -0,0 +1,702 @@
+"""Microsoft Dynamics 365 Ingestion Module.
+
+Pulls entity records from a Microsoft Dynamics 365 organisation via the
+Dynamics 365 Web API (OData v4 / REST) and flattens them into document dicts
+that the Semantica pipeline can feed to ``GraphBuilder``.
+
+Why this exists
+---------------
+Dynamics 365 is a very common Enterprise CRM/ERP source for business entities
+(Account, Opportunity, Order, Contact, Lead) that a Context Graph wants.
+Dynamics exposes those entities over a standard OData v4 REST surface at::
+
+ https://<org>.api.crm.dynamics.com/api/data/v9.2/
+
+This connector speaks only that REST surface; it uses ``msal`` for the
+Azure AD OAuth2 client-credentials flow and ``requests`` (already a core
+dependency) for all HTTP calls routed through ``request_with_ssrf_guard``.
+
+Design notes
+------------
+Three classes, matching the SAP/Snowflake/Salesforce ingestors:
+
+- ``Dynamics365Data``: a collection fetch from one Dynamics entity,
+ flattened to document dicts for ``GraphBuilder`` via
+ ``export_as_documents``.
+- ``Dynamics365Connector``: Azure AD / MSAL client-credentials auth plus the
+ SSRF-guarded ``requests`` session. *Every* outbound request goes through
+ ``request_with_ssrf_guard`` so user-supplied ``org_url`` values cannot
+ reach private/loopback/link-local address space.
+- ``Dynamics365Ingestor``: the three main operations —
+ ``list_entities``, ``ingest_entity``, and ``export_as_documents``.
+
+Optional Dependency
+-------------------
+Install via the ``ingest-dynamics365`` extra::
+
+ pip install "semantica[ingest-dynamics365]"
+
+or directly::
+
+ pip install msal>=1.20
+
+Environment Variables
+---------------------
+``DYNAMICS_TENANT_ID`` Azure AD tenant (directory) ID.
+``DYNAMICS_CLIENT_ID`` Azure AD application (client) ID.
+``DYNAMICS_CLIENT_SECRET`` Azure AD client secret value.
+``DYNAMICS_ORG_URL`` Base URL of your Dynamics 365 org, e.g.
+ ``https://myorg.api.crm.dynamics.com``.
+
+Example Usage::
+
+ >>> import os
+ >>> from semantica.ingest import Dynamics365Ingestor
+ >>> ingestor = Dynamics365Ingestor(
+ ... tenant_id=os.getenv("DYNAMICS_TENANT_ID"),
+ ... client_id=os.getenv("DYNAMICS_CLIENT_ID"),
+ ... client_secret=os.getenv("DYNAMICS_CLIENT_SECRET"),
+ ... org_url=os.getenv("DYNAMICS_ORG_URL"),
+ ... )
+ >>> data = ingestor.ingest_entity("accounts", select=["name", "accountid"], top=100)
+ >>> docs = ingestor.export_as_documents(data)
+
+Author: Semantica Contributors
+License: MIT
+"""
+
+from __future__ import annotations
+
+import os
+import time
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any, Dict, List, Optional
+from urllib.parse import urljoin, urlparse
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+from ..utils.progress_tracker import get_progress_tracker
+from .ssrf import request_with_ssrf_guard
+
+# ---------------------------------------------------------------------------
+# Optional-dependency guard — mirrors the pattern in salesforce_ingestor,
+# snowflake_ingestor, and bigquery_ingestor exactly. The module always
+# imports cleanly; the guard fires at instantiation time via the
+# DYNAMICS_AVAILABLE check in semantica/ingest/__init__.py.__getattr__.
+# ---------------------------------------------------------------------------
+try:
+ import msal as _msal
+
+ DYNAMICS_AVAILABLE = True
+except (ImportError, OSError):
+ _msal = None # type: ignore[assignment]
+ DYNAMICS_AVAILABLE = False
+
+__all__ = [
+ "Dynamics365Data",
+ "Dynamics365Connector",
+ "Dynamics365Ingestor",
+]
+
+_logger = get_logger("dynamics365_ingestor")
+
+# Dynamics 365 Web API version used for all requests.
+_WEBAPI_VERSION = "v9.2"
+
+# Irregular plural → singular map for entity ID inference.
+_IRREGULAR_SINGULARS: Dict[str, str] = {
+ 'opportunities': 'opportunity',
+ 'activities': 'activity',
+ 'categories': 'category',
+ 'currencies': 'currency',
+}
+
+# Entities that are almost always present in a standard Dynamics 365 org.
+_DEFAULT_ENTITIES = [
+ "accounts",
+ "contacts",
+ "leads",
+ "opportunities",
+ "incidents",
+ "orders",
+ "products",
+ "systemusers",
+]
+
+
+# ---------------------------------------------------------------------------
+# URL validation helpers
+# ---------------------------------------------------------------------------
+
+def _validate_org_url(url: str) -> str:
+ """Validate a user-supplied Dynamics 365 org URL.
+
+ Args:
+ url: The org URL to validate.
+
+ Returns:
+ The normalised URL (trailing slash stripped) if valid.
+
+ Raises:
+ ValidationError: If *url* is not a valid public HTTPS URL.
+ """
+ if not isinstance(url, str) or not url.strip():
+ raise ValidationError(
+ "Dynamics 365 org_url is required and must be a non-empty string."
+ )
+ url = url.rstrip("/")
+ parsed = urlparse(url)
+ if parsed.scheme != "https":
+ raise ValidationError(
+ f"Dynamics 365 org_url must use the https:// scheme, got: {url!r}"
+ )
+ if not parsed.netloc:
+ raise ValidationError(
+ f"Dynamics 365 org_url must contain a valid hostname, got: {url!r}"
+ )
+ # Block obvious private / loopback hostnames early (SSRF guard covers IPs).
+ hostname = parsed.hostname or ""
+ private_suffixes = ("localhost", "127.0.0.1", "::1", "0.0.0.0")
+ if any(hostname == h or hostname.endswith("." + h) for h in private_suffixes):
+ raise ValidationError(
+ f"Dynamics 365 org_url must not point to a private address: {url!r}"
+ )
+ return url
+
+
+class _SSRFGuardedHttpClient:
+ """MSAL ``http_client`` that routes requests through ``request_with_ssrf_guard``.
+
+ MSAL performs authority discovery and the token exchange with its own
+ ``requests.Session`` unless one is supplied; this keeps those calls on the
+ same guarded path as the Web API requests.
+ """
+
+ def __init__(self, timeout: float = 30) -> None:
+ self.timeout = timeout
+
+ def get(self, url: str, params=None, headers=None, **kwargs: Any):
+ return self._request("GET", url, params=params, headers=headers, **kwargs)
+
+ def post(self, url: str, params=None, data=None, headers=None, **kwargs: Any):
+ return self._request(
+ "POST", url, params=params, data=data, headers=headers, **kwargs
+ )
+
+ def close(self) -> None:
+ pass
+
+ def _request(self, method: str, url: str, **kwargs: Any):
+ kwargs.setdefault("timeout", self.timeout)
+ return request_with_ssrf_guard(method, url, **kwargs)
+
+
+# ---------------------------------------------------------------------------
+# Data result type
+# ---------------------------------------------------------------------------
+
+@dataclass
+class Dynamics365Data:
+ """A collection fetch from one Dynamics 365 entity.
+
+ Attributes:
+ records: Raw record dicts returned by the Web API.
+ entity_name: Logical name of the entity set, e.g. ``"accounts"``.
+ row_count: Number of records in *records*.
+ columns: Ordered list of field names present across all records.
+ org_url: Base URL of the Dynamics 365 org.
+ metadata: Optional extra metadata from the caller / connector.
+ ingested_at: UTC timestamp of when the fetch completed.
+ """
+
+ records: List[Dict[str, Any]]
+ entity_name: str
+ row_count: int
+ columns: List[str]
+ org_url: str
+ metadata: Optional[Dict[str, Any]] = None
+ ingested_at: datetime = field(default_factory=datetime.utcnow)
+
+
+# ---------------------------------------------------------------------------
+# Connector
+# ---------------------------------------------------------------------------
+
+class Dynamics365Connector:
+ """Connection and authentication management for a Dynamics 365 Web API org.
+
+ Uses the MSAL ``ConfidentialClientApplication`` client-credentials flow
+ (Azure AD app registration) to obtain a bearer token. The token is cached
+ inside the MSAL application object and refreshed transparently on expiry.
+
+ Every outbound HTTP call — including the initial MSAL token exchange — goes
+ through ``request_with_ssrf_guard`` so user-supplied URLs cannot reach
+ private/loopback/link-local address space.
+
+ Args:
+ tenant_id: Azure AD tenant (directory) ID.
+ client_id: Azure AD application (client) ID.
+ client_secret: Azure AD client secret value.
+ org_url: Base URL of the Dynamics 365 org. Validated and
+ normalised; must be an https:// URL pointing to a
+ publicly reachable host.
+ **config: Extra options forwarded to ``request_with_ssrf_guard``,
+ e.g. ``timeout``.
+
+ Environment variables (all optional — constructor args take precedence)::
+
+ DYNAMICS_TENANT_ID, DYNAMICS_CLIENT_ID,
+ DYNAMICS_CLIENT_SECRET, DYNAMICS_ORG_URL
+ """
+
+ def __init__(
+ self,
+ tenant_id: Optional[str] = None,
+ client_id: Optional[str] = None,
+ client_secret: Optional[str] = None,
+ org_url: Optional[str] = None,
+ **config: Any,
+ ) -> None:
+ if not DYNAMICS_AVAILABLE: # pragma: no cover — guard raised by __init__
+ raise ImportError(
+ "Dynamics 365 ingestion requires optional dependency 'msal'. "
+ "Install it with: pip install 'semantica[ingest-dynamics365]'"
+ )
+
+ self.tenant_id = tenant_id or os.getenv("DYNAMICS_TENANT_ID")
+ self.client_id = client_id or os.getenv("DYNAMICS_CLIENT_ID")
+ self.client_secret = client_secret or os.getenv("DYNAMICS_CLIENT_SECRET")
+ raw_org_url = org_url or os.getenv("DYNAMICS_ORG_URL") or ""
+ self.org_url = _validate_org_url(raw_org_url)
+ self.config = config
+
+ if not self.tenant_id:
+ raise ValidationError(
+ "Dynamics 365 tenant_id is required. Provide via 'tenant_id' or "
+ "DYNAMICS_TENANT_ID environment variable."
+ )
+ if not self.client_id:
+ raise ValidationError(
+ "Dynamics 365 client_id is required. Provide via 'client_id' or "
+ "DYNAMICS_CLIENT_ID environment variable."
+ )
+ if not self.client_secret:
+ raise ValidationError(
+ "Dynamics 365 client_secret is required. Provide via 'client_secret' or "
+ "DYNAMICS_CLIENT_SECRET environment variable."
+ )
+
+ self._msal_app: Optional[Any] = None
+ self._access_token: Optional[str] = None
+ self._token_expires_at: float = 0.0
+ self.logger = _logger
+
+ # ------------------------------------------------------------------
+ # Public interface
+ # ------------------------------------------------------------------
+
+ def connect(self) -> None:
+ """Obtain an access token via MSAL client-credentials flow.
+
+ The MSAL ``ConfidentialClientApplication`` is initialised here so that
+ tests can mock ``_msal`` before the connector is constructed.
+
+ Raises:
+ ProcessingError: If the token cannot be obtained.
+ """
+ authority = f"https://login.microsoftonline.com/{self.tenant_id}"
+ scope = [f"{self.org_url}/.default"]
+ self.logger.info(
+ "Dynamics365Connector.connect: acquiring token for org %s", self.org_url
+ )
+ try:
+ self._msal_app = _msal.ConfidentialClientApplication(
+ client_id=self.client_id,
+ client_credential=self.client_secret,
+ authority=authority,
+ http_client=_SSRFGuardedHttpClient(
+ timeout=self.config.get("timeout", 30)
+ ),
+ )
+ result = self._msal_app.acquire_token_for_client(scopes=scope)
+ except Exception as exc:
+ raise ProcessingError(
+ f"Dynamics 365 MSAL token acquisition failed: {exc}"
+ ) from exc
+
+ if "access_token" not in result:
+ error = result.get("error_description") or result.get("error") or str(result)
+ raise ProcessingError(
+ f"Dynamics 365 MSAL token acquisition failed: {error}"
+ )
+
+ self._access_token = result["access_token"]
+ self._token_expires_at = time.time() + result.get("expires_in", 3600) - 60
+ self.logger.info("Dynamics365Connector.connect: token acquired successfully")
+
+ def disconnect(self) -> None:
+ """Clear cached credentials."""
+ self._access_token = None
+ self._msal_app = None
+ self.logger.debug("Dynamics365Connector.disconnect: token cleared")
+
+ def test_connection(self) -> bool:
+ """Probe the Web API root to verify credentials and connectivity.
+
+ Returns:
+ ``True`` if the probe returns HTTP 200.
+
+ Raises:
+ ProcessingError: If the connection test fails or an HTTP error
+ is returned.
+ """
+ if not self._access_token:
+ self.connect()
+
+ probe_url = f"{self.org_url}/api/data/{_WEBAPI_VERSION}/"
+ headers = self._auth_headers()
+ try:
+ resp = request_with_ssrf_guard(
+ "GET",
+ probe_url,
+ headers=headers,
+ timeout=self.config.get("timeout", 30),
+ )
+ resp.raise_for_status()
+ return True
+ except Exception as exc:
+ raise ProcessingError(
+ f"Dynamics 365 connection test failed: {exc}"
+ ) from exc
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _auth_headers(self) -> Dict[str, str]:
+ """Return HTTP headers including the Bearer token."""
+ return {
+ "Authorization": f"Bearer {self._access_token}",
+ "Accept": "application/json",
+ "OData-MaxVersion": "4.0",
+ "OData-Version": "4.0",
+ }
+
+ def _ensure_connected(self) -> None:
+ if not self._access_token or time.time() >= self._token_expires_at:
+ self.connect()
+
+ # Context-manager support (mirrors SAP/Snowflake connectors).
+ def __enter__(self) -> "Dynamics365Connector":
+ self.connect()
+ return self
+
+ def __exit__(self, *_: Any) -> None:
+ self.disconnect()
+
+
+# ---------------------------------------------------------------------------
+# Origin validation helper for nextLink SSRF protection
+# ---------------------------------------------------------------------------
+
+def _same_origin(a: str, b: str) -> bool:
+ """Return True if URLs *a* and *b* share the same scheme, hostname, and port."""
+ pa, pb = urlparse(a), urlparse(b)
+ port_a = pa.port or (443 if pa.scheme == "https" else 80)
+ port_b = pb.port or (443 if pb.scheme == "https" else 80)
+ return pa.scheme == pb.scheme and pa.hostname == pb.hostname and port_a == port_b
+
+
+# ---------------------------------------------------------------------------
+# Ingestor
+# ---------------------------------------------------------------------------
+
+class Dynamics365Ingestor:
+ """Orchestrates data extraction from a Microsoft Dynamics 365 org.
+
+ Wraps a ``Dynamics365Connector`` and exposes three public methods:
+
+ - ``list_entities``: discover available entity sets.
+ - ``ingest_entity``: fetch records from a single entity set.
+ - ``export_as_documents``: convert a ``Dynamics365Data`` object into the
+ ``[{id, text, metadata}]`` list that ``GraphBuilder`` consumes.
+
+ Args:
+ tenant_id: Azure AD tenant ID (or ``DYNAMICS_TENANT_ID`` env var).
+ client_id: Azure AD application ID (or ``DYNAMICS_CLIENT_ID``).
+ client_secret: Azure AD client secret (or ``DYNAMICS_CLIENT_SECRET``).
+ org_url: Dynamics 365 org base URL (or ``DYNAMICS_ORG_URL``).
+ connector: Pre-built ``Dynamics365Connector`` instance; when
+ supplied the four credential args are ignored.
+ **config: Extra options forwarded to the connector, e.g.
+ ``timeout``.
+ """
+
+ def __init__(
+ self,
+ tenant_id: Optional[str] = None,
+ client_id: Optional[str] = None,
+ client_secret: Optional[str] = None,
+ org_url: Optional[str] = None,
+ *,
+ connector: Optional[Dynamics365Connector] = None,
+ **config: Any,
+ ) -> None:
+ if not DYNAMICS_AVAILABLE: # pragma: no cover — guard raised by __init__
+ raise ImportError(
+ "Dynamics 365 ingestion requires optional dependency 'msal'. "
+ "Install it with: pip install 'semantica[ingest-dynamics365]'"
+ )
+
+ if connector is not None:
+ self._connector = connector
+ else:
+ self._connector = Dynamics365Connector(
+ tenant_id=tenant_id,
+ client_id=client_id,
+ client_secret=client_secret,
+ org_url=org_url,
+ **config,
+ )
+ self.logger = _logger
+ self._progress = get_progress_tracker()
+
+ # ------------------------------------------------------------------
+ # Context-manager support
+ # ------------------------------------------------------------------
+
+ def __enter__(self) -> "Dynamics365Ingestor":
+ self._connector.connect()
+ return self
+
+ def __exit__(self, *_: Any) -> None:
+ self._connector.disconnect()
+
+ # ------------------------------------------------------------------
+ # Public interface
+ # ------------------------------------------------------------------
+
+ def list_entities(self) -> List[str]:
+ """Return a list of available entity set names from the Web API.
+
+ Queries the OData service root (``/api/data/v9.2/``) for the list of
+ entity sets. Falls back to a built-in default list if the service
+ root does not include entity-set metadata (some restricted tenants
+ suppress it).
+
+ Returns:
+ List of entity set (logical plural) names, e.g.
+ ``["accounts", "contacts", "leads", ...]``.
+
+ Raises:
+ ProcessingError: If the Web API is unreachable.
+ """
+ self._connector._ensure_connected()
+ url = f"{self._connector.org_url}/api/data/{_WEBAPI_VERSION}/"
+ headers = self._connector._auth_headers()
+ self.logger.info("Dynamics365Ingestor.list_entities: fetching service root")
+ try:
+ resp = request_with_ssrf_guard(
+ "GET",
+ url,
+ headers=headers,
+ timeout=self._connector.config.get("timeout", 30),
+ )
+ resp.raise_for_status()
+ data = resp.json()
+ except Exception as exc:
+ raise ProcessingError(
+ f"Dynamics 365 list_entities failed: {exc}"
+ ) from exc
+
+ entity_sets = [
+ str(e["name"])
+ for e in data.get("value", [])
+ if isinstance(e, dict) and e.get("name")
+ ]
+ if not entity_sets:
+ self.logger.debug(
+ "list_entities: no entity sets in service root, using defaults"
+ )
+ return list(_DEFAULT_ENTITIES)
+ return entity_sets
+
+ def ingest_entity(
+ self,
+ entity_name: str,
+ select: Optional[List[str]] = None,
+ filter: Optional[str] = None, # noqa: A002 — mirrors the OData param name
+ top: Optional[int] = None,
+ ) -> Dynamics365Data:
+ """Fetch records from a Dynamics 365 entity set.
+
+ Follows ``@odata.nextLink`` for automatic server-driven pagination so
+ the full record set is always returned regardless of page size.
+
+ Args:
+ entity_name: Logical plural name of the entity set, e.g.
+ ``"accounts"``, ``"contacts"``.
+ select: List of field names to include in the response
+ (OData ``$select``). ``None`` fetches all fields.
+ filter: OData ``$filter`` expression, e.g.
+ ``"statecode eq 0"``. ``None`` for no filter.
+ top: Maximum number of records to return (OData ``$top``).
+ ``None`` returns all pages.
+
+ Returns:
+ ``Dynamics365Data`` with the fetched records.
+
+ Raises:
+ ValidationError: If *entity_name* is empty.
+ ProcessingError: If the Web API returns an error.
+ """
+ if not isinstance(entity_name, str) or not entity_name.strip():
+ raise ValidationError(
+ "entity_name must be a non-empty string."
+ )
+ entity_name = entity_name.strip()
+
+ self._connector._ensure_connected()
+ base_url = (
+ f"{self._connector.org_url}/api/data/{_WEBAPI_VERSION}/{entity_name}"
+ )
+ params: Dict[str, Any] = {}
+ if select:
+ params["$select"] = ",".join(select)
+ if filter:
+ params["$filter"] = filter
+ if top is not None:
+ params["$top"] = top
+
+ headers = self._connector._auth_headers()
+ all_records: List[Dict[str, Any]] = []
+ next_url: Optional[str] = base_url
+ page = 0
+
+ self.logger.info(
+ "Dynamics365Ingestor.ingest_entity: fetching entity=%s", entity_name
+ )
+ tracking_id = self._progress.start_tracking(
+ file=entity_name,
+ module="ingest",
+ submodule="Dynamics365Ingestor",
+ message=f"Fetching {entity_name}",
+ )
+
+ try:
+ while next_url:
+ req_kwargs: Dict[str, Any] = {
+ "headers": headers,
+ "timeout": self._connector.config.get("timeout", 60),
+ }
+ if page == 0:
+ req_kwargs["params"] = params
+
+ resp = request_with_ssrf_guard("GET", next_url, **req_kwargs)
+ resp.raise_for_status()
+ payload = resp.json()
+
+ records = payload.get("value", [])
+ all_records.extend(records)
+ page += 1
+ self._progress.update_tracking(
+ tracking_id,
+ message=f"Fetched {len(all_records)} records so far…",
+ )
+ self.logger.debug(
+ "ingest_entity: page %d — %d records (total so far: %d)",
+ page,
+ len(records),
+ len(all_records),
+ )
+
+ next_link = payload.get("@odata.nextLink")
+ if next_link:
+ if not _same_origin(self._connector.org_url, next_link):
+ raise ProcessingError(
+ f"nextLink origin mismatch: refusing to send credentials to {next_link!r}"
+ )
+ next_url = next_link
+ else:
+ next_url = None
+ # Honour top: stop paging once we have enough records.
+ if top is not None and len(all_records) >= top:
+ all_records = all_records[:top]
+ break
+
+ self._progress.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Ingested {len(all_records)} records",
+ )
+ except ProcessingError:
+ self._progress.stop_tracking(tracking_id, status="failed")
+ raise
+ except Exception as exc:
+ self._progress.stop_tracking(tracking_id, status="failed")
+ raise ProcessingError(
+ f"Dynamics 365 ingest_entity({entity_name!r}) failed: {exc}"
+ ) from exc
+
+ # Derive columns from the union of keys across all records.
+ columns: List[str] = []
+ seen: set = set()
+ for rec in all_records:
+ for key in rec:
+ if key not in seen:
+ seen.add(key)
+ columns.append(key)
+
+ self.logger.info(
+ "Dynamics365Ingestor.ingest_entity: fetched %d records from %s",
+ len(all_records),
+ entity_name,
+ )
+ return Dynamics365Data(
+ records=all_records,
+ entity_name=entity_name,
+ row_count=len(all_records),
+ columns=columns,
+ org_url=self._connector.org_url,
+ )
+
+ def export_as_documents(
+ self, data: Dynamics365Data
+ ) -> List[Dict[str, Any]]:
+ """Convert a ``Dynamics365Data`` into the document list for GraphBuilder.
+
+ Each record is serialised as a ``text`` blob (key=value pairs) and
+ wrapped with the ``id`` and ``metadata`` that the pipeline requires.
+
+ Args:
+ data: A ``Dynamics365Data`` instance produced by ``ingest_entity``.
+
+ Returns:
+ List of ``{id, text, metadata}`` dicts. ``metadata`` always
+ carries ``source="dynamics365"``, ``entity_name``, and ``org_url``.
+ """
+ docs: List[Dict[str, Any]] = []
+ for index, record in enumerate(data.records):
+ # Best-effort ID resolution: prefer common Dynamics ID fields.
+ record_id = (
+ record.get(f"{_IRREGULAR_SINGULARS.get(data.entity_name, data.entity_name[:-1])}id") # e.g. accountid, opportunityid
+ or record.get("id")
+ or record.get("Id")
+ or f"{data.entity_name}:{index}"
+ )
+ text = " | ".join(
+ f"{k}: {v}" for k, v in record.items() if v not in (None, "")
+ )
+ docs.append(
+ {
+ "id": str(record_id),
+ "text": text,
+ "metadata": {
+ "source": "dynamics365",
+ "entity_name": data.entity_name,
+ "org_url": data.org_url,
+ },
+ }
+ )
+ return docs
diff --git a/tests/test_dynamics365_ingestor.py b/tests/test_dynamics365_ingestor.py
new file mode 100644
index 00000000..cf69391d
--- /dev/null
+++ b/tests/test_dynamics365_ingestor.py
@@ -0,0 +1,464 @@
+"""
+Unit tests for Dynamics365Connector and Dynamics365Ingestor.
+
+All MSAL and HTTP calls are mocked — no live Dynamics 365 org is required.
+"""
+
+from datetime import datetime
+from unittest.mock import MagicMock, call, patch
+
+import pytest
+
+try:
+ import msal # noqa: F401
+ MSAL_LIB_AVAILABLE = True
+except ImportError:
+ MSAL_LIB_AVAILABLE = False
+
+
+# ---------------------------------------------------------------------------
+# autouse fixture: mock msal when not installed
+# ---------------------------------------------------------------------------
+
+
[email protected](autouse=True)
+def _mock_msal_if_needed(request):
+ _is_import_test = (
+ getattr(request.node.cls, "__name__", "") == "TestImportBehaviourWithoutLib"
+ )
+ if not MSAL_LIB_AVAILABLE and not _is_import_test:
+ msal_mod = MagicMock()
+ with patch.dict("sys.modules", {"msal": msal_mod}):
+ import semantica.ingest as _ingest_mod
+ for _name in ("Dynamics365Ingestor", "Dynamics365Data", "Dynamics365Connector"):
+ _ingest_mod.__dict__.pop(_name, None)
+ yield
+ for _name in ("Dynamics365Ingestor", "Dynamics365Data", "Dynamics365Connector"):
+ _ingest_mod.__dict__.pop(_name, None)
+ else:
+ yield
+
+
+# ---------------------------------------------------------------------------
+# Import behaviour
+# ---------------------------------------------------------------------------
+
+
+class TestImportBehaviourWithoutLib:
+ def test_raises_import_error_without_msal(self):
+ with patch("semantica.ingest.dynamics365_ingestor.DYNAMICS_AVAILABLE", False):
+ with pytest.raises((ImportError, Exception)):
+ from semantica.ingest.dynamics365_ingestor import Dynamics365Connector
+ Dynamics365Connector(
+ tenant_id="t", client_id="c", client_secret="s",
+ org_url="https://org.crm.dynamics.com",
+ )
+
+
+# ---------------------------------------------------------------------------
+# Connector
+# ---------------------------------------------------------------------------
+
+
+class TestDynamics365Connector:
+
+ @patch("semantica.ingest.dynamics365_ingestor.DYNAMICS_AVAILABLE", True)
+ def test_init_with_credentials(self):
+ from semantica.ingest.dynamics365_ingestor import Dynamics365Connector
+ connector = Dynamics365Connector(
+ tenant_id="tenant-id",
+ client_id="client-id",
+ client_secret="secret",
+ org_url="https://myorg.crm.dynamics.com",
+ )
+ assert connector.org_url == "https://myorg.crm.dynamics.com"
+
+ @patch("semantica.ingest.dynamics365_ingestor.DYNAMICS_AVAILABLE", True)
+ def test_init_raises_without_org_url(self):
+ from semantica.ingest.dynamics365_ingestor import Dynamics365Connector
+ from semantica.utils.exceptions import ValidationError
+ with pytest.raises((ValidationError, Exception)):
+ Dynamics365Connector(
+ tenant_id="t", client_id="c", client_secret="s", org_url=None,
+ )
+
+ @patch("semantica.ingest.dynamics365_ingestor.DYNAMICS_AVAILABLE", True)
+ def test_init_raises_without_credentials(self):
+ from semantica.ingest.dynamics365_ingestor import Dynamics365Connector
+ from semantica.utils.exceptions import ValidationError
+ with pytest.raises((ValidationError, Exception)):
+ Dynamics365Connector(org_url="https://org.crm.dynamics.com")
+
+
+# ---------------------------------------------------------------------------
+# Ingestor
+# ---------------------------------------------------------------------------
+
+
+class TestDynamics365IngestorEntity:
+
+ @patch("semantica.ingest.dynamics365_ingestor.DYNAMICS_AVAILABLE", True)
+ def test_ingest_entity_returns_data(self):
+ from semantica.ingest.dynamics365_ingestor import Dynamics365Data, Dynamics365Ingestor
+ import semantica.ingest.dynamics365_ingestor as _mod
+
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "value": [
+ {"accountid": "acc-001", "name": "Contoso", "statecode": 0},
+ ]
+ }
+ mock_response.raise_for_status = MagicMock()
+
+ mock_ssrf = MagicMock(return_value=mock_response)
+ mock_msal_app = MagicMock()
+ mock_msal_app.acquire_token_silent.return_value = None
+ mock_msal_app.acquire_token_for_client.return_value = {
+ "access_token": "fake-token"
+ }
+
+ with patch.object(_mod, "request_with_ssrf_guard", mock_ssrf), \
+ patch.object(_mod, "_msal") as mock_msal_mod:
+ mock_msal_mod.ConfidentialClientApplication.return_value = mock_msal_app
+
+ ingestor = Dynamics365Ingestor(
+ tenant_id="t",
+ client_id="c",
+ client_secret="s",
+ org_url="https://myorg.crm.dynamics.com",
+ )
+ data = ingestor.ingest_entity("accounts", select=["accountid", "name"])
+
+ assert isinstance(data, Dynamics365Data)
+ assert len(data.records) == 1
+ assert data.records[0]["name"] == "Contoso"
+ assert data.entity_name == "accounts"
+ assert data.row_count == 1
+
+ @patch("semantica.ingest.dynamics365_ingestor.DYNAMICS_AVAILABLE", True)
+ def test_ingest_entity_raises_on_empty_name(self):
+ from semantica.ingest.dynamics365_ingestor import Dynamics365Ingestor
+ from semantica.utils.exceptions import ValidationError
+ import semantica.ingest.dynamics365_ingestor as _mod
+
+ mock_msal_app = MagicMock()
+ mock_msal_app.acquire_token_silent.return_value = None
+ mock_msal_app.acquire_token_for_client.return_value = {"access_token": "tok"}
+
+ with patch.object(_mod, "_msal") as mock_msal_mod:
+ mock_msal_mod.ConfidentialClientApplication.return_value = mock_msal_app
+ ingestor = Dynamics365Ingestor(
+ tenant_id="t", client_id="c", client_secret="s",
+ org_url="https://myorg.crm.dynamics.com",
+ )
+ with pytest.raises((ValidationError, Exception)):
+ ingestor.ingest_entity("")
+
+
+# ---------------------------------------------------------------------------
+# export_as_documents
+# ---------------------------------------------------------------------------
+
+
+class TestDynamics365ExportDocuments:
+
+ @patch("semantica.ingest.dynamics365_ingestor.DYNAMICS_AVAILABLE", True)
+ def test_export_document_shape(self):
+ from semantica.ingest.dynamics365_ingestor import Dynamics365Data, Dynamics365Ingestor
+
+ data = Dynamics365Data(
+ records=[{"accountid": "acc-001", "name": "Contoso"}],
+ entity_name="accounts",
+ row_count=1,
+ columns=["accountid", "name"],
+ org_url="https://myorg.crm.dynamics.com",
+ )
+ import semantica.ingest.dynamics365_ingestor as _mod
+ mock_msal_app = MagicMock()
+ mock_msal_app.acquire_token_silent.return_value = None
+ mock_msal_app.acquire_token_for_client.return_value = {"access_token": "tok"}
+
+ with patch.object(_mod, "_msal") as mock_msal_mod:
+ mock_msal_mod.ConfidentialClientApplication.return_value = mock_msal_app
+ ingestor = Dynamics365Ingestor(
+ tenant_id="t", client_id="c", client_secret="s",
+ org_url="https://myorg.crm.dynamics.com",
+ )
+ docs = ingestor.export_as_documents(data)
+
+ assert len(docs) == 1
+ doc = docs[0]
+ assert "id" in doc and "text" in doc and "metadata" in doc
+ assert doc["metadata"]["source"] == "dynamics365"
+ assert doc["metadata"]["entity_name"] == "accounts"
+ assert doc["metadata"]["org_url"] == "https://myorg.crm.dynamics.com"
+ assert "Contoso" in doc["text"]
+
+ @patch("semantica.ingest.dynamics365_ingestor.DYNAMICS_AVAILABLE", True)
+ def test_export_empty_data(self):
+ from semantica.ingest.dynamics365_ingestor import Dynamics365Data, Dynamics365Ingestor
+ import semantica.ingest.dynamics365_ingestor as _mod
+
+ data = Dynamics365Data(
+ records=[], entity_name="contacts", row_count=0,
+ columns=[], org_url="https://myorg.crm.dynamics.com",
+ )
+ mock_msal_app = MagicMock()
+ mock_msal_app.acquire_token_silent.return_value = None
+ mock_msal_app.acquire_token_for_client.return_value = {"access_token": "tok"}
+
+ with patch.object(_mod, "_msal") as mock_msal_mod:
+ mock_msal_mod.ConfidentialClientApplication.return_value = mock_msal_app
+ ingestor = Dynamics365Ingestor(
+ tenant_id="t", client_id="c", client_secret="s",
+ org_url="https://myorg.crm.dynamics.com",
+ )
+ docs = ingestor.export_as_documents(data)
+
+ assert docs == []
+
+ @patch("semantica.ingest.dynamics365_ingestor.DYNAMICS_AVAILABLE", True)
+ def test_export_opportunities_uses_opportunityid(self):
+ """Bug fix: 'opportunities'[:-1] == 'opportunitie', not 'opportunity'."""
+ from semantica.ingest.dynamics365_ingestor import Dynamics365Data, Dynamics365Ingestor
+ import semantica.ingest.dynamics365_ingestor as _mod
+
+ data = Dynamics365Data(
+ records=[{"opportunityid": "opp-001", "name": "Deal A"}],
+ entity_name="opportunities",
+ row_count=1,
+ columns=["opportunityid", "name"],
+ org_url="https://myorg.crm.dynamics.com",
+ )
+ mock_msal_app = MagicMock()
+ mock_msal_app.acquire_token_for_client.return_value = {"access_token": "tok"}
+
+ with patch.object(_mod, "_msal") as mock_msal_mod:
+ mock_msal_mod.ConfidentialClientApplication.return_value = mock_msal_app
+ ingestor = Dynamics365Ingestor(
+ tenant_id="t", client_id="c", client_secret="s",
+ org_url="https://myorg.crm.dynamics.com",
+ )
+ docs = ingestor.export_as_documents(data)
+
+ assert len(docs) == 1
+ assert docs[0]["id"] == "opp-001", (
+ f"Expected 'opp-001' but got {docs[0]['id']!r} — irregular plural map broken"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Context manager on Ingestor
+# ---------------------------------------------------------------------------
+
+
+class TestDynamics365IngestorContextManager:
+
+ @patch("semantica.ingest.dynamics365_ingestor.DYNAMICS_AVAILABLE", True)
+ def test_ingestor_context_manager_calls_connect_and_disconnect(self):
+ """Dynamics365Ingestor must support `with` and delegate to connector."""
+ from semantica.ingest.dynamics365_ingestor import Dynamics365Ingestor
+ import semantica.ingest.dynamics365_ingestor as _mod
+
+ mock_msal_app = MagicMock()
+ mock_msal_app.acquire_token_for_client.return_value = {"access_token": "tok", "expires_in": 3600}
+
+ with patch.object(_mod, "_msal") as mock_msal_mod:
+ mock_msal_mod.ConfidentialClientApplication.return_value = mock_msal_app
+ ingestor = Dynamics365Ingestor(
+ tenant_id="t", client_id="c", client_secret="s",
+ org_url="https://myorg.crm.dynamics.com",
+ )
+ with ingestor as ctx:
+ assert ctx is ingestor
+ assert ingestor._connector._access_token == "tok"
+
+ # After __exit__ the token should be cleared
+ assert ingestor._connector._access_token is None
+
+
+# ---------------------------------------------------------------------------
+# nextLink origin validation
+# ---------------------------------------------------------------------------
+
+
+class TestNextLinkOriginValidation:
+
+ @patch("semantica.ingest.dynamics365_ingestor.DYNAMICS_AVAILABLE", True)
+ def test_cross_origin_nextlink_raises_processing_error(self):
+ """nextLink pointing to a different origin must raise ProcessingError."""
+ from semantica.ingest.dynamics365_ingestor import Dynamics365Ingestor
+ from semantica.utils.exceptions import ProcessingError
+ import semantica.ingest.dynamics365_ingestor as _mod
+
+ # First page returns a cross-origin nextLink.
+ page1 = MagicMock()
+ page1.raise_for_status = MagicMock()
+ page1.json.return_value = {
+ "value": [{"accountid": "a1", "name": "Acme"}],
+ "@odata.nextLink": "https://evil.attacker.com/api/data/v9.2/accounts?$skip=100",
+ }
+
+ mock_ssrf = MagicMock(return_value=page1)
+ mock_msal_app = MagicMock()
+ mock_msal_app.acquire_token_for_client.return_value = {"access_token": "tok", "expires_in": 3600}
+
+ with patch.object(_mod, "request_with_ssrf_guard", mock_ssrf), \
+ patch.object(_mod, "_msal") as mock_msal_mod:
+ mock_msal_mod.ConfidentialClientApplication.return_value = mock_msal_app
+ ingestor = Dynamics365Ingestor(
+ tenant_id="t", client_id="c", client_secret="s",
+ org_url="https://myorg.crm.dynamics.com",
+ )
+ with pytest.raises(ProcessingError, match="nextLink origin mismatch"):
+ ingestor.ingest_entity("accounts")
+
+
+# ---------------------------------------------------------------------------
+# Token expiry
+# ---------------------------------------------------------------------------
+
+
+class TestTokenExpiry:
+
+ @patch("semantica.ingest.dynamics365_ingestor.DYNAMICS_AVAILABLE", True)
+ def test_expired_token_triggers_reconnect(self):
+ """_ensure_connected must call connect() again when token has expired."""
+ from semantica.ingest.dynamics365_ingestor import Dynamics365Connector
+ import semantica.ingest.dynamics365_ingestor as _mod
+ import time as _time
+
+ mock_msal_app = MagicMock()
+ mock_msal_app.acquire_token_for_client.return_value = {
+ "access_token": "fresh-token",
+ "expires_in": 3600,
+ }
+
+ with patch.object(_mod, "_msal") as mock_msal_mod:
+ mock_msal_mod.ConfidentialClientApplication.return_value = mock_msal_app
+ connector = Dynamics365Connector(
+ tenant_id="t", client_id="c", client_secret="s",
+ org_url="https://myorg.crm.dynamics.com",
+ )
+ # Simulate an already-expired token
+ connector._access_token = "old-token"
+ connector._token_expires_at = _time.time() - 1 # already expired
+
+ connector._ensure_connected()
+
+ # connect() was called again (total calls == 1 since we set state manually)
+ assert mock_msal_app.acquire_token_for_client.call_count == 1
+ assert connector._access_token == "fresh-token"
+
+
+# ---------------------------------------------------------------------------
+# Package-level exports
+# ---------------------------------------------------------------------------
+
+_EXPORTED = ("Dynamics365Ingestor", "Dynamics365Data", "Dynamics365Connector")
+
+
+class TestPackageExports:
+
+ @patch("semantica.ingest.dynamics365_ingestor.DYNAMICS_AVAILABLE", True)
+ def test_classes_importable_from_package(self):
+ import semantica.ingest as ingest_pkg
+ import semantica.ingest.dynamics365_ingestor as _mod
+
+ for name in _EXPORTED:
+ ingest_pkg.__dict__.pop(name, None)
+ try:
+ from semantica.ingest import (
+ Dynamics365Connector,
+ Dynamics365Data,
+ Dynamics365Ingestor,
+ )
+ finally:
+ for name in _EXPORTED:
+ ingest_pkg.__dict__.pop(name, None)
+
+ assert Dynamics365Ingestor is _mod.Dynamics365Ingestor
+ assert Dynamics365Data is _mod.Dynamics365Data
+ assert Dynamics365Connector is _mod.Dynamics365Connector
+ assert set(_EXPORTED) <= set(ingest_pkg.__all__)
+
+ @patch("semantica.ingest.dynamics365_ingestor.DYNAMICS_AVAILABLE", False)
+ def test_package_import_without_msal_gives_install_hint(self):
+ import semantica.ingest as ingest_pkg
+
+ ingest_pkg.__dict__.pop("Dynamics365Ingestor", None)
+ with pytest.raises(ImportError, match=r"semantica\[ingest-dynamics365\]"):
+ from semantica.ingest import Dynamics365Ingestor # noqa: F401
+
+
+# ---------------------------------------------------------------------------
+# MSAL transport goes through the SSRF guard
+# ---------------------------------------------------------------------------
+
+
+class TestMsalTransport:
+
+ @patch("semantica.ingest.dynamics365_ingestor.DYNAMICS_AVAILABLE", True)
+ def test_connect_passes_guarded_http_client_to_msal(self):
+ import semantica.ingest.dynamics365_ingestor as _mod
+
+ mock_msal_app = MagicMock()
+ mock_msal_app.acquire_token_for_client.return_value = {"access_token": "tok"}
+
+ with patch.object(_mod, "_msal") as mock_msal_mod:
+ mock_msal_mod.ConfidentialClientApplication.return_value = mock_msal_app
+ connector = _mod.Dynamics365Connector(
+ tenant_id="t", client_id="c", client_secret="s",
+ org_url="https://myorg.crm.dynamics.com",
+ timeout=12,
+ )
+ connector.connect()
+
+ kwargs = mock_msal_mod.ConfidentialClientApplication.call_args.kwargs
+ assert isinstance(kwargs["http_client"], _mod._SSRFGuardedHttpClient)
+ assert kwargs["http_client"].timeout == 12
+
+ def test_guarded_http_client_routes_get_and_post_through_guard(self):
+ import semantica.ingest.dynamics365_ingestor as _mod
+
+ mock_ssrf = MagicMock()
+ client = _mod._SSRFGuardedHttpClient(timeout=5)
+ token_url = "https://login.microsoftonline.com/t/oauth2/v2.0/token"
+ config_url = (
+ "https://login.microsoftonline.com/t/v2.0/"
+ ".well-known/openid-configuration"
+ )
+
+ with patch.object(_mod, "request_with_ssrf_guard", mock_ssrf):
+ client.get(config_url, headers={"X": "1"})
+ client.post(token_url, data={"grant_type": "client_credentials"})
+
+ assert mock_ssrf.call_args_list == [
+ call("GET", config_url, params=None, headers={"X": "1"}, timeout=5),
+ call(
+ "POST", token_url,
+ params=None, data={"grant_type": "client_credentials"},
+ headers=None, timeout=5,
+ ),
+ ]
+
+ @pytest.mark.skipif(not MSAL_LIB_AVAILABLE, reason="msal not installed")
+ def test_real_msal_requests_go_through_guard(self):
+ import semantica.ingest.dynamics365_ingestor as _mod
+ from semantica.utils.exceptions import ProcessingError
+
+ mock_ssrf = MagicMock(side_effect=RuntimeError("guarded"))
+ with patch.object(_mod, "request_with_ssrf_guard", mock_ssrf):
+ connector = _mod.Dynamics365Connector(
+ tenant_id="t", client_id="c", client_secret="s",
+ org_url="https://myorg.crm.dynamics.com",
+ )
+ with pytest.raises(ProcessingError, match="guarded"):
+ connector.connect()
+
+ assert mock_ssrf.called
+ assert all(
+ c.args[1].startswith("https://login.microsoftonline.com/")
+ for c in mock_ssrf.call_args_list
+ )
diff --git a/uv.lock b/uv.lock
index d973cb99..3985af43 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4643,6 +4643,20 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198, upload-time = "2023-03-07T16:47:09.197Z" },
]
+[[package]]
+name = "msal"
+version = "1.39.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cryptography" },
+ { name = "pyjwt", extra = ["crypto"] },
+ { name = "requests" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/bb/85/747d28986a44b715cc51cf57aa021c8fd94e9614064261ceec77320e8b0b/msal-1.39.0.tar.gz", hash = "sha256:6ab7de335e6d7f5717e2c7e1dbf86e4dda2f6acf3c56773b78dc53ebc6395b5f", size = 205360, upload-time = "2026-09-17T16:07:45.1Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a4/32/178457385925ce301c7b3232bd85665d4df57da39568b62dcfc74031873f/msal-1.39.0-py3-none-any.whl", hash = "sha256:2d2577886906cd7293850dffa2da29119966c213bfc6ec0cecf8bf7621e1ca77", size = 131629, upload-time = "2026-09-17T16:07:46.722Z" },
+]
+
[[package]]
name = "msgpack"
version = "1.2.2"
@@ -8444,6 +8458,9 @@ ingest-airflow = [
ingest-arrow = [
{ name = "pyarrow" },
]
+ingest-dynamics365 = [
+ { name = "msal" },
+]
ingest-git = [
{ name = "gitpython" },
]
@@ -8666,6 +8683,7 @@ requires-dist = [
{ name = "looker-sdk", marker = "extra == 'ingest-looker'", specifier = ">=24.0.0" },
{ name = "lxml", marker = "extra == 'documents'", specifier = ">=6.1.1" },
{ name = "matplotlib", marker = "extra == 'viz'", specifier = ">=3.9.4" },
+ { name = "msal", marker = "extra == 'ingest-dynamics365'", specifier = ">=1.20" },
{ name = "neo4j", marker = "extra == 'graph-amazon-neptune'", specifier = ">=5.0.0" },
{ name = "neo4j", marker = "extra == 'graph-neo4j'", specifier = ">=5.0.0" },
{ name = "networkx", specifier = ">=2.8.0" },
@@ -8750,7 +8768,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-typesafe", "llm-all", "documents", "parse-docling", "parse-pdf", "shacl", "db-snowflake", "db-databricks", "db-arrow", "db-salesforce", "db-redshift", "db-cassandra", "db-bigquery", "ingest-looker", "ingest-parquet", "ingest-arrow", "ingest-tableau", "ingest-sap", "ingest-servicenow", "ingest-airflow", "ingest-git", "db-all", "models-huggingface", "embeddings-local", "nlp-spacy", "nlp-langdetect", "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-typesafe", "llm-all", "documents", "parse-docling", "parse-pdf", "shacl", "db-snowflake", "db-databricks", "db-arrow", "db-salesforce", "db-redshift", "ingest-dynamics365", "db-cassandra", "db-bigquery", "ingest-looker", "ingest-parquet", "ingest-arrow", "ingest-tableau", "ingest-sap", "ingest-servicenow", "ingest-airflow", "ingest-git", "db-all", "models-huggingface", "embeddings-local", "nlp-spacy", "nlp-langdetect", "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 = [