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 rapid7_insightvm import source (#71148)

Tom Owers112a64b82449
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 b58aa3698e7d..0b511a55f9bc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -364,6 +364,7 @@ the row lists both.
| qualaroo | HTTP | requests | ✅ |
| recurly | HTTP | requests + `rest_source.RESTClient` | ✅ |
| ramp | HTTP | requests | ✅ |
+| rapid7_insightvm | HTTP | requests | ✅ |
| recharge | HTTP | requests | ✅ |
| recruitee | HTTP | requests | ✅ |
| reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -824,7 +825,6 @@ doesn't conflict with concurrent PRs.
- quickbooks
- railway
- railz
-- rapid7_insightvm
- raygun
- razorpay
- rb2b
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 3b0b1e771b0b..2b3165a6b2f4 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
@@ -3401,7 +3401,8 @@ class RampSourceConfig(config.Config):
@config.config
class Rapid7InsightvmSourceConfig(config.Config):
- pass
+ api_key: str
+ region: Literal["us", "eu", "ca", "au", "ap", "jp"] = config.value(default="us")
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/canonical_descriptions.py
new file mode 100644
index 000000000000..c9729586bd00
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/canonical_descriptions.py
@@ -0,0 +1,49 @@
+"""Canonical, documentation-sourced descriptions for Rapid7 InsightVM endpoints and columns.
+
+Sourced from the Rapid7 InsightVM Cloud Integrations API (v4) reference
+(https://help.rapid7.com/insightvm/en-us/api/integrations.html). Keyed by the endpoint names in
+`settings.py` `RAPID7_INSIGHTVM_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced
+table. Column coverage is intentionally partial (the v4 objects are deeply nested); anything absent
+here falls back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "assets": {
+ "description": "A scanned asset (host) in InsightVM, with its network identity, operating system, "
+ "risk score, tags, and the vulnerability findings detected on it.",
+ "docs_url": "https://help.rapid7.com/insightvm/en-us/api/integrations.html",
+ "columns": {
+ "id": "Unique identifier for the asset.",
+ "host_name": "Primary hostname of the asset.",
+ "ip": "IP address of the asset.",
+ "mac": "MAC address of the asset, when known.",
+ "os": "Operating system detected on the asset.",
+ "risk_score": "InsightVM risk score for the asset.",
+ "tags": "Tags applied to the asset (site, location, owner, or custom tags).",
+ "last_scan_time": "Timestamp of the most recent scan of the asset.",
+ "vulnerabilities": "Vulnerability findings detected on the asset (status, proof, port, protocol, first/last found).",
+ },
+ },
+ "vulnerabilities": {
+ "description": "A unique vulnerability definition in InsightVM, with severity, CVSS scoring, "
+ "CVE mappings, exploit and malware-kit indicators, and remediation references.",
+ "docs_url": "https://help.rapid7.com/insightvm/en-us/api/integrations.html",
+ "columns": {
+ "id": "Unique identifier for the vulnerability definition.",
+ "title": "Human-readable title of the vulnerability.",
+ "description": "Detailed description of the vulnerability.",
+ "severity": "Severity classification (e.g. Critical, Severe, Moderate).",
+ "cvss_v2_score": "CVSS v2 base score.",
+ "cvss_v3_score": "CVSS v3 base score.",
+ "cves": "CVE identifiers associated with the vulnerability.",
+ "published": "Date the vulnerability was published.",
+ "added": "Date the vulnerability was added to InsightVM's content.",
+ "exploits": "Known exploits associated with the vulnerability.",
+ "malware_kits": "Known malware kits that leverage the vulnerability.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/rapid7_insightvm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/rapid7_insightvm.py
new file mode 100644
index 000000000000..12dd34deea71
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/rapid7_insightvm.py
@@ -0,0 +1,173 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import 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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.rapid7_insightvm.settings import (
+ API_BASE_PATH,
+ MAX_PAGE_SIZE,
+ RAPID7_INSIGHTVM_ENDPOINTS,
+ REGION_HOSTS,
+)
+
+REQUEST_TIMEOUT_SECONDS = 120
+RETRY_MAX_ATTEMPTS = 5
+
+
+class Rapid7InsightvmRetryableError(Exception):
+ pass
+
+
+class Rapid7InsightvmResumeConfig:
+ # Opaque cursor token returned in the previous page's `metadata.cursor`. `None` starts the
+ # endpoint from its first page.
+ cursor: str | None = None
+
+
+def _host(region: str) -> str:
+ return REGION_HOSTS.get(region, REGION_HOSTS["us"])
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {
+ "X-Api-Key": api_key,
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ }
+
+
+def _endpoint_url(region: str, path: str) -> str:
+ return f"{_host(region)}{API_BASE_PATH}/{path}"
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ Rapid7InsightvmRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(RETRY_MAX_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict:
+ # v4 search endpoints are POST operations; an empty JSON body returns all resources.
+ full_url = f"{url}?{urlencode(params)}" if params else url
+ response = session.post(full_url, headers=headers, json={}, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise Rapid7InsightvmRetryableError(
+ f"Rapid7 InsightVM API error (retryable): status={response.status_code}, url={url}"
+ )
+
+ if not response.ok:
+ logger.error(f"Rapid7 InsightVM API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def get_rows(
+ api_key: str,
+ region: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[Rapid7InsightvmResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = RAPID7_INSIGHTVM_ENDPOINTS[endpoint]
+ headers = _headers(api_key)
+ # One session reused across every page so urllib3 keeps the connection alive.
+ # `allow_redirects=False` keeps the credentialed `X-Api-Key` from being replayed to a
+ # redirect target; `redact_values` masks the key in logged URLs and captured samples.
+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)
+ url = _endpoint_url(region, config.path)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ cursor = resume.cursor if resume else None
+
+ while True:
+ params: dict[str, Any] = {"size": MAX_PAGE_SIZE}
+ if cursor:
+ params["cursor"] = cursor
+
+ data = _fetch_page(session, url, headers, params, logger)
+
+ items = data.get("data", [])
+ if items:
+ yield items
+
+ metadata = data.get("metadata", {})
+ next_cursor = metadata.get("cursor")
+
+ # Cursored pagination terminates when the API stops handing back a fresh cursor: a missing
+ # cursor, an unchanged cursor (some deployments echo the last token), or an empty page.
+ if not items or not next_cursor or next_cursor == cursor:
+ break
+
+ cursor = next_cursor
+ # Save state AFTER yielding the batch so a crash re-yields the last page (merge dedupes on
+ # the primary key) rather than skipping it.
+ resumable_source_manager.save_state(Rapid7InsightvmResumeConfig(cursor=cursor))
+
+
+def validate_credentials(api_key: str, region: str) -> tuple[bool, Optional[str]]:
+ # Probe the assets search endpoint with the smallest possible page. A valid key returns 200;
+ # an invalid or expired key returns 401/403.
+ url = _endpoint_url(region, RAPID7_INSIGHTVM_ENDPOINTS["assets"].path)
+ try:
+ response = make_tracked_session(redact_values=(api_key,), allow_redirects=False).post(
+ f"{url}?{urlencode({'size': 1})}",
+ headers=_headers(api_key),
+ json={},
+ timeout=30,
+ )
+ except Exception as e:
+ return False, f"Could not reach Rapid7 InsightVM ({e}). Please check your network and selected region."
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (401, 403):
+ return False, "Rapid7 InsightVM rejected the API key. Check the key and selected region, then reconnect."
+ return False, f"Rapid7 InsightVM returned an unexpected status ({response.status_code})."
+
+
+def rapid7_insightvm_source(
+ api_key: str,
+ region: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[Rapid7InsightvmResumeConfig],
+) -> SourceResponse:
+ endpoint_config = RAPID7_INSIGHTVM_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ region=region,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ 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/rapid7_insightvm/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/settings.py
new file mode 100644
index 000000000000..ff77173428f9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/settings.py
@@ -0,0 +1,62 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+# InsightVM's Insight Platform Cloud API is deployed per data-residency region. A single API key
+# belongs to one region, so the host is chosen by the `region` form field rather than a
+# user-supplied URL — the set is fixed, so there is no SSRF surface.
+REGION_HOSTS: dict[str, str] = {
+ "us": "https://us.api.insight.rapid7.com",
+ "eu": "https://eu.api.insight.rapid7.com",
+ "ca": "https://ca.api.insight.rapid7.com",
+ "au": "https://au.api.insight.rapid7.com",
+ "ap": "https://ap.api.insight.rapid7.com",
+ "jp": "https://jp.api.insight.rapid7.com",
+}
+
+# The Cloud Integrations API (v4) exposes purpose-built bulk-export search endpoints. They are
+# POST search operations that page with a `size` query param (max 1000) and a `cursor` token
+# returned in the response metadata.
+API_BASE_PATH = "/vm/v4/integration"
+MAX_PAGE_SIZE = 1000
+
+
+@dataclass
+class Rapid7InsightvmEndpointConfig:
+ name: str
+ # Path segment appended to `{host}{API_BASE_PATH}/` (e.g. "assets").
+ path: str
+ primary_keys: list[str]
+ # Incremental sync is only advertised where the API exposes a confirmed server-side timestamp
+ # filter. The v4 search body accepts filter expressions but their timestamp-filter fidelity is
+ # unverified, so both endpoints ship full refresh only.
+ supports_incremental: bool = False
+ supports_append: bool = False
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Must be a STABLE datetime field (never `updated_at`/`last_seen`) so partitions don't rewrite
+ # every sync. Left unset: the v4 objects have no field confirmed stable across scans, so we
+ # don't partition rather than partition on a field that might be revised.
+ partition_key: str | None = None
+
+
+RAPID7_INSIGHTVM_ENDPOINTS: dict[str, Rapid7InsightvmEndpointConfig] = {
+ # Asset inventory with embedded vulnerability findings and solutions. Purpose-built for bulk
+ # export — the whole host record comes back in one response.
+ "assets": Rapid7InsightvmEndpointConfig(
+ name="assets",
+ path="assets",
+ primary_keys=["id"],
+ ),
+ # Unique vulnerability definitions with CVE mappings, CVSS scores, severity, and references.
+ "vulnerabilities": Rapid7InsightvmEndpointConfig(
+ name="vulnerabilities",
+ path="vulnerabilities",
+ primary_keys=["id"],
+ ),
+}
+
+ENDPOINTS = tuple(RAPID7_INSIGHTVM_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in RAPID7_INSIGHTVM_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/source.py
index b027aced3e9c..cb098e060d5f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/source.py
@@ -1,32 +1,155 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-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 (
Rapid7InsightvmSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rapid7_insightvm.rapid7_insightvm import (
+ Rapid7InsightvmResumeConfig,
+ rapid7_insightvm_source,
+ validate_credentials as validate_rapid7_insightvm_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rapid7_insightvm.settings import (
+ INCREMENTAL_FIELDS,
+ RAPID7_INSIGHTVM_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class Rapid7InsightvmSource(SimpleSource[Rapid7InsightvmSourceConfig]):
+class Rapid7InsightvmSource(ResumableSource[Rapid7InsightvmSourceConfig, Rapid7InsightvmResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.RAPID7INSIGHTVM
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.rapid7_insightvm.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ message = (
+ "Rapid7 InsightVM rejected the API key. Generate a new Insight Platform key "
+ "(Settings → API Keys at insight.rapid7.com), confirm the selected region, then reconnect."
+ )
+ return {
+ "401 Client Error: Unauthorized": message,
+ "403 Client Error: Forbidden": message,
+ }
+
+ def get_schemas(
+ self,
+ config: Rapid7InsightvmSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint.name,
+ supports_incremental=endpoint.supports_incremental,
+ supports_append=endpoint.supports_append,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint.name, []),
+ )
+ for endpoint in RAPID7_INSIGHTVM_ENDPOINTS.values()
+ ]
+
+ 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: Rapid7InsightvmSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_rapid7_insightvm_credentials(config.api_key, config.region)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[Rapid7InsightvmResumeConfig]:
+ return ResumableSourceManager[Rapid7InsightvmResumeConfig](inputs, Rapid7InsightvmResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: Rapid7InsightvmSourceConfig,
+ resumable_source_manager: ResumableSourceManager[Rapid7InsightvmResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return rapid7_insightvm_source(
+ api_key=config.api_key,
+ region=config.region,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.RAPID7_INSIGHTVM,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Rapid7 InsightVM",
+ caption=(
+ "Connect Rapid7 InsightVM with an **Insight Platform API key** to pull your asset inventory "
+ "and vulnerability findings into the PostHog Data warehouse.\n\n"
+ "Generate a key under **Settings → API Keys** at [insight.rapid7.com](https://insight.rapid7.com), "
+ "then pick the **region** your Insight Platform account lives in (the first part of your product "
+ "URL, e.g. `us` in `us.idr.insight.rapid7.com`).\n\n"
+ "Requires a paid InsightVM Cloud (Insight Platform) subscription."
+ ),
+ docsUrl="https://posthog.com/docs/cdp/sources/rapid7-insightvm",
iconPath="/static/services/rapid7_insightvm.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue="us",
+ options=[
+ SourceFieldSelectConfigOption(label="United States (us)", value="us"),
+ SourceFieldSelectConfigOption(label="Europe (eu)", value="eu"),
+ SourceFieldSelectConfigOption(label="Canada (ca)", value="ca"),
+ SourceFieldSelectConfigOption(label="Australia (au)", value="au"),
+ SourceFieldSelectConfigOption(label="Asia Pacific (ap)", value="ap"),
+ SourceFieldSelectConfigOption(label="Japan (jp)", value="jp"),
+ ],
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/tests/test_rapid7_insightvm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/tests/test_rapid7_insightvm.py
new file mode 100644
index 000000000000..a3b1da33cd33
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/tests/test_rapid7_insightvm.py
@@ -0,0 +1,203 @@
+from typing import Any, cast
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.rapid7_insightvm import rapid7_insightvm
+from products.warehouse_sources.backend.temporal.data_imports.sources.rapid7_insightvm.rapid7_insightvm import (
+ Rapid7InsightvmResumeConfig,
+ get_rows,
+ rapid7_insightvm_source,
+ validate_credentials,
+)
+
+TRANSPORT = "products.warehouse_sources.backend.temporal.data_imports.sources.rapid7_insightvm.rapid7_insightvm"
+
+
+class FakeManager:
+ """In-memory stand-in for ResumableSourceManager that records saved cursors."""
+
+ def __init__(self, initial: Rapid7InsightvmResumeConfig | None = None):
+ self._state = initial
+ self.saved: list[Rapid7InsightvmResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> Rapid7InsightvmResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: Rapid7InsightvmResumeConfig) -> None:
+ self.saved.append(data)
+ self._state = data
+
+
+def _response(status: int, body: dict[str, Any]) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status
+ resp.ok = 200 <= status < 300
+ resp.json.return_value = body
+ resp.text = str(body)
+ if not resp.ok:
+ resp.raise_for_status.side_effect = requests.HTTPError(f"{status} error", response=resp)
+ return resp
+
+
+def _page(items: list[dict], cursor: str | None) -> dict[str, Any]:
+ return {"data": items, "metadata": {"cursor": cursor} if cursor is not None else {}}
+
+
+class TestGetRowsPagination:
+ def _run(self, pages: list[dict], manager: FakeManager) -> tuple[list, mock.MagicMock]:
+ session = mock.MagicMock()
+ session.post.side_effect = [_response(200, page) for page in pages]
+ with mock.patch(f"{TRANSPORT}.make_tracked_session", return_value=session):
+ batches = list(
+ get_rows(
+ api_key="key",
+ region="us",
+ endpoint="assets",
+ logger=mock.MagicMock(),
+ resumable_source_manager=cast(ResumableSourceManager[Rapid7InsightvmResumeConfig], manager),
+ )
+ )
+ return batches, session
+
+ def test_walks_pages_until_cursor_missing(self):
+ pages = [
+ _page([{"id": 1}], cursor="c1"),
+ _page([{"id": 2}], cursor="c2"),
+ _page([{"id": 3}], cursor=None),
+ ]
+ manager = FakeManager()
+ batches, session = self._run(pages, manager)
+
+ assert [item["id"] for batch in batches for item in batch] == [1, 2, 3]
+ assert session.post.call_count == 3
+
+ def test_terminates_when_cursor_repeats(self):
+ # Some deployments echo the last cursor instead of dropping it; a naive loop would spin forever.
+ pages = [_page([{"id": 1}], cursor="c1"), _page([{"id": 2}], cursor="c1")]
+ manager = FakeManager()
+ batches, session = self._run(pages, manager)
+
+ assert [item["id"] for batch in batches for item in batch] == [1, 2]
+ assert session.post.call_count == 2
+
+ def test_terminates_on_empty_page(self):
+ pages = [_page([], cursor="c1")]
+ manager = FakeManager()
+ batches, session = self._run(pages, manager)
+
+ assert batches == []
+ assert session.post.call_count == 1
+
+ def test_saves_cursor_after_each_yielded_batch(self):
+ pages = [
+ _page([{"id": 1}], cursor="c1"),
+ _page([{"id": 2}], cursor="c2"),
+ _page([{"id": 3}], cursor=None),
+ ]
+ manager = FakeManager()
+ self._run(pages, manager)
+
+ # State is persisted only for pages that have a successor cursor (c1, c2); the final page
+ # (no next cursor) saves nothing, so a resumed run re-yields the last page rather than skipping.
+ assert [state.cursor for state in manager.saved] == ["c1", "c2"]
+
+ def test_resumes_from_saved_cursor(self):
+ pages = [_page([{"id": 99}], cursor=None)]
+ manager = FakeManager(initial=Rapid7InsightvmResumeConfig(cursor="saved-cursor"))
+ _, session = self._run(pages, manager)
+
+ # The first (and only) request must carry the saved cursor as its starting point.
+ first_call_url = session.post.call_args_list[0].args[0]
+ assert "cursor=saved-cursor" in first_call_url
+
+
+class TestFetchPageRetries:
+ @pytest.mark.parametrize("status", [429, 500, 503])
+ def test_retryable_statuses_raise_retryable_error(self, status):
+ session = mock.MagicMock()
+ session.post.return_value = _response(status, {})
+ with pytest.raises(rapid7_insightvm.Rapid7InsightvmRetryableError):
+ rapid7_insightvm._fetch_page(
+ session, "https://us.api.insight.rapid7.com/vm/v4/integration/assets", {}, {}, mock.MagicMock()
+ )
+
+ def test_client_error_raises_http_error(self):
+ session = mock.MagicMock()
+ session.post.return_value = _response(403, {})
+ with pytest.raises(requests.HTTPError):
+ rapid7_insightvm._fetch_page(
+ session, "https://us.api.insight.rapid7.com/vm/v4/integration/assets", {}, {}, mock.MagicMock()
+ )
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status, expected_valid",
+ [(200, True), (401, False), (403, False), (500, False)],
+ )
+ def test_status_maps_to_validity(self, status, expected_valid):
+ session = mock.MagicMock()
+ session.post.return_value = _response(status, {})
+ with mock.patch(f"{TRANSPORT}.make_tracked_session", return_value=session):
+ is_valid, message = validate_credentials("key", "us")
+
+ assert is_valid is expected_valid
+ assert (message is None) is expected_valid
+
+ def test_network_error_is_not_valid(self):
+ session = mock.MagicMock()
+ session.post.side_effect = requests.ConnectionError("boom")
+ with mock.patch(f"{TRANSPORT}.make_tracked_session", return_value=session):
+ is_valid, message = validate_credentials("key", "us")
+
+ assert is_valid is False
+ assert message is not None
+
+
+class TestCredentialedSessionIsHardened:
+ # A 3xx from the credentialed Rapid7 endpoint would otherwise replay `X-Api-Key` to the
+ # redirect target, so both entry points must pin redirects off and redact the key.
+ def _get_rows(self) -> None:
+ list(
+ get_rows(
+ api_key="secret-key",
+ region="us",
+ endpoint="assets",
+ logger=mock.MagicMock(),
+ resumable_source_manager=cast(ResumableSourceManager[Rapid7InsightvmResumeConfig], FakeManager()),
+ )
+ )
+
+ def _validate(self) -> None:
+ validate_credentials("secret-key", "us")
+
+ @pytest.mark.parametrize("entry_point", ["_get_rows", "_validate"])
+ def test_session_pins_redirects_off_and_redacts_key(self, entry_point):
+ session = mock.MagicMock()
+ session.post.return_value = _response(200, _page([], cursor=None))
+ with mock.patch(f"{TRANSPORT}.make_tracked_session", return_value=session) as factory:
+ getattr(self, entry_point)()
+
+ factory.assert_called_once_with(redact_values=("secret-key",), allow_redirects=False)
+
+
+class TestSourceResponse:
+ @pytest.mark.parametrize("endpoint", ["assets", "vulnerabilities"])
+ def test_full_refresh_endpoints_have_no_partitioning(self, endpoint):
+ response = rapid7_insightvm_source(
+ api_key="key",
+ region="us",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=mock.MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ assert response.partition_mode is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/tests/test_rapid7_insightvm_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/tests/test_rapid7_insightvm_source.py
new file mode 100644
index 000000000000..f2a661fafa12
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rapid7_insightvm/tests/test_rapid7_insightvm_source.py
@@ -0,0 +1,103 @@
+from types import SimpleNamespace
+from typing import cast
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+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 (
+ Rapid7InsightvmSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rapid7_insightvm.rapid7_insightvm import (
+ Rapid7InsightvmResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rapid7_insightvm.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.rapid7_insightvm.source import (
+ Rapid7InsightvmSource,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+SOURCE = "products.warehouse_sources.backend.temporal.data_imports.sources.rapid7_insightvm.source"
+
+
+class TestRapid7InsightvmSource:
+ def setup_method(self):
+ self.source = Rapid7InsightvmSource()
+ self.team_id = 123
+ self.config = Rapid7InsightvmSourceConfig(api_key="key", region="us")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.RAPID7INSIGHTVM
+
+ def test_get_source_config_is_released_alpha(self):
+ config = self.source.get_source_config
+ # Guards against the scaffold's `unreleasedSource=True` (which hides the connector entirely)
+ # regressing back in — a finished source must be visible.
+ assert not config.unreleasedSource
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ def test_get_source_config_fields(self):
+ fields = self.source.get_source_config.fields
+
+ api_key_field = fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+
+ region_field = fields[1]
+ assert isinstance(region_field, SourceFieldSelectConfig)
+ assert region_field.name == "region"
+ assert region_field.defaultValue == "us"
+ assert {option.value for option in region_field.options} == {"us", "eu", "ca", "au", "ap", "jp"}
+
+ def test_lists_tables_without_credentials(self):
+ # Static endpoint catalog with no I/O — must opt in so the public docs render the table list.
+ assert self.source.lists_tables_without_credentials is True
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error: Unauthorized", "403 Client Error: Forbidden"])
+ def test_non_retryable_errors_include_auth(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_returns_every_endpoint_as_full_refresh(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ # No endpoint advertises incremental — the v4 timestamp filter is unverified, so all ship full refresh.
+ assert all(not schema.supports_incremental for schema in schemas)
+ assert all(not schema.supports_append for schema in schemas)
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["assets"])
+ assert [schema.name for schema in schemas] == ["assets"]
+
+ def test_validate_credentials_plumbs_to_transport(self):
+ with mock.patch(f"{SOURCE}.validate_rapid7_insightvm_credentials", return_value=(True, None)) as mock_validate:
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is True
+ assert message is None
+ mock_validate.assert_called_once_with("key", "us")
+
+ def test_get_resumable_source_manager_is_bound_to_resume_config(self):
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is Rapid7InsightvmResumeConfig
+
+ def test_source_for_pipeline_plumbs_inputs(self):
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+ logger = mock.MagicMock()
+ inputs = SimpleNamespace(schema_name="assets", team_id=self.team_id, job_id="job-1", logger=logger)
+
+ with mock.patch(f"{SOURCE}.rapid7_insightvm_source") as mock_source:
+ self.source.source_for_pipeline(self.config, manager, cast(SourceInputs, inputs))
+
+ mock_source.assert_called_once_with(
+ api_key="key",
+ region="us",
+ endpoint="assets",
+ logger=logger,
+ resumable_source_manager=manager,
+ )