Skip to content

: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.

feat(data-warehouse): implement sentinelone import source (#71174)

Tom Owers39544f3e673e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index ae6eaa072128..9ef463846529 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -434,6 +434,7 @@ the row lists both.
| semgrep | HTTP | requests | ✅ |
| sendgrid | HTTP | requests | ✅ |
| sendowl | HTTP | requests | ✅ |
+| sentinelone | HTTP | requests | ✅ |
| sentry | HTTP | requests + `rest_source.RESTClient` | ✅ |
| servicenow | HTTP | requests | ✅ |
| shippo | HTTP | requests | ✅ |
@@ -889,7 +890,6 @@ doesn't conflict with concurrent PRs.
- semaphore
- sendpulse
- senseforce
-- sentinelone
- serpstat
- sevenshifts
- sftp
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 52da6a9c9828..b245f0624bf0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -3810,7 +3810,8 @@ class SenseforceSourceConfig(config.Config):
@config.config
class SentineloneSourceConfig(config.Config):
- pass
+ console_url: str
+ api_token: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/canonical_descriptions.py
new file mode 100644
index 000000000000..f06290d7af91
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/canonical_descriptions.py
@@ -0,0 +1,91 @@
+"""Canonical, documentation-sourced descriptions for SentinelOne endpoints and columns.
+
+Sourced from the SentinelOne Management API v2.1 reference (available in each tenant's
+console under `/api-doc`) and its public mirrors. Keyed by the endpoint names in
+`settings.py` `SENTINELONE_ENDPOINTS`, which match the `ExternalDataSchema.name` of a
+synced SentinelOne 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 = {
+ "threats": {
+ "description": "A threat detected by SentinelOne, with detection details, classification, and mitigation status.",
+ "columns": {
+ "id": "Unique identifier for the threat.",
+ "threatInfo": "Detection details: threat name, classification, confidence level, analyst verdict, incident status, and mitigation status.",
+ "agentDetectionInfo": "Snapshot of the detecting agent at detection time (site, group, OS, policy).",
+ "agentRealtimeInfo": "Current state of the agent the threat was detected on.",
+ "mitigationStatus": "Mitigation actions taken for the threat and their results.",
+ "indicators": "Behavioral indicators that contributed to the detection.",
+ "createdAt": "Time at which the threat was created (hoisted from threatInfo).",
+ "updatedAt": "Time at which the threat was last updated (hoisted from threatInfo).",
+ },
+ },
+ "agents": {
+ "description": "A SentinelOne agent — an endpoint (workstation or server) with its inventory, health, and protection state.",
+ "columns": {
+ "id": "Unique identifier for the agent.",
+ "computerName": "Hostname of the endpoint.",
+ "agentVersion": "Installed SentinelOne agent version.",
+ "osName": "Operating system name of the endpoint.",
+ "osType": "Operating system family (windows, macos, linux).",
+ "isActive": "Whether the agent is currently active.",
+ "infected": "Whether the endpoint has unresolved threats.",
+ "networkStatus": "Network quarantine state of the endpoint (connected, disconnected).",
+ "siteId": "Identifier of the site the agent belongs to.",
+ "groupId": "Identifier of the group the agent belongs to.",
+ "lastActiveDate": "Time the agent last communicated with the console.",
+ "registeredAt": "Time the agent registered with the console.",
+ "createdAt": "Time at which the agent record was created.",
+ "updatedAt": "Time at which the agent record was last updated.",
+ },
+ },
+ "activities": {
+ "description": "The activity log — an append-only audit trail of console and agent events (logins, policy changes, mitigations, and more).",
+ "columns": {
+ "id": "Unique identifier for the activity.",
+ "activityType": "Numeric code identifying the kind of activity.",
+ "primaryDescription": "Human-readable description of the activity.",
+ "secondaryDescription": "Additional context for the activity.",
+ "userId": "Identifier of the console user who performed the activity, if any.",
+ "agentId": "Identifier of the agent the activity relates to, if any.",
+ "siteId": "Identifier of the site the activity occurred in.",
+ "threatId": "Identifier of the related threat, if any.",
+ "data": "Structured payload with activity-specific fields.",
+ "createdAt": "Time at which the activity occurred.",
+ },
+ },
+ "groups": {
+ "description": "A group — a policy-scoped collection of agents within a site.",
+ "columns": {
+ "id": "Unique identifier for the group.",
+ "name": "Name of the group.",
+ "siteId": "Identifier of the site the group belongs to.",
+ "type": "How membership is managed (static or dynamic).",
+ "filterId": "Identifier of the dynamic filter driving membership, if any.",
+ "rank": "Priority of the group among a site's dynamic groups.",
+ "totalAgents": "Number of agents in the group.",
+ "createdAt": "Time at which the group was created.",
+ "updatedAt": "Time at which the group was last updated.",
+ },
+ },
+ "sites": {
+ "description": "A site — a tenant subdivision with its own licensing, policies, and users.",
+ "columns": {
+ "id": "Unique identifier for the site.",
+ "name": "Name of the site.",
+ "accountId": "Identifier of the account the site belongs to.",
+ "accountName": "Name of the account the site belongs to.",
+ "activeLicenses": "Number of licenses in use in the site.",
+ "totalLicenses": "Number of licenses allocated to the site.",
+ "state": "Lifecycle state of the site (active, expired, deleted).",
+ "siteType": "License type of the site (trial, paid).",
+ "expiration": "Time at which the site's license expires.",
+ "createdAt": "Time at which the site was created.",
+ "updatedAt": "Time at which the site was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/sentinelone.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/sentinelone.py
new file mode 100644
index 000000000000..b26a7e87a874
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/sentinelone.py
@@ -0,0 +1,375 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import parse_qsl, urlencode, urlparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+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.mixins import _is_host_safe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.sentinelone.settings import (
+ SENTINELONE_ENDPOINTS,
+ SentinelOneEndpointConfig,
+)
+
+API_BASE_PATH = "/web/api/v2.1"
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+MAX_RETRY_AFTER_SECONDS = 60
+
+HOST_NOT_ALLOWED_ERROR = "SentinelOne console URL is not allowed"
+
+
+class SentinelOneRetryableError(Exception):
+ def __init__(self, message: str, retry_after: float | None = None) -> None:
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+class SentinelOneHostNotAllowedError(Exception):
+ pass
+
+
+class SentinelOneResumeConfig:
+ next_url: str
+
+
+def normalize_console_url(console_url: str) -> str:
+ """Turn whatever the user typed into a bare SentinelOne console host.
+
+ Accepts values like ``usea1-example.sentinelone.net``,
+ ``https://usea1-example.sentinelone.net/``, or a pasted API URL with the
+ ``/web/api/v2.1`` path, and returns ``usea1-example.sentinelone.net``.
+ """
+ console_url = console_url.strip()
+ console_url = re.sub(r"^https?://", "", console_url, flags=re.IGNORECASE)
+ console_url = console_url.split("/")[0]
+ return console_url.strip().rstrip("/")
+
+
+def _base_url(console_url: str) -> str:
+ return f"https://{normalize_console_url(console_url)}{API_BASE_PATH}"
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"ApiToken {api_token}",
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ }
+
+
+def _format_datetime_z(dt: datetime) -> str:
+ """SentinelOne accepts ISO 8601 timestamps; use millisecond precision with a ``Z`` suffix."""
+ utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+
+
+def _format_incremental_value(value: Any) -> str:
+ if isinstance(value, datetime):
+ return _format_datetime_z(value)
+ if isinstance(value, date):
+ return _format_datetime_z(datetime.combine(value, datetime.min.time(), tzinfo=UTC))
+ return str(value)
+
+
+def _build_initial_params(
+ config: SentinelOneEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"limit": config.page_size}
+
+ if config.default_incremental_field is None:
+ # Full-refresh-only endpoint (groups, sites): stay on the API's default order —
+ # their sortBy enums aren't verifiable without a live tenant.
+ return params
+
+ # Cursor pagination needs a deterministic ascending walk for the watermark to be
+ # meaningful; sort by the field we filter on (createdAt for full refreshes, since
+ # it's stable while rows are inserted mid-sync).
+ sort_field = (
+ (incremental_field or config.default_incremental_field) if should_use_incremental_field else "createdAt"
+ )
+ params["sortBy"] = sort_field
+ params["sortOrder"] = "asc"
+
+ if should_use_incremental_field and db_incremental_field_last_value:
+ params[f"{sort_field}__gte"] = _format_incremental_value(db_incremental_field_last_value)
+
+ return params
+
+
+def _build_initial_url(console_url: str, config: SentinelOneEndpointConfig, params: dict[str, Any]) -> str:
+ url = f"{_base_url(console_url)}{config.path}"
+ if not params:
+ return url
+ return f"{url}?{urlencode(params)}"
+
+
+def _next_page_url(current_url: str, cursor: str) -> str:
+ """Same endpoint + params as the current page, with the ``cursor`` param swapped in.
+
+ SentinelOne's cursor is only valid for the exact query it was minted against, so every
+ non-cursor param must be carried over unchanged.
+ """
+ parsed = urlparse(current_url)
+ params = dict(parse_qsl(parsed.query))
+ params["cursor"] = cursor
+ return parsed._replace(query=urlencode(params)).geturl()
+
+
+def _is_same_host(url: str, console_url: str) -> bool:
+ """Whether ``url`` points at the configured console host.
+
+ Resume URLs come from Redis state; pin them to the validated console host so a
+ poisoned entry can't point the sync at an arbitrary internal address (SSRF).
+ """
+ try:
+ return (urlparse(url).hostname or "").lower() == normalize_console_url(console_url).lower()
+ except Exception:
+ return False
+
+
+def _extract_rows(payload: dict[str, Any], config: SentinelOneEndpointConfig) -> list[dict[str, Any]]:
+ data = payload.get("data")
+ if config.data_key is not None:
+ if isinstance(data, dict) and isinstance(data.get(config.data_key), list):
+ return data[config.data_key]
+ return []
+ return data if isinstance(data, list) else []
+
+
+def _normalize_row(row: dict[str, Any], config: SentinelOneEndpointConfig) -> dict[str, Any]:
+ """Hoist createdAt/updatedAt to the top level where the object nests them.
+
+ Threats keep their timestamps under ``threatInfo``; the pipeline reads the
+ incremental watermark and partition key from top-level columns.
+ """
+ if config.hoist_datetime_fields_from:
+ nested = row.get(config.hoist_datetime_fields_from)
+ if isinstance(nested, dict):
+ for field in ("createdAt", "updatedAt"):
+ if field not in row and nested.get(field) is not None:
+ row[field] = nested[field]
+ return row
+
+
+def _parse_error_message(response: requests.Response) -> str:
+ """SentinelOne errors arrive as ``{"errors": [{"title": ..., "detail": ...}]}``."""
+ try:
+ errors = response.json().get("errors") or []
+ if errors and isinstance(errors[0], dict):
+ title = errors[0].get("title") or ""
+ detail = errors[0].get("detail") or ""
+ message = ": ".join(part for part in (title, detail) if part)
+ if message:
+ return message
+ except Exception:
+ pass
+ return response.text
+
+
+def validate_credentials(
+ console_url: str, api_token: str, schema_name: Optional[str] = None, team_id: Optional[int] = None
+) -> tuple[bool, str | None]:
+ """Probe the console to confirm the API token is genuine.
+
+ At source-create (``schema_name is None``) we hit the cheap ``/system/info`` endpoint
+ and accept 403 — the token is valid but its user's role may lack that view. A scoped
+ probe (``schema_name`` set) hits the endpoint itself and treats 403 as a hard failure.
+ """
+ normalized = normalize_console_url(console_url)
+ if not normalized or not re.match(r"^[A-Za-z0-9.\-]+$", normalized):
+ return False, "Invalid SentinelOne console URL"
+
+ # The console host is fully customer-controlled, so block hosts that resolve to
+ # private/internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.
+ if team_id is not None:
+ host_ok, host_err = _is_host_safe(normalized, team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+
+ endpoint_config = SENTINELONE_ENDPOINTS.get(schema_name) if schema_name else None
+ if endpoint_config is not None:
+ url = f"{_base_url(normalized)}{endpoint_config.path}"
+ params: dict[str, Any] = {"limit": 1}
+ else:
+ url = f"{_base_url(normalized)}/system/info"
+ params = {}
+
+ try:
+ # Don't follow redirects: the validated host could 3xx to an internal address,
+ # defeating the host check above (SSRF).
+ response = make_tracked_session(redact_values=(api_token,), capture=False, allow_redirects=False).get(
+ url, headers=_get_headers(api_token), params=params, timeout=10, allow_redirects=False
+ )
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ if response.is_redirect or response.is_permanent_redirect:
+ return False, HOST_NOT_ALLOWED_ERROR
+
+ if response.status_code == 200:
+ return True, None
+
+ if response.status_code == 401:
+ return False, "Invalid SentinelOne API token"
+
+ if response.status_code == 403:
+ if schema_name is None:
+ # Valid token, missing role/scope for this probe — let source creation through.
+ return True, None
+ return False, "Your SentinelOne API token's user lacks the required permissions for this endpoint"
+
+ return False, _parse_error_message(response)
+
+
+def _parse_retry_after(response: requests.Response) -> float | None:
+ """Honor a whole-seconds ``Retry-After`` on 429. Ignore HTTP-date forms."""
+ raw = response.headers.get("Retry-After")
+ if raw and raw.strip().isdigit():
+ return min(float(raw.strip()), MAX_RETRY_AFTER_SECONDS)
+ return None
+
+
+def _retry_wait(retry_state: RetryCallState) -> float:
+ """Honor a server-provided Retry-After when present, else exponential backoff."""
+ exc = retry_state.outcome.exception() if retry_state.outcome else None
+ if isinstance(exc, SentinelOneRetryableError) and exc.retry_after is not None:
+ return exc.retry_after
+ return wait_exponential_jitter(initial=1, max=30)(retry_state)
+
+
+def get_rows(
+ console_url: str,
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SentinelOneResumeConfig],
+ team_id: int,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[Any]:
+ config = SENTINELONE_ENDPOINTS[endpoint]
+ headers = _get_headers(api_token)
+
+ # Re-check at run time (not just at source-create) in case the console URL was edited
+ # or now resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.
+ host_ok, host_err = _is_host_safe(normalize_console_url(console_url), team_id)
+ if not host_ok:
+ raise SentinelOneHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+ params = _build_initial_params(
+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+
+ initial_url = _build_initial_url(console_url, config, params)
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None and _is_same_host(resume_config.next_url, console_url):
+ url: str = resume_config.next_url
+ logger.debug(f"SentinelOne: resuming from URL: {url}")
+ else:
+ if resume_config is not None:
+ logger.warning("SentinelOne: ignoring resume URL whose host does not match the configured console URL")
+ url = initial_url
+
+ session = make_tracked_session(redact_values=(api_token,), capture=False, allow_redirects=False)
+
+ @retry(
+ retry=retry_if_exception_type((SentinelOneRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=_retry_wait,
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> dict[str, Any]:
+ # Don't follow redirects: an attacker-controlled host could 3xx to an internal
+ # address, bypassing the host validation done before the request (SSRF).
+ response = session.get(page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ retry_after = _parse_retry_after(response) if response.status_code == 429 else None
+ raise SentinelOneRetryableError(
+ f"SentinelOne API error (retryable): status={response.status_code}, url={page_url}",
+ retry_after=retry_after,
+ )
+
+ # A 3xx isn't an error status (`response.ok` is True), so reject it explicitly
+ # rather than silently parsing the redirect body as data.
+ if response.is_redirect or response.is_permanent_redirect:
+ raise SentinelOneHostNotAllowedError(
+ f"SentinelOne API returned an unexpected redirect (status={response.status_code}); refusing to follow it"
+ )
+
+ if not response.ok:
+ logger.error(f"SentinelOne API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ payload = fetch_page(url)
+
+ rows = _extract_rows(payload, config)
+ if not rows:
+ break
+
+ next_cursor = (payload.get("pagination") or {}).get("nextCursor")
+
+ yield [_normalize_row(row, config) for row in rows]
+
+ if not next_cursor:
+ break
+
+ # Save AFTER yielding so a crash re-yields the last page instead of skipping it —
+ # merge dedupes the re-yielded rows on the primary key.
+ next_url = _next_page_url(url, next_cursor)
+ resumable_source_manager.save_state(SentinelOneResumeConfig(next_url=next_url))
+ url = next_url
+
+
+def sentinelone_source(
+ console_url: str,
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SentinelOneResumeConfig],
+ team_id: int,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ endpoint_config = SENTINELONE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ console_url=console_url,
+ api_token=api_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=team_id,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=[endpoint_config.primary_key],
+ # Incremental-capable endpoints request sortBy=<cursor field>&sortOrder=asc, so
+ # ascending order is explicit rather than assumed from the API default.
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="week" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/settings.py
new file mode 100644
index 000000000000..ed6baf1b777c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/settings.py
@@ -0,0 +1,96 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+def _datetime_incremental_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+@dataclass
+class SentinelOneEndpointConfig:
+ name: str
+ path: str
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Field used to build the server-side `<field>__gte` filter when the user hasn't
+ # picked one. Only set on endpoints whose list API documents the filter param.
+ default_incremental_field: Optional[str] = None
+ # Stable, immutable field to partition by. Never updatedAt (it mutates).
+ partition_key: Optional[str] = None
+ primary_key: str = "id"
+ # SentinelOne caps `limit` at 1000 for most list endpoints; endpoints with a
+ # smaller documented cap override this.
+ page_size: int = 1000
+ # Key under which the row list lives in the response `data` value. Most list
+ # endpoints return `data` as a plain list; sites nests it (`data.sites`).
+ data_key: Optional[str] = None
+ # Nested object to hoist createdAt/updatedAt from when they're missing at the
+ # top level (threats keep their timestamps under `threatInfo`).
+ hoist_datetime_fields_from: Optional[str] = None
+
+
+# The stream set mirrors what dedicated SentinelOne collectors (Sumo Logic, Elastic)
+# warehouse: detections, fleet inventory, and the audit/event log, plus the small
+# grouping dimensions (groups, sites) they join against.
+SENTINELONE_ENDPOINTS: dict[str, SentinelOneEndpointConfig] = {
+ "threats": SentinelOneEndpointConfig(
+ name="threats",
+ path="/threats",
+ # Threats expose server-side createdAt__gte and updatedAt__gte filters.
+ # updatedAt is the default cursor so mitigation-status changes are re-synced.
+ incremental_fields=[
+ _datetime_incremental_field("updatedAt"),
+ _datetime_incremental_field("createdAt"),
+ ],
+ default_incremental_field="updatedAt",
+ partition_key="createdAt",
+ hoist_datetime_fields_from="threatInfo",
+ ),
+ "agents": SentinelOneEndpointConfig(
+ name="agents",
+ path="/agents",
+ # Agents expose updatedAt__gte and createdAt__gte; updatedAt is the useful
+ # cursor since endpoint health/inventory fields mutate constantly.
+ incremental_fields=[
+ _datetime_incremental_field("updatedAt"),
+ _datetime_incremental_field("createdAt"),
+ ],
+ default_incremental_field="updatedAt",
+ partition_key="createdAt",
+ ),
+ "activities": SentinelOneEndpointConfig(
+ name="activities",
+ path="/activities",
+ # The activity log is append-only; createdAt__gte is the documented filter.
+ incremental_fields=[_datetime_incremental_field("createdAt")],
+ default_incremental_field="createdAt",
+ partition_key="createdAt",
+ ),
+ # Groups and sites are small dimension tables. Their list APIs document filter
+ # params we couldn't verify against a live tenant, so they stay full refresh.
+ "groups": SentinelOneEndpointConfig(
+ name="groups",
+ path="/groups",
+ partition_key="createdAt",
+ page_size=100, # groups caps `limit` lower than the usual 1000
+ ),
+ "sites": SentinelOneEndpointConfig(
+ name="sites",
+ path="/sites",
+ partition_key="createdAt",
+ page_size=100,
+ data_key="sites", # sites wraps the list: {"data": {"sites": [...]}}
+ ),
+}
+
+ENDPOINTS = tuple(SENTINELONE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in SENTINELONE_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/source.py
index 499cdbdaa579..d45cbdd31fea 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/source.py
@@ -1,30 +1,149 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+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
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SentineloneSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.sentinelone.sentinelone import (
+ HOST_NOT_ALLOWED_ERROR,
+ SentinelOneResumeConfig,
+ sentinelone_source,
+ validate_credentials as validate_sentinelone_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sentinelone.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SentineloneSource(SimpleSource[SentineloneSourceConfig]):
+class SentineloneSource(ResumableSource[SentineloneSourceConfig, SentinelOneResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SENTINELONE
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `console_url` is where the stored API token is sent; retargeting it must re-require the token.
+ return ["console_url"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.SENTINELONE,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="SentinelOne",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your SentinelOne management console URL and an API token to pull your SentinelOne data into the PostHog Data warehouse.
+
+You can generate an API token in your management console under **My User > Actions > API Token Operations**. The token inherits your user's role and scope (account, site, or group), which determines which records sync.
+""",
iconPath="/static/services/sentinelone.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/sentinelone",
+ keywords=["s1", "edr", "endpoint security"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="console_url",
+ label="Console URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="your-tenant.sentinelone.net",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Invalid or expired SentinelOne API token. Please generate a new token in your management console and reconnect.",
+ "403 Client Error": "Your SentinelOne API token's user lacks the required permissions. Please check the user's role and scope and try again.",
+ HOST_NOT_ALLOWED_ERROR: "The SentinelOne console URL is not allowed. Please use your organization's management console URL.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.sentinelone.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: SentineloneSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: SentineloneSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_sentinelone_credentials(config.console_url, config.api_token, schema_name, team_id)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SentinelOneResumeConfig]:
+ return ResumableSourceManager[SentinelOneResumeConfig](inputs, SentinelOneResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SentineloneSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SentinelOneResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return sentinelone_source(
+ console_url=config.console_url,
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=inputs.team_id,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/tests/test_sentinelone.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/tests/test_sentinelone.py
new file mode 100644
index 000000000000..6672b1bcee59
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/tests/test_sentinelone.py
@@ -0,0 +1,422 @@
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.sentinelone import (
+ sentinelone as sentinelone_module,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sentinelone.sentinelone import (
+ SentinelOneResumeConfig,
+ _build_initial_params,
+ _build_initial_url,
+ _extract_rows,
+ _format_incremental_value,
+ _next_page_url,
+ _normalize_row,
+ get_rows,
+ normalize_console_url,
+ sentinelone_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sentinelone.settings import SENTINELONE_ENDPOINTS
+
+
+def _response(
+ *, status_code: int = 200, json_data: Any = None, headers: Optional[dict[str, str]] = None, text: str = ""
+) -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 400
+ response.is_redirect = status_code in (302, 303, 307)
+ response.is_permanent_redirect = status_code in (301, 308)
+ response.text = text
+ response.json.return_value = json_data
+ response.headers = headers or {}
+ return response
+
+
+def _page(rows: list[dict[str, Any]], next_cursor: str | None = None, total: int | None = None) -> dict[str, Any]:
+ return {"data": rows, "pagination": {"nextCursor": next_cursor, "totalItems": total or len(rows)}}
+
+
+class TestNormalizeConsoleUrl:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("usea1-example.sentinelone.net", "usea1-example.sentinelone.net"),
+ ("https://usea1-example.sentinelone.net", "usea1-example.sentinelone.net"),
+ ("http://usea1-example.sentinelone.net/", "usea1-example.sentinelone.net"),
+ (" usea1-example.sentinelone.net ", "usea1-example.sentinelone.net"),
+ ("usea1-example.sentinelone.net/web/api/v2.1", "usea1-example.sentinelone.net"),
+ ("https://usea1-example.sentinelone.net/web/api/v2.1/threats", "usea1-example.sentinelone.net"),
+ ],
+ )
+ def test_normalize(self, raw, expected):
+ assert normalize_console_url(raw) == expected
+
+
+class TestFormatIncrementalValue:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),
+ (datetime(2026, 1, 15, 10, 30, 45, 123456, tzinfo=UTC), "2026-01-15T10:30:45.123Z"),
+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),
+ (date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),
+ ("already-a-cursor", "already-a-cursor"),
+ ],
+ )
+ def test_format(self, value, expected):
+ assert _format_incremental_value(value) == expected
+
+
+class TestBuildInitialParams:
+ def test_incremental_builds_gte_filter_and_matching_sort(self):
+ params = _build_initial_params(
+ SENTINELONE_ENDPOINTS["threats"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ incremental_field="updatedAt",
+ )
+ assert params["updatedAt__gte"] == "2024-01-01T00:00:00.000Z"
+ assert params["sortBy"] == "updatedAt"
+ assert params["sortOrder"] == "asc"
+ assert params["limit"] == 1000
+
+ def test_incremental_honors_user_chosen_field_over_default(self):
+ # threats defaults to updatedAt; a user who picked createdAt must get createdAt__gte.
+ params = _build_initial_params(
+ SENTINELONE_ENDPOINTS["threats"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ incremental_field="createdAt",
+ )
+ assert params["createdAt__gte"] == "2024-01-01T00:00:00.000Z"
+ assert "updatedAt__gte" not in params
+ assert params["sortBy"] == "createdAt"
+
+ def test_incremental_without_watermark_has_no_filter(self):
+ params = _build_initial_params(
+ SENTINELONE_ENDPOINTS["agents"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ incremental_field="updatedAt",
+ )
+ assert "updatedAt__gte" not in params
+ assert params["sortBy"] == "updatedAt"
+
+ def test_full_refresh_sorts_by_stable_field_without_filter(self):
+ params = _build_initial_params(
+ SENTINELONE_ENDPOINTS["threats"],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ incremental_field=None,
+ )
+ assert not any(key.endswith("__gte") for key in params)
+ assert params["sortBy"] == "createdAt"
+ assert params["sortOrder"] == "asc"
+
+ @pytest.mark.parametrize("endpoint", ["groups", "sites"])
+ def test_full_refresh_only_endpoints_send_no_sort_or_filter(self, endpoint):
+ params = _build_initial_params(
+ SENTINELONE_ENDPOINTS[endpoint],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ incremental_field=None,
+ )
+ assert params == {"limit": SENTINELONE_ENDPOINTS[endpoint].page_size}
+
+
+class TestUrlBuilding:
+ def test_initial_url(self):
+ url = _build_initial_url("example.sentinelone.net", SENTINELONE_ENDPOINTS["threats"], {"limit": 1000})
+ assert url == "https://example.sentinelone.net/web/api/v2.1/threats?limit=1000"
+
+ def test_next_page_url_carries_params_and_swaps_cursor(self):
+ # The cursor is only valid for the exact query it was minted against, so the
+ # incremental filter and sort params must survive pagination unchanged.
+ url = "https://example.sentinelone.net/web/api/v2.1/threats?limit=1000&sortBy=updatedAt&updatedAt__gte=2024-01-01T00%3A00%3A00.000Z"
+ next_url = _next_page_url(url, "cur123")
+ query = parse_qs(urlparse(next_url).query)
+ assert query["cursor"] == ["cur123"]
+ assert query["limit"] == ["1000"]
+ assert query["sortBy"] == ["updatedAt"]
+ assert query["updatedAt__gte"] == ["2024-01-01T00:00:00.000Z"]
+
+ def test_next_page_url_replaces_previous_cursor(self):
+ url = "https://example.sentinelone.net/web/api/v2.1/threats?limit=1000&cursor=old"
+ query = parse_qs(urlparse(_next_page_url(url, "new")).query)
+ assert query["cursor"] == ["new"]
+
+
+class TestExtractRows:
+ @pytest.mark.parametrize(
+ "endpoint, payload, expected_ids",
+ [
+ ("threats", {"data": [{"id": "1"}, {"id": "2"}]}, ["1", "2"]),
+ ("sites", {"data": {"sites": [{"id": "3"}], "allSites": {"totalLicenses": 5}}}, ["3"]),
+ ("threats", {"data": None}, []),
+ ("threats", {}, []),
+ ("sites", {"data": []}, []),
+ ("sites", {"data": {"allSites": {}}}, []),
+ ],
+ )
+ def test_extract(self, endpoint, payload, expected_ids):
+ rows = _extract_rows(payload, SENTINELONE_ENDPOINTS[endpoint])
+ assert [r["id"] for r in rows] == expected_ids
+
+
+class TestNormalizeRow:
+ def test_hoists_threat_info_timestamps(self):
+ row = {"id": "t1", "threatInfo": {"createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-02T00:00:00Z"}}
+ normalized = _normalize_row(row, SENTINELONE_ENDPOINTS["threats"])
+ assert normalized["createdAt"] == "2024-01-01T00:00:00Z"
+ assert normalized["updatedAt"] == "2024-01-02T00:00:00Z"
+
+ def test_does_not_overwrite_existing_top_level_fields(self):
+ row = {"id": "t1", "createdAt": "top", "threatInfo": {"createdAt": "nested"}}
+ assert _normalize_row(row, SENTINELONE_ENDPOINTS["threats"])["createdAt"] == "top"
+
+ def test_no_hoist_for_endpoints_without_nested_timestamps(self):
+ row = {"id": "a1", "createdAt": "2024-01-01T00:00:00Z"}
+ assert _normalize_row(row, SENTINELONE_ENDPOINTS["agents"]) == row
+
+
+class TestValidateCredentials:
+ def _patch_session(self, response=None, raises=None):
+ session = mock.MagicMock()
+ if raises is not None:
+ session.get.side_effect = raises
+ else:
+ session.get.return_value = response
+ return mock.patch.object(sentinelone_module, "make_tracked_session", return_value=session)
+
+ def test_success(self):
+ with self._patch_session(_response(status_code=200)):
+ assert validate_credentials("example.sentinelone.net", "tok") == (True, None)
+
+ def test_invalid_token(self):
+ with self._patch_session(_response(status_code=401)):
+ valid, msg = validate_credentials("example.sentinelone.net", "tok")
+ assert valid is False
+ assert msg == "Invalid SentinelOne API token"
+
+ def test_403_at_source_create_is_accepted(self):
+ with self._patch_session(_response(status_code=403)):
+ assert validate_credentials("example.sentinelone.net", "tok", schema_name=None) == (True, None)
+
+ def test_403_for_scoped_probe_fails(self):
+ with self._patch_session(_response(status_code=403)):
+ valid, msg = validate_credentials("example.sentinelone.net", "tok", schema_name="threats")
+ assert valid is False
+ assert msg is not None
+
+ def test_scoped_probe_hits_the_endpoint_path(self):
+ with self._patch_session(_response(status_code=200)) as patched:
+ validate_credentials("example.sentinelone.net", "tok", schema_name="threats")
+ url = patched.return_value.get.call_args.args[0]
+ assert url == "https://example.sentinelone.net/web/api/v2.1/threats"
+ assert patched.return_value.get.call_args.kwargs["params"] == {"limit": 1}
+
+ def test_create_probe_hits_system_info(self):
+ with self._patch_session(_response(status_code=200)) as patched:
+ validate_credentials("example.sentinelone.net", "tok")
+ url = patched.return_value.get.call_args.args[0]
+ assert url == "https://example.sentinelone.net/web/api/v2.1/system/info"
+
+ @pytest.mark.parametrize("bad_url", ["", "not a url!", "https://"])
+ def test_invalid_console_url_short_circuits(self, bad_url):
+ valid, msg = validate_credentials(bad_url, "tok")
+ assert valid is False
+ assert msg == "Invalid SentinelOne console URL"
+
+ def test_request_exception_returns_failure(self):
+ import requests
+
+ with self._patch_session(raises=requests.exceptions.ConnectionError("boom")):
+ valid, msg = validate_credentials("example.sentinelone.net", "tok")
+ assert valid is False
+ assert "boom" in (msg or "")
+
+ def test_rejects_redirect_response(self):
+ # A validated host that 3xx-redirects (potentially to an internal address) must be
+ # rejected, not followed (SSRF).
+ with self._patch_session(_response(status_code=302)) as patched:
+ valid, msg = validate_credentials("example.sentinelone.net", "tok")
+ assert valid is False
+ assert msg == sentinelone_module.HOST_NOT_ALLOWED_ERROR
+ assert patched.return_value.get.call_args.kwargs["allow_redirects"] is False
+
+ def test_blocks_unsafe_host(self):
+ with (
+ mock.patch.object(sentinelone_module, "_is_host_safe", return_value=(False, "internal address")),
+ self._patch_session(_response(status_code=200)) as patched,
+ ):
+ valid, msg = validate_credentials("10.0.0.1", "tok", team_id=99)
+ assert valid is False
+ assert msg == "internal address"
+ patched.return_value.get.assert_not_called()
+
+ def test_error_body_is_surfaced(self):
+ body = {"errors": [{"title": "Bad request", "detail": "invalid filter"}]}
+ with self._patch_session(_response(status_code=400, json_data=body)):
+ valid, msg = validate_credentials("example.sentinelone.net", "tok")
+ assert valid is False
+ assert msg == "Bad request: invalid filter"
+
+
+class TestSentinelOneSourceResponse:
+ @pytest.mark.parametrize(
+ "endpoint, primary_key, partition_key",
+ [
+ ("threats", "id", "createdAt"),
+ ("agents", "id", "createdAt"),
+ ("activities", "id", "createdAt"),
+ ("groups", "id", "createdAt"),
+ ("sites", "id", "createdAt"),
+ ],
+ )
+ def test_response_shape(self, endpoint, primary_key, partition_key):
+ response = sentinelone_source(
+ console_url="example.sentinelone.net",
+ api_token="tok",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=mock.MagicMock(),
+ team_id=1,
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == [primary_key]
+ assert response.sort_mode == "asc"
+ assert response.partition_keys == [partition_key]
+ assert response.partition_mode == "datetime"
+
+
+class TestGetRows:
+ def _run(self, manager, responses, endpoint="threats"):
+ session = mock.MagicMock()
+ session.get.side_effect = responses
+ with mock.patch.object(sentinelone_module, "make_tracked_session", return_value=session):
+ rows: list[Any] = []
+ for batch in get_rows(
+ console_url="example.sentinelone.net",
+ api_token="tok",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ team_id=1,
+ ):
+ rows.extend(batch)
+ return rows, session
+
+ def test_follows_cursor_across_pages(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ page1 = _response(json_data=_page([{"id": "1"}, {"id": "2"}], next_cursor="cur"))
+ page2 = _response(json_data=_page([{"id": "3"}]))
+ rows, session = self._run(manager, [page1, page2])
+
+ assert [r["id"] for r in rows] == ["1", "2", "3"]
+ second_url = session.get.call_args_list[1].args[0]
+ query = parse_qs(urlparse(second_url).query)
+ assert query["cursor"] == ["cur"]
+ # Non-cursor params must be carried over — the cursor is bound to them.
+ assert query["limit"] == ["1000"]
+
+ def test_saves_state_after_yield_only_when_more_pages(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ last_page = _response(json_data=_page([{"id": "1"}]))
+ self._run(manager, [last_page])
+ manager.save_state.assert_not_called()
+
+ manager2 = mock.MagicMock()
+ manager2.can_resume.return_value = False
+ page1 = _response(json_data=_page([{"id": "1"}], next_cursor="cur"))
+ page2 = _response(json_data=_page([{"id": "2"}]))
+ self._run(manager2, [page1, page2])
+ saved = manager2.save_state.call_args.args[0]
+ assert isinstance(saved, SentinelOneResumeConfig)
+ assert "cursor=cur" in saved.next_url
+
+ def test_resumes_from_saved_state(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SentinelOneResumeConfig(
+ next_url="https://example.sentinelone.net/web/api/v2.1/threats?limit=1000&cursor=resume"
+ )
+ rows, session = self._run(manager, [_response(json_data=_page([{"id": "9"}]))])
+
+ first_url = session.get.call_args_list[0].args[0]
+ assert "cursor=resume" in first_url
+ assert [r["id"] for r in rows] == ["9"]
+
+ def test_ignores_resume_url_on_foreign_host(self):
+ # A poisoned resume URL must fall back to the initial console URL, not be followed.
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SentinelOneResumeConfig(next_url="http://169.254.169.254/latest/meta-data/")
+ rows, session = self._run(manager, [_response(json_data=_page([{"id": "1"}]))])
+
+ first_url = session.get.call_args_list[0].args[0]
+ assert first_url.startswith("https://example.sentinelone.net/web/api/v2.1/threats")
+ assert [r["id"] for r in rows] == ["1"]
+
+ def test_empty_page_terminates(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ rows, session = self._run(manager, [_response(json_data=_page([], next_cursor="cur"))])
+ assert rows == []
+ assert session.get.call_count == 1
+
+ def test_sites_rows_come_from_nested_data_key(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ payload = {"data": {"sites": [{"id": "s1"}], "allSites": {}}, "pagination": {"nextCursor": None}}
+ rows, _session = self._run(manager, [_response(json_data=payload)], endpoint="sites")
+ assert [r["id"] for r in rows] == ["s1"]
+
+ def test_threat_rows_are_normalized(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ payload = _page([{"id": "t1", "threatInfo": {"createdAt": "2024-01-01T00:00:00Z"}}])
+ rows, _session = self._run(manager, [_response(json_data=payload)])
+ assert rows[0]["createdAt"] == "2024-01-01T00:00:00Z"
+
+ def test_redirect_response_raises(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ with pytest.raises(sentinelone_module.SentinelOneHostNotAllowedError):
+ self._run(manager, [_response(status_code=302)])
+
+ def test_passes_allow_redirects_false(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ _rows, session = self._run(manager, [_response(json_data=_page([{"id": "1"}]))])
+ assert session.get.call_args.kwargs["allow_redirects"] is False
+
+
+class TestRetryAfter:
+ @pytest.mark.parametrize(
+ "header, expected",
+ [
+ ({"Retry-After": "5"}, 5.0),
+ ({"Retry-After": "100000"}, 60.0), # capped
+ ({"Retry-After": "Wed, 21 Oct 2026 07:28:00 GMT"}, None), # HTTP-date ignored
+ ({}, None),
+ ],
+ )
+ def test_parse_retry_after(self, header, expected):
+ response = mock.MagicMock()
+ response.headers = header
+ assert sentinelone_module._parse_retry_after(response) == expected
+
+ def test_retry_wait_prefers_retry_after(self):
+ state = mock.MagicMock()
+ state.outcome.exception.return_value = sentinelone_module.SentinelOneRetryableError(
+ "rate limited", retry_after=7.0
+ )
+ assert sentinelone_module._retry_wait(state) == 7.0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/tests/test_sentinelone_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/tests/test_sentinelone_source.py
new file mode 100644
index 000000000000..b9bc895ad308
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentinelone/tests/test_sentinelone_source.py
@@ -0,0 +1,140 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SentineloneSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.sentinelone.sentinelone import (
+ SentinelOneResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sentinelone.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.sentinelone.source import SentineloneSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestSentineloneSource:
+ def setup_method(self):
+ self.source = SentineloneSource()
+ self.team_id = 123
+ self.config = SentineloneSourceConfig(console_url="example.sentinelone.net", api_token="tok")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.SENTINELONE
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Sentinelone"
+ assert config.label == "SentinelOne"
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/sentinelone.png"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["console_url", "api_token"]
+
+ console_field, token_field = config.fields
+ assert isinstance(console_field, SourceFieldInputConfig)
+ assert console_field.type == SourceFieldInputConfigType.TEXT
+ assert console_field.secret is False
+
+ assert isinstance(token_field, SourceFieldInputConfig)
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.secret is True
+ assert token_field.required is True
+
+ def test_console_url_is_a_connection_host_field(self):
+ # Retargeting the console URL must force re-entry of the API token — otherwise a
+ # member could point the stored token at a server they control.
+ assert self.source.connection_host_fields == ["console_url"]
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_returns_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "endpoint, incremental",
+ [
+ ("threats", True),
+ ("agents", True),
+ ("activities", True),
+ ("groups", False),
+ ("sites", False),
+ ],
+ )
+ def test_schema_incremental_support(self, endpoint, incremental):
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas[endpoint].supports_incremental is incremental
+ assert schemas[endpoint].supports_append is incremental
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["threats"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "threats"
+
+ @pytest.mark.parametrize(
+ "mock_return",
+ [
+ (True, None),
+ (False, "Invalid SentinelOne API token"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.sentinelone.source.validate_sentinelone_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return):
+ mock_validate.return_value = mock_return
+
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="threats")
+
+ assert result == mock_return
+ mock_validate.assert_called_once_with(self.config.console_url, self.config.api_token, "threats", self.team_id)
+
+ def test_get_resumable_source_manager(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is SentinelOneResumeConfig
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.sentinelone.source.sentinelone_source"
+ )
+ def test_source_for_pipeline_plumbs_arguments(self, mock_sentinelone_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "threats"
+ inputs.team_id = 42
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00.000Z"
+ inputs.incremental_field = "updatedAt"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_sentinelone_source.call_args.kwargs
+ assert kwargs["console_url"] == "example.sentinelone.net"
+ assert kwargs["api_token"] == "tok"
+ assert kwargs["endpoint"] == "threats"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["team_id"] == 42
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00.000Z"
+ assert kwargs["incremental_field"] == "updatedAt"
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.sentinelone.source.sentinelone_source"
+ )
+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self, mock_sentinelone_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "groups"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "ignored"
+ inputs.incremental_field = None
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_sentinelone_source.call_args.kwargs["db_incremental_field_last_value"] is None