:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add sharepoint source (#112070)
Tom Owersde1aaa49ee95
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 62d0629d987f..1b46ec2b8891 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -699,6 +699,7 @@ the row lists both.| sevdesk | HTTP | requests + `rest_source.RESTClient` | ✅ || sevenshifts | HTTP | requests | ✅ || sftp | SSH (SFTP) | paramiko | ➖ |+| sharepoint | HTTP | requests | ✅ || shipmail | HTTP | requests + `rest_source.RESTClient` | ✅ || shippo | HTTP | requests | ✅ || shipstation | HTTP | requests | ✅ |@@ -1390,7 +1391,6 @@ doesn't conflict with concurrent PRs.- servicetitan- servicetrade- sevalla-- sharepoint- sharetribe- shippo- shopwarediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sample_scrub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sample_scrub.pyindex 189a6a9e9c85..7c52ea1f5b5d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sample_scrub.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sample_scrub.py@@ -49,6 +49,10 @@ REDACT_FIELD_NAMES: frozenset[str] = frozenset(# either grants terminal access, so keep them out of captured HTTP samples too."jupyter_token","jupyter_url",+ # Microsoft Graph drive-item responses can contain preauthenticated URLs that grant+ # temporary access to document contents without any further authorization.+ "@microsoft.graph.downloadurl",+ "content.downloadurl",# Smartlead's email-accounts endpoint returns mailbox SMTP/IMAP credentials under this# key; `password` above already covers the SMTP field, but the IMAP one has a distinct# name and would otherwise reach captured samples raw (the source's own `redact_fields`diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_http_sampling.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_http_sampling.pyindex ca40294968d6..2123aba70531 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_http_sampling.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_http_sampling.py@@ -503,6 +503,16 @@ def test_scrub_body_redacts_webhook_signing_secret():assert out["webhooks"][0]["secret"] == "REDACTED"+def test_scrub_body_redacts_preauthenticated_download_urls():+ out = _scrub_body(+ '{"@microsoft.graph.downloadUrl": "https://download.example/file", '+ '"content.downloadUrl": "https://download.example/content"}'+ )+ assert isinstance(out, dict)+ assert out["@microsoft.graph.downloadUrl"] == "REDACTED"+ assert out["content.downloadUrl"] == "REDACTED"++def test_scrub_body_passes_through_non_json_string():out = _scrub_body("just a string")assert isinstance(out, str)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sharepoint.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sharepoint.pyindex 135b1ff7f329..7ade1bab197a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sharepoint.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sharepoint.py@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass SharePointSourceConfig(config.Config):- pass+ tenant_id: str+ client_id: str+ client_secret: str+ site_urls: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/canonical_descriptions.pynew file mode 100644index 000000000000..20c39c6782f1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/canonical_descriptions.py@@ -0,0 +1,107 @@+"""Canonical, documentation-sourced descriptions for SharePoint endpoints and columns.++Sourced from the Microsoft Graph v1.0 SharePoint and files reference+(https://learn.microsoft.com/en-us/graph/api/resources/sharepoint). Keyed by the endpoint names in+`settings.py` `SHAREPOINT_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced table.+Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "sites": {+ "description": "A SharePoint site: a container for lists, document libraries, and pages.",+ "docs_url": "https://learn.microsoft.com/en-us/graph/api/resources/site",+ "columns": {+ "id": "Unique identifier of the site, in the form hostname,site-collection-id,web-id.",+ "name": "Name of the site.",+ "displayName": "Full title of the site.",+ "description": "Description of the site.",+ "webUrl": "URL that opens the site in a browser.",+ "createdDateTime": "Date and time the site was created.",+ "lastModifiedDateTime": "Date and time the site was last modified.",+ "isPersonalSite": "Whether the site is a personal OneDrive site.",+ "siteCollection": "Details of the site collection the site belongs to, such as its hostname.",+ "root": "Present when the site is the root site of its site collection.",+ },+ },+ "lists": {+ "description": "A list or document library in a SharePoint site.",+ "docs_url": "https://learn.microsoft.com/en-us/graph/api/resources/list",+ "columns": {+ "site_id": "Identifier of the site the list belongs to.",+ "id": "Unique identifier of the list.",+ "name": "Internal name of the list.",+ "displayName": "Display title of the list.",+ "description": "Description of the list.",+ "webUrl": "URL that opens the list in a browser.",+ "createdDateTime": "Date and time the list was created.",+ "lastModifiedDateTime": "Date and time the list was last modified.",+ "createdBy": "Identity of the user or app that created the list.",+ "lastModifiedBy": "Identity of the user or app that last modified the list.",+ "list": "List details: the template it was created from, whether it is hidden, and whether content types are enabled.",+ "eTag": "Version tag of the list.",+ },+ },+ "list_items": {+ "description": "An item in a SharePoint list, such as a row in a custom list or a file entry in a document library.",+ "docs_url": "https://learn.microsoft.com/en-us/graph/api/resources/listitem",+ "columns": {+ "site_id": "Identifier of the site the item's list belongs to.",+ "list_id": "Identifier of the list the item belongs to.",+ "id": "Identifier of the item, unique within its list.",+ "fields": "Values of the list's columns for this item, keyed by column internal name.",+ "webUrl": "URL that opens the item in a browser.",+ "createdDateTime": "Date and time the item was created.",+ "lastModifiedDateTime": "Date and time the item was last modified.",+ "createdBy": "Identity of the user or app that created the item.",+ "lastModifiedBy": "Identity of the user or app that last modified the item.",+ "contentType": "Content type of the item.",+ "parentReference": "Reference to the list that contains the item.",+ "eTag": "Version tag of the item.",+ },+ },+ "drives": {+ "description": "A document library in a SharePoint site, exposed as a drive.",+ "docs_url": "https://learn.microsoft.com/en-us/graph/api/resources/drive",+ "columns": {+ "site_id": "Identifier of the site the drive belongs to.",+ "id": "Unique identifier of the drive.",+ "name": "Name of the drive.",+ "description": "Description of the drive.",+ "driveType": "Type of drive. SharePoint document libraries are documentLibrary.",+ "webUrl": "URL that opens the document library in a browser.",+ "createdDateTime": "Date and time the drive was created.",+ "lastModifiedDateTime": "Date and time the drive was last modified.",+ "createdBy": "Identity of the user or app that created the drive.",+ "lastModifiedBy": "Identity of the user or app that last modified the drive.",+ "owner": "Identity of the owner of the drive.",+ "quota": "Storage quota of the drive.",+ },+ },+ "drive_items": {+ "description": "A file or folder in a SharePoint document library. Rows hold metadata only, not file contents.",+ "docs_url": "https://learn.microsoft.com/en-us/graph/api/resources/driveitem",+ "columns": {+ "site_id": "Identifier of the site the drive belongs to.",+ "drive_id": "Identifier of the drive (document library) the item belongs to.",+ "id": "Identifier of the item, unique within its drive.",+ "name": "File or folder name.",+ "size": "Size of the item in bytes.",+ "webUrl": "URL that opens the item in a browser.",+ "createdDateTime": "Date and time the item was created.",+ "lastModifiedDateTime": "Date and time the item was last modified.",+ "createdBy": "Identity of the user or app that created the item.",+ "lastModifiedBy": "Identity of the user or app that last modified the item.",+ "file": "File details, such as MIME type and hashes. Absent for folders.",+ "folder": "Folder details, such as the child count. Absent for files.",+ "parentReference": "Reference to the parent folder and drive of the item.",+ "fileSystemInfo": "Created and modified times as reported by the client that uploaded the file.",+ "eTag": "Version tag of the whole item, including metadata.",+ "cTag": "Version tag of the item's content.",+ "root": "Present when the item is the root folder of the drive.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/settings.pynew file mode 100644index 000000000000..98ba0ad10afe--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/settings.py@@ -0,0 +1,79 @@+from dataclasses import dataclass+from enum import StrEnum+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField++GRAPH_BASE_URL = "https://graph.microsoft.com/v1.0"+# Entra ID (Azure AD) token endpoint; the tenant id is interpolated into the path.+LOGIN_BASE_URL = "https://login.microsoftonline.com"+# Client-credentials scope for Microsoft Graph. The app's granted application permissions+# (Sites.Read.All or Sites.Selected) decide what the token can actually read.+TOKEN_SCOPE = "https://graph.microsoft.com/.default"++# Hard cap per collection walk so a `@odata.nextLink` that never ends can't spin forever. Far+# above any realistic list or document library at Graph's default page sizes.+MAX_PAGES_PER_COLLECTION = 50_000++SITE_ID_COLUMN = "site_id"+LIST_ID_COLUMN = "list_id"+DRIVE_ID_COLUMN = "drive_id"+++class SharePointEndpoint(StrEnum):+ SITES = "sites"+ LISTS = "lists"+ LIST_ITEMS = "list_items"+ DRIVES = "drives"+ DRIVE_ITEMS = "drive_items"+++@dataclass(frozen=True)+class SharePointEndpointConfig:+ name: SharePointEndpoint+ primary_keys: list[str]+ description: str+ # Stable datetime column for datetime partitioning (None = no datetime partitioning).+ partition_key: Optional[str] = None+++SHAREPOINT_ENDPOINTS: dict[str, SharePointEndpointConfig] = {+ SharePointEndpoint.SITES: SharePointEndpointConfig(+ name=SharePointEndpoint.SITES,+ primary_keys=["id"],+ # `getAllSites` omits `createdDateTime`, so sites can't be partitioned on it.+ description="SharePoint sites the app can read, excluding personal OneDrive sites",+ ),+ SharePointEndpoint.LISTS: SharePointEndpointConfig(+ name=SharePointEndpoint.LISTS,+ primary_keys=[SITE_ID_COLUMN, "id"],+ description="Lists and document libraries in each site",+ partition_key="createdDateTime",+ ),+ SharePointEndpoint.LIST_ITEMS: SharePointEndpointConfig(+ name=SharePointEndpoint.LIST_ITEMS,+ # Item ids are only unique within their list.+ primary_keys=[SITE_ID_COLUMN, LIST_ID_COLUMN, "id"],+ description="Items in every visible list, with the list's column values in `fields`",+ partition_key="createdDateTime",+ ),+ SharePointEndpoint.DRIVES: SharePointEndpointConfig(+ name=SharePointEndpoint.DRIVES,+ primary_keys=[SITE_ID_COLUMN, "id"],+ description="Document libraries (drives) in each site",+ partition_key="createdDateTime",+ ),+ SharePointEndpoint.DRIVE_ITEMS: SharePointEndpointConfig(+ name=SharePointEndpoint.DRIVE_ITEMS,+ # Drive item ids are only guaranteed unique within their drive.+ primary_keys=[DRIVE_ID_COLUMN, "id"],+ description="File and folder metadata in every document library",+ partition_key="createdDateTime",+ ),+}++ENDPOINTS = tuple(SHAREPOINT_ENDPOINTS.keys())++# Graph has no reliable server-side "modified since" filter across lists and drives (list+# filters only work on indexed columns), so every table is full refresh.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in ENDPOINTS}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/sharepoint.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/sharepoint.pynew file mode 100644index 000000000000..f0d56c9a3551--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/sharepoint.py@@ -0,0 +1,518 @@+import dataclasses+from collections.abc import Callable, Iterator+from datetime import UTC, datetime+from typing import Any, Optional+from urllib.parse import quote, urlparse++import requests+import structlog+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.settings import (+ DRIVE_ID_COLUMN,+ GRAPH_BASE_URL,+ LIST_ID_COLUMN,+ LOGIN_BASE_URL,+ MAX_PAGES_PER_COLLECTION,+ SHAREPOINT_ENDPOINTS,+ SITE_ID_COLUMN,+ TOKEN_SCOPE,+ SharePointEndpoint,+)++REQUEST_TIMEOUT_SECONDS = 120+VALIDATE_TIMEOUT_SECONDS = 30++_module_logger: FilteringBoundLogger = structlog.get_logger(__name__)++SITES_DENIED_ERROR = (+ "Microsoft Graph denied access to SharePoint. Grant the app the Sites.Read.All application permission "+ "with admin consent, or list the site URLs it was granted through Sites.Selected."+)+INVALID_SITE_URL_ERROR = "Enter each SharePoint site as a full URL"+++class SharePointSiteURLError(ValueError):+ pass++[email protected](frozen=True)+class SharePointResumeConfig:+ """Position of the walk: the site, the list or drive inside it, and the next page.++ `next_url` is None when the walk restarts at the start of `parent_id` (or of `site_id` for+ tables that have no parent below the site).+ """++ site_id: Optional[str] = None+ parent_id: Optional[str] = None+ next_url: Optional[str] = None+++def _parse_datetime(value: Any) -> Optional[datetime]:+ if isinstance(value, datetime):+ return value if value.tzinfo else value.replace(tzinfo=UTC)+ if not isinstance(value, str) or not value.strip():+ return None+ try:+ parsed = datetime.fromisoformat(value.strip())+ except ValueError:+ return None+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)+++def _normalize(row: dict[str, Any], endpoint: SharePointEndpoint, **parent_columns: str) -> dict[str, Any]:+ row.update(parent_columns)+ partition_key = SHAREPOINT_ENDPOINTS[endpoint].partition_key+ if partition_key is not None:+ # Type the partition column as a real datetime so it buckets by month.+ parsed = _parse_datetime(row.get(partition_key))+ if parsed is not None:+ row[partition_key] = parsed+ return row+++def parse_site_urls(raw: Optional[str]) -> list[str]:+ """Turn the user's site URLs into Graph site paths, e.g. `/sites/contoso.sharepoint.com:/sites/hr:`.++ An empty value means every site the app can read.+ """+ if not raw:+ return []++ paths: list[str] = []+ for entry in raw.replace(",", "\n").splitlines():+ url = entry.strip()+ if not url:+ continue+ parsed = urlparse(url)+ if parsed.scheme != "https" or not parsed.hostname:+ raise SharePointSiteURLError(+ f"{INVALID_SITE_URL_ERROR}, for example https://contoso.sharepoint.com/sites/marketing. Got: {url}"+ )+ hostname = quote(parsed.hostname, safe=".-")+ relative_path = parsed.path.strip("/")+ if relative_path:+ paths.append(f"/sites/{hostname}:/{quote(relative_path, safe='/')}:")+ else:+ paths.append(f"/sites/{hostname}")+ return paths+++def _is_personal_site(site: dict[str, Any]) -> bool:+ # `getAllSites` also returns every user's OneDrive. Those are personal files, not SharePoint.+ if site.get("isPersonalSite"):+ return True+ host = urlparse(site.get("webUrl") or "").hostname or ""+ return host.endswith("-my.sharepoint.com")+++class SharePointClient:+ """Minimal Microsoft Graph client: mints an Entra ID app token and issues GETs.++ Access tokens last about an hour, so a long sync re-mints on the first 401 rather than+ failing the job.+ """++ def __init__(+ self,+ tenant_id: str,+ client_id: str,+ client_secret: str,+ logger: FilteringBoundLogger,+ ) -> None:+ self._tenant_id = tenant_id.strip()+ self._client_id = client_id.strip()+ self._client_secret = client_secret+ self._logger = logger+ self._session = make_tracked_session(redact_values=(client_secret,))+ self._token: Optional[str] = None++ @property+ def token_url(self) -> str:+ return f"{LOGIN_BASE_URL}/{quote(self._tenant_id, safe='')}/oauth2/v2.0/token"++ def mint_token(self) -> str:+ response = self._session.post(+ self.token_url,+ data={+ "grant_type": "client_credentials",+ "client_id": self._client_id,+ "client_secret": self._client_secret,+ "scope": TOKEN_SCOPE,+ },+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ token = response.json().get("access_token")+ if not token:+ raise ValueError("Entra ID did not return an access token for the app registration")+ self._token = token+ return token++ def get(+ self, path_or_url: str, params: Optional[dict[str, str]] = None, timeout: int = REQUEST_TIMEOUT_SECONDS+ ) -> Any:+ if path_or_url.startswith("/"):+ url = f"{GRAPH_BASE_URL}{path_or_url}"+ elif path_or_url.startswith(f"{GRAPH_BASE_URL}/"):+ url = path_or_url+ else:+ # `@odata.nextLink` comes from the response body. Never send the token anywhere but Graph.+ raise ValueError(f"Refusing to follow a non-Graph URL: {path_or_url}")++ if self._token is None:+ self.mint_token()++ def _do() -> requests.Response:+ return self._session.get(+ url,+ params=params,+ headers={"Authorization": f"Bearer {self._token}", "Accept": "application/json"},+ timeout=timeout,+ )++ response = _do()+ if response.status_code == 401:+ self.mint_token()+ response = _do()++ if not response.ok:+ self._logger.error(+ f"Microsoft Graph error: status={response.status_code}, body={response.text[:500]}, url={url}"+ )+ response.raise_for_status()++ return response.json()+++def _status(error: requests.HTTPError) -> Optional[int]:+ return error.response.status_code if error.response is not None else None+++def _walk_collection(+ client: SharePointClient,+ path: str,+ params: Optional[dict[str, str]],+ start_url: Optional[str],+ stage_next: Callable[[str], None],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Follow `@odata.nextLink` through one Graph collection, staging each next page before its yield."""+ url = start_url or path+ # The next link already carries every query option, so params only go on the first request.+ request_params = None if start_url else params++ for _ in range(MAX_PAGES_PER_COLLECTION):+ body = client.get(url, params=request_params)+ rows = body.get("value") or []+ next_url = body.get("@odata.nextLink")+ if next_url:+ stage_next(next_url)+ if rows:+ yield rows+ if not next_url:+ return+ url = next_url+ request_params = None++ logger.warning(f"SharePoint: hit the {MAX_PAGES_PER_COLLECTION}-page cap for {path}, later rows are skipped")+++def _walk_child_collection(+ client: SharePointClient,+ path: str,+ params: Optional[dict[str, str]],+ start_url: Optional[str],+ stage_next: Callable[[str], None],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Like `_walk_collection`, but a 404 skips the collection: sites and lists can go away mid-sync."""+ try:+ yield from _walk_collection(client, path, params, start_url, stage_next, logger)+ except requests.HTTPError as e:+ if _status(e) != 404:+ raise+ logger.warning(f"SharePoint: {path} no longer exists, skipping it")+++def _list_sites(client: SharePointClient, site_paths: list[str], logger: FilteringBoundLogger) -> list[dict[str, Any]]:+ if site_paths:+ return [site for path in site_paths if not _is_personal_site(site := client.get(path))]++ sites: list[dict[str, Any]] = []+ for page in _walk_collection(client, "/sites/getAllSites", None, None, lambda _: None, logger):+ sites.extend(site for site in page if not _is_personal_site(site))+ return sites+++def _resume_index(ids: list[str], resume_id: Optional[str]) -> Optional[int]:+ if resume_id is None:+ return None+ try:+ return ids.index(resume_id)+ except ValueError:+ return None+++def _iter_sites(+ client: SharePointClient,+ site_paths: list[str],+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[SharePointResumeConfig],+ resume: Optional[SharePointResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ if site_paths:+ sites = _list_sites(client, site_paths, logger)+ if sites:+ yield [_normalize(site, SharePointEndpoint.SITES) for site in sites]+ return++ def stage(next_url: str) -> None:+ manager.save_state(SharePointResumeConfig(next_url=next_url))++ start_url = resume.next_url if resume is not None else None+ for page in _walk_collection(client, "/sites/getAllSites", None, start_url, stage, logger):+ rows = [_normalize(site, SharePointEndpoint.SITES) for site in page if not _is_personal_site(site)]+ if rows:+ yield rows+ else:+ manager.safe_point()+++def _iter_site_children(+ client: SharePointClient,+ endpoint: SharePointEndpoint,+ collection: str,+ sites: list[dict[str, Any]],+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[SharePointResumeConfig],+ resume: Optional[SharePointResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Rows of `/sites/{id}/{collection}` for every site: the `lists` and `drives` tables."""+ site_ids = [site["id"] for site in sites]+ start = _resume_index(site_ids, resume.site_id if resume is not None else None)+ start_url = resume.next_url if resume is not None and start is not None else None++ for site_id in site_ids[start or 0 :]:+ manager.save_state(SharePointResumeConfig(site_id=site_id))+ yielded = False++ def stage(next_url: str, site_id: str = site_id) -> None:+ manager.save_state(SharePointResumeConfig(site_id=site_id, next_url=next_url))++ path = f"/sites/{quote(site_id, safe=',.-')}/{collection}"+ for page in _walk_child_collection(client, path, None, start_url, stage, logger):+ yielded = True+ yield [_normalize(row, endpoint, **{SITE_ID_COLUMN: site_id}) for row in page]+ start_url = None+ if not yielded:+ manager.safe_point()+++def _iter_grandchildren(+ client: SharePointClient,+ endpoint: SharePointEndpoint,+ sites: list[dict[str, Any]],+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[SharePointResumeConfig],+ resume: Optional[SharePointResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Rows inside every list (`list_items`) or every drive (`drive_items`) of every site."""+ site_ids = [site["id"] for site in sites]+ site_start = _resume_index(site_ids, resume.site_id if resume is not None else None)+ resume_parent_id = resume.parent_id if resume is not None and site_start is not None else None+ resume_next_url = resume.next_url if resume is not None and site_start is not None else None++ for site_id in site_ids[site_start or 0 :]:+ quoted_site = quote(site_id, safe=",.-")+ parents = _site_parents(client, endpoint, quoted_site, logger)+ parent_ids = [parent["id"] for parent in parents]+ parent_start = _resume_index(parent_ids, resume_parent_id)+ start_url = resume_next_url if parent_start is not None else None+ resume_parent_id = None+ resume_next_url = None++ if not parent_ids:+ manager.save_state(SharePointResumeConfig(site_id=site_id))+ manager.safe_point()+ continue++ for parent_id in parent_ids[parent_start or 0 :]:+ manager.save_state(SharePointResumeConfig(site_id=site_id, parent_id=parent_id))+ yielded = False++ def stage(next_url: str, site_id: str = site_id, parent_id: str = parent_id) -> None:+ manager.save_state(SharePointResumeConfig(site_id=site_id, parent_id=parent_id, next_url=next_url))++ for page in _iter_parent_rows(client, endpoint, quoted_site, site_id, parent_id, start_url, stage, logger):+ yielded = True+ yield page+ start_url = None+ if not yielded:+ manager.safe_point()+++def _site_parents(+ client: SharePointClient, endpoint: SharePointEndpoint, quoted_site: str, logger: FilteringBoundLogger+) -> list[dict[str, Any]]:+ collection = "lists" if endpoint == SharePointEndpoint.LIST_ITEMS else "drives"+ parents: list[dict[str, Any]] = []+ path = f"/sites/{quoted_site}/{collection}"+ for page in _walk_child_collection(client, path, None, None, lambda _: None, logger):+ for parent in page:+ # Hidden lists are SharePoint's own plumbing (workflow history, user info, and so on).+ if endpoint == SharePointEndpoint.LIST_ITEMS and (parent.get("list") or {}).get("hidden"):+ continue+ parents.append(parent)+ return parents+++def _iter_parent_rows(+ client: SharePointClient,+ endpoint: SharePointEndpoint,+ quoted_site: str,+ site_id: str,+ parent_id: str,+ start_url: Optional[str],+ stage: Callable[[str], None],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ quoted_parent = quote(parent_id, safe="!-_")++ if endpoint == SharePointEndpoint.LIST_ITEMS:+ path = f"/sites/{quoted_site}/lists/{quoted_parent}/items"+ for page in _walk_child_collection(client, path, {"expand": "fields"}, start_url, stage, logger):+ yield [_normalize(row, endpoint, **{SITE_ID_COLUMN: site_id, LIST_ID_COLUMN: parent_id}) for row in page]+ return++ # Delta is the only enumeration Graph guarantees returns every item in a drive, and it walks+ # every folder level in one flat feed. The same item can show up more than once, so keep the+ # first copy. The seen set is per drive and is lost on resume, so a resumed drive can repeat rows.+ seen: set[str] = set()+ path = f"/drives/{quoted_parent}/root/delta"+ for page in _walk_child_collection(client, path, None, start_url, stage, logger):+ rows = []+ for row in page:+ item_id = row.get("id")+ if row.get("deleted") is not None or item_id is None or item_id in seen:+ continue+ seen.add(item_id)+ # Graph's preauthenticated download URL grants temporary access to the document contents.+ # This metadata source must not persist it in the warehouse.+ row.pop("@microsoft.graph.downloadUrl", None)+ rows.append(_normalize(row, endpoint, **{SITE_ID_COLUMN: site_id, DRIVE_ID_COLUMN: parent_id}))+ if rows:+ yield rows+++def _get_rows(+ tenant_id: str,+ client_id: str,+ client_secret: str,+ site_urls: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SharePointResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ sharepoint_endpoint = SharePointEndpoint(endpoint)+ site_paths = parse_site_urls(site_urls)+ client = SharePointClient(tenant_id, client_id, client_secret, logger)+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if sharepoint_endpoint == SharePointEndpoint.SITES:+ yield from _iter_sites(client, site_paths, logger, resumable_source_manager, resume)+ return++ sites = _list_sites(client, site_paths, logger)++ if sharepoint_endpoint in (SharePointEndpoint.LISTS, SharePointEndpoint.DRIVES):+ yield from _iter_site_children(+ client, sharepoint_endpoint, sharepoint_endpoint.value, sites, logger, resumable_source_manager, resume+ )+ return++ yield from _iter_grandchildren(client, sharepoint_endpoint, sites, logger, resumable_source_manager, resume)+++def sharepoint_source(+ tenant_id: str,+ client_id: str,+ client_secret: str,+ site_urls: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SharePointResumeConfig],+) -> SourceResponse:+ config = SHAREPOINT_ENDPOINTS[endpoint]+ has_datetime_partition = config.partition_key is not None++ return SourceResponse(+ name=endpoint,+ items=lambda: _get_rows(+ tenant_id=tenant_id,+ client_id=client_id,+ client_secret=client_secret,+ site_urls=site_urls,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if has_datetime_partition else None,+ partition_format="month" if has_datetime_partition else None,+ partition_keys=[config.partition_key] if config.partition_key is not None else None,+ sort_mode="asc",+ )+++def validate_credentials(+ tenant_id: str,+ client_id: str,+ client_secret: str,+ site_urls: Optional[str],+) -> tuple[bool, Optional[str]]:+ if not tenant_id.strip():+ return False, "Enter the directory (tenant) ID of your Entra ID tenant."++ try:+ site_paths = parse_site_urls(site_urls)+ except SharePointSiteURLError as e:+ return False, str(e)++ client = SharePointClient(tenant_id, client_id, client_secret, _module_logger)++ try:+ client.mint_token()+ except requests.HTTPError as e:+ status = _status(e)+ if status in (400, 401):+ return (+ False,+ "Entra ID rejected the app registration. Check the tenant ID, application (client) ID, "+ "and client secret.",+ )+ return False, f"Could not get a token from Entra ID (status {status})."+ except Exception as e:+ return False, f"Could not reach Entra ID ({e}). Please retry."++ probes = site_paths or ["/sites/getAllSites"]+ for path in probes:+ try:+ client.get(path, timeout=VALIDATE_TIMEOUT_SECONDS)+ except requests.HTTPError as e:+ status = _status(e)+ if status in (401, 403):+ return False, SITES_DENIED_ERROR+ if status == 404:+ return False, f"SharePoint couldn't find the site {path}. Check the site URL."+ return False, f"Microsoft Graph returned an unexpected status ({status})."+ except Exception as e:+ return False, f"Could not reach Microsoft Graph ({e}). Please retry."++ return True, Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/source.pyindex b8637c234fac..e04f63f5b4ae 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/source.py@@ -1,27 +1,186 @@-from typing import cast+from typing import Optional, cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sharepoint import (SharePointSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SHAREPOINT_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.sharepoint import (+ INVALID_SITE_URL_ERROR,+ SITES_DENIED_ERROR,+ SharePointResumeConfig,+ sharepoint_source,+ validate_credentials as validate_sharepoint_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SharePointSource(SimpleSource[SharePointSourceConfig]):+class SharePointSource(ResumableSource[SharePointSourceConfig, SharePointResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # `v1.0` is Microsoft Graph's only GA channel; `beta` is preview and not for production use.+ supported_versions = ("v1.0",)+ default_version = "v1.0"+ api_docs_url = "https://learn.microsoft.com/en-us/graph/versioning-and-support"++ @property+ def connection_host_fields(self) -> list[str]:+ # `tenant_id` selects which Entra directory the client secret is sent to. Without it here,+ # an editor could repoint a preserved secret at another tenant of a multi-tenant app.+ return ["tenant_id"]+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SHAREPOINT+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ INVALID_SITE_URL_ERROR: None,+ "400 Client Error: Bad Request for url: https://login.microsoftonline.com": (+ "Entra ID rejected the app registration. Check the tenant ID, application (client) ID, "+ "and client secret."+ ),+ "401 Client Error: Unauthorized for url: https://login.microsoftonline.com": (+ "Entra ID rejected the app credentials. Generate a new client secret and reconnect."+ ),+ "401 Client Error: Unauthorized for url: https://graph.microsoft.com": SITES_DENIED_ERROR,+ "403 Client Error: Forbidden for url: https://graph.microsoft.com": SITES_DENIED_ERROR,+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: SharePointSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ descriptions={name: endpoint.description for name, endpoint in SHAREPOINT_ENDPOINTS.items()},+ )++ def validate_credentials(+ self,+ config: SharePointSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_sharepoint_credentials(+ tenant_id=config.tenant_id,+ client_id=config.client_id,+ client_secret=config.client_secret,+ site_urls=config.site_urls,+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SharePointResumeConfig]:+ return ResumableSourceManager[SharePointResumeConfig](inputs, SharePointResumeConfig).with_namespace(+ inputs.schema_name+ )++ def source_for_pipeline(+ self,+ config: SharePointSourceConfig,+ resumable_source_manager: ResumableSourceManager[SharePointResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return sharepoint_source(+ tenant_id=config.tenant_id,+ client_id=config.client_id,+ client_secret=config.client_secret,+ site_urls=config.site_urls,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.SHAREPOINT,category=DataWarehouseSourceCategory.FILE_STORAGE,label="SharePoint",+ keywords=["microsoft", "sharepoint online", "office 365", "microsoft 365"],+ caption=(+ "Sync SharePoint Online sites, lists and list items, document libraries, and file metadata "+ "through Microsoft Graph.\n\n"+ "Create an Entra ID app registration and add a client secret. Grant it the **Sites.Read.All** "+ "Microsoft Graph application permission and give admin consent. To limit access to a few "+ "sites, grant **Sites.Selected** instead and list those site URLs below. Then enter the "+ "directory (tenant) ID, application (client) ID, and client secret.\n\n"+ "Personal OneDrive sites are not synced."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/sharepoint",iconPath="/static/services/sharepoint.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="tenant_id",+ label="Directory (tenant) ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="00000000-0000-0000-0000-000000000000",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_id",+ label="Application (client) ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="00000000-0000-0000-0000-000000000000",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="site_urls",+ label="Site URLs (optional)",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=False,+ placeholder="https://contoso.sharepoint.com/sites/marketing",+ caption="One site URL per line. Leave empty to sync every site the app can read.",+ secret=False,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/tests/test_sharepoint.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/tests/test_sharepoint.pynew file mode 100644index 000000000000..21fd00abc5c6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/tests/test_sharepoint.py@@ -0,0 +1,337 @@+from datetime import UTC, datetime+from typing import Any, Optional, Union++import pytest+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.settings import (+ ENDPOINTS,+ GRAPH_BASE_URL,+ SHAREPOINT_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.sharepoint import (+ INVALID_SITE_URL_ERROR,+ SITES_DENIED_ERROR,+ SharePointResumeConfig,+ SharePointSiteURLError,+ _get_rows,+ parse_site_urls,+ validate_credentials,+)++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.sharepoint"++TENANT_ID = "11111111-1111-1111-1111-111111111111"+CLIENT_ID = "22222222-2222-2222-2222-222222222222"+CLIENT_SECRET = "super-secret"++SITE_A = "contoso.sharepoint.com,aaaa,1111"+SITE_B = "contoso.sharepoint.com,bbbb,2222"++Route = Union[dict[str, Any], int]+++def _response(status: int = 200, json_body: Any = None) -> mock.MagicMock:+ response = mock.MagicMock(spec=requests.Response)+ response.status_code = status+ response.ok = 200 <= status < 300+ response.text = ""+ response.json.return_value = json_body if json_body is not None else {}+ if not response.ok:+ response.raise_for_status.side_effect = requests.HTTPError(f"{status} Client Error", response=response)+ else:+ response.raise_for_status.return_value = None+ return response+++def _token_response() -> mock.MagicMock:+ return _response(200, {"access_token": "token-1", "expires_in": 3599})+++def _session(routes: dict[str, Route], post_responses: Optional[list[mock.MagicMock]] = None) -> Any:+ session = mock.MagicMock(spec=requests.Session)++ def _get(url: str, **kwargs: Any) -> mock.MagicMock:+ route = routes[url]+ if isinstance(route, int):+ return _response(route)+ return _response(200, route)++ session.get.side_effect = _get+ session.post.side_effect = post_responses if post_responses is not None else [_token_response()]+ return session+++def _manager(resume_state: Optional[SharePointResumeConfig] = None) -> Any:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _rows(+ endpoint: str, session: Any, manager: Optional[Any] = None, site_urls: Optional[str] = None+) -> list[dict[str, Any]]:+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ pages = list(+ _get_rows(+ tenant_id=TENANT_ID,+ client_id=CLIENT_ID,+ client_secret=CLIENT_SECRET,+ site_urls=site_urls,+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=manager if manager is not None else _manager(),+ )+ )+ return [row for page in pages for row in page]+++def _g(path: str) -> str:+ return f"{GRAPH_BASE_URL}{path}"+++ALL_SITES_ROUTES: dict[str, Route] = {+ _g("/sites/getAllSites"): {+ "value": [+ {"id": SITE_A, "webUrl": "https://contoso.sharepoint.com/sites/a", "isPersonalSite": False},+ {"id": "personal-1", "webUrl": "https://contoso-my.sharepoint.com/personal/x", "isPersonalSite": True},+ ],+ "@odata.nextLink": _g("/sites/getAllSites?$skiptoken=page2"),+ },+ _g("/sites/getAllSites?$skiptoken=page2"): {+ "value": [+ # Older tenants can omit `isPersonalSite`, so the -my host alone must exclude OneDrive.+ {"id": "personal-2", "webUrl": "https://contoso-my.sharepoint.com/personal/y"},+ {"id": SITE_B, "webUrl": "https://contoso.sharepoint.com/sites/b"},+ ],+ },+}+++class TestParseSiteUrls:+ @parameterized.expand(+ [+ ("empty", None, []),+ ("blank_lines", "\n \n", []),+ ("root_site", "https://contoso.sharepoint.com", ["/sites/contoso.sharepoint.com"]),+ (+ "site_path_with_trailing_slash",+ "https://contoso.sharepoint.com/sites/marketing/",+ ["/sites/contoso.sharepoint.com:/sites/marketing:"],+ ),+ (+ "space_in_path_is_encoded",+ "https://contoso.sharepoint.com/sites/Sales Team",+ ["/sites/contoso.sharepoint.com:/sites/Sales%20Team:"],+ ),+ (+ "newline_and_comma_separated",+ "https://contoso.sharepoint.com/sites/a\nhttps://contoso.sharepoint.com/sites/b, https://contoso.sharepoint.com",+ [+ "/sites/contoso.sharepoint.com:/sites/a:",+ "/sites/contoso.sharepoint.com:/sites/b:",+ "/sites/contoso.sharepoint.com",+ ],+ ),+ ]+ )+ def test_builds_graph_site_paths(self, _name: str, raw: Optional[str], expected: list[str]) -> None:+ assert parse_site_urls(raw) == expected++ @parameterized.expand([("http", "http://contoso.sharepoint.com/sites/a"), ("no_scheme", "contoso.sharepoint.com")])+ def test_rejects_non_https_urls(self, _name: str, raw: str) -> None:+ with pytest.raises(SharePointSiteURLError, match=INVALID_SITE_URL_ERROR):+ parse_site_urls(raw)+++class TestSharePointRows:+ def test_sites_follow_next_link_and_skip_personal_sites(self) -> None:+ rows = _rows("sites", _session(ALL_SITES_ROUTES))++ assert [row["id"] for row in rows] == [SITE_A, SITE_B]++ @pytest.mark.parametrize("endpoint", ["sites", "drives"])+ def test_explicit_personal_site_is_skipped(self, endpoint: str) -> None:+ site_url = "https://contoso-my.sharepoint.com/personal/user"+ routes: dict[str, Route] = {+ _g("/sites/contoso-my.sharepoint.com:/personal/user:"): {+ "id": "personal-1",+ "webUrl": site_url,+ "isPersonalSite": True,+ }+ }++ assert _rows(endpoint, _session(routes), site_urls=site_url) == []++ def test_next_link_outside_graph_is_refused(self) -> None:+ routes: dict[str, Route] = {+ _g("/sites/getAllSites"): {"value": [{"id": SITE_A}], "@odata.nextLink": "https://evil.example.com/next"}+ }++ with pytest.raises(ValueError, match="non-Graph URL"):+ _rows("sites", _session(routes))++ def test_list_items_skip_hidden_lists_and_carry_parent_ids(self) -> None:+ routes: dict[str, Route] = {+ _g(f"/sites/contoso.sharepoint.com:/sites/a:"): {"id": SITE_A},+ _g(f"/sites/{SITE_A}/lists"): {+ "value": [+ {"id": "list-1", "list": {"hidden": False}},+ {"id": "hidden-list", "list": {"hidden": True}},+ {"id": "deleted-list"},+ ]+ },+ _g(f"/sites/{SITE_A}/lists/list-1/items"): {+ "value": [{"id": "1", "createdDateTime": "2026-01-02T03:04:05Z", "fields": {"Title": "Widget"}}],+ },+ _g(f"/sites/{SITE_A}/lists/deleted-list/items"): 404,+ }+ session = _session(routes)++ rows = _rows("list_items", session, site_urls="https://contoso.sharepoint.com/sites/a")++ assert rows == [+ {+ "id": "1",+ "createdDateTime": datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),+ "fields": {"Title": "Widget"},+ "site_id": SITE_A,+ "list_id": "list-1",+ }+ ]+ item_calls = [c for c in session.get.call_args_list if c.args[0].endswith("/list-1/items")]+ assert item_calls[0].kwargs["params"] == {"expand": "fields"}+ assert all("hidden-list" not in c.args[0] for c in session.get.call_args_list)++ def test_drive_items_drop_deleted_and_repeated_items(self) -> None:+ routes: dict[str, Route] = {+ **ALL_SITES_ROUTES,+ _g(f"/sites/{SITE_A}/drives"): {"value": [{"id": "b!drive-a"}]},+ _g(f"/sites/{SITE_B}/drives"): {"value": []},+ _g("/drives/b!drive-a/root/delta"): {+ "value": [+ {"id": "root", "root": {}},+ {"id": "f1", "file": {}, "@microsoft.graph.downloadUrl": "https://temporary.example.com/file"},+ {"id": "gone", "deleted": {}},+ ],+ "@odata.nextLink": _g("/drives/b!drive-a/root/delta?token=2"),+ },+ _g("/drives/b!drive-a/root/delta?token=2"): {"value": [{"id": "f1", "file": {}}, {"id": "f2", "file": {}}]},+ }++ rows = _rows("drive_items", _session(routes))++ assert [(row["drive_id"], row["id"]) for row in rows] == [+ ("b!drive-a", "root"),+ ("b!drive-a", "f1"),+ ("b!drive-a", "f2"),+ ]+ assert all(row["site_id"] == SITE_A for row in rows)+ assert all("@microsoft.graph.downloadUrl" not in row for row in rows)++ def test_expired_token_is_reminted_once(self) -> None:+ session = _session({}, post_responses=[_token_response(), _token_response()])+ session.get.side_effect = [_response(401), _response(200, {"value": [{"id": SITE_A}]})]++ rows = _rows("sites", session)++ assert [row["id"] for row in rows] == [SITE_A]+ assert session.post.call_count == 2+++class TestSharePointResume:+ def test_list_items_resume_mid_list_on_saved_page(self) -> None:+ resume_url = _g(f"/sites/{SITE_B}/lists/list-b2/items?$skiptoken=5")+ routes: dict[str, Route] = {+ **ALL_SITES_ROUTES,+ _g(f"/sites/{SITE_B}/lists"): {"value": [{"id": "list-b1"}, {"id": "list-b2"}, {"id": "list-b3"}]},+ resume_url: {"value": [{"id": "6"}]},+ _g(f"/sites/{SITE_B}/lists/list-b3/items"): {"value": [{"id": "1"}]},+ }+ session = _session(routes)+ manager = _manager(SharePointResumeConfig(site_id=SITE_B, parent_id="list-b2", next_url=resume_url))++ rows = _rows("list_items", session, manager=manager)++ assert [(row["list_id"], row["id"]) for row in rows] == [("list-b2", "6"), ("list-b3", "1")]+ resumed_call = next(c for c in session.get.call_args_list if c.args[0] == resume_url)+ # The next link already carries `expand`; sending params again would duplicate it.+ assert resumed_call.kwargs["params"] is None++ def test_resume_on_a_site_that_is_gone_restarts_from_the_first_site(self) -> None:+ routes: dict[str, Route] = {+ **ALL_SITES_ROUTES,+ _g(f"/sites/{SITE_A}/lists"): {"value": [{"id": "list-a"}]},+ _g(f"/sites/{SITE_B}/lists"): {"value": [{"id": "list-b"}]},+ }+ manager = _manager(SharePointResumeConfig(site_id="deleted-site", next_url=_g("/stale")))++ rows = _rows("lists", _session(routes), manager=manager)++ assert [(row["site_id"], row["id"]) for row in rows] == [(SITE_A, "list-a"), (SITE_B, "list-b")]++ def test_next_page_is_staged_before_its_rows_are_yielded(self) -> None:+ manager = _manager()+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=_session(ALL_SITES_ROUTES)):+ pages = _get_rows(TENANT_ID, CLIENT_ID, CLIENT_SECRET, None, "sites", mock.MagicMock(), manager)+ next(pages)++ manager.save_state.assert_called_once_with(+ SharePointResumeConfig(next_url=_g("/sites/getAllSites?$skiptoken=page2"))+ )+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("token_rejected", 401, None, None, "Entra ID rejected the app registration"),+ ("token_bad_request", 400, None, None, "Entra ID rejected the app registration"),+ ("graph_forbidden", 200, 403, None, SITES_DENIED_ERROR),+ ("site_not_found", 200, 404, "https://contoso.sharepoint.com/sites/a", "couldn't find the site"),+ ("ok", 200, 200, None, None),+ ]+ )+ def test_maps_status_to_message(+ self,+ _name: str,+ token_status: int,+ graph_status: Optional[int],+ site_urls: Optional[str],+ expected_error: Optional[str],+ ) -> None:+ token = _token_response() if token_status == 200 else _response(token_status)+ session = _session({}, post_responses=[token])+ session.get.side_effect = [_response(graph_status or 200, {"value": []})]++ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ ok, error = validate_credentials(TENANT_ID, CLIENT_ID, CLIENT_SECRET, site_urls)++ assert ok is (expected_error is None)+ if expected_error is None:+ assert error is None+ else:+ assert error is not None and expected_error in error++ def test_invalid_site_url_fails_before_any_request(self) -> None:+ session = _session({})++ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ ok, error = validate_credentials(TENANT_ID, CLIENT_ID, CLIENT_SECRET, "contoso.sharepoint.com/sites/a")++ assert not ok+ assert error is not None and error.startswith(INVALID_SITE_URL_ERROR)+ session.post.assert_not_called()+++def test_canonical_descriptions_document_every_primary_key() -> None:+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)+ for name, entry in CANONICAL_DESCRIPTIONS.items():+ assert set(SHAREPOINT_ENDPOINTS[name].primary_keys) <= set(entry["columns"])