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 intruder import source (#67823)

Tom Owers965501f053cb
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 a020d6d94835..0e18475a1f9e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -181,6 +181,7 @@ the row lists both.
| incident_io | HTTP | requests | ✅ |
| insightly | HTTP | requests | ✅ |
| intercom | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| intruder | HTTP | requests | ✅ |
| invoiceninja | HTTP | requests | ✅ |
| ip2whois | HTTP | requests | ✅ |
| iterable | HTTP | requests | ✅ |
@@ -484,7 +485,6 @@ doesn't conflict with concurrent PRs.
- instantly
- instatus
- interzoid
-- intruder
- invoiced
- jamf_pro
- jobber
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 0459c04508f4..d4763ee614f2 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
@@ -1653,7 +1653,7 @@ class InterzoidSourceConfig(config.Config):
@config.config
class IntruderSourceConfig(config.Config):
- pass
+ access_token: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/canonical_descriptions.py
new file mode 100644
index 000000000000..0aec0271dba5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/canonical_descriptions.py
@@ -0,0 +1,121 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "targets": {
+ "description": "A system (host, IP, URL, cloud account, or container image) that Intruder scans for vulnerabilities.",
+ "docs_url": "https://developers.intruder.io/reference/targets_list-1",
+ "columns": {
+ "id": "Unique identifier for the target.",
+ "address": "The target's address (hostname, IP, URL, or cloud account identifier).",
+ "display_address": "Human-readable address (e.g. a cloud account name).",
+ "has_api_schemas": "Whether the target has one or more API schemas attached for API scanning.",
+ "has_authentications": "Whether the target has authenticated-scan credentials configured.",
+ "license_type": "Whether the target consumes an infrastructure or application license.",
+ "waf_provider": "The web application firewall provider detected on this target, or null if none.",
+ "waf_interference": "Whether a WAF is blocking scans on this target, or null if not applicable.",
+ "tags": "Tag names applied to this target.",
+ "target_status": "Current status of the target (e.g. live, unscanned, unresponsive, license_exceeded, agent_uninstalled).",
+ "target_type": "The kind of target (external, internal, cloud, or container_image).",
+ },
+ },
+ "scans": {
+ "description": "A vulnerability scan run against your targets.",
+ "docs_url": "https://developers.intruder.io/reference/scans_list-1",
+ "columns": {
+ "id": "Unique identifier for the scan.",
+ "status": "Current status of the scan (e.g. in_progress, completed, cancelled, analysing_results).",
+ "created_at": "When the scan was created.",
+ "scan_type": "What triggered the scan (e.g. assessment_schedule, new_service, cloudbot_new_target, rapid_remediation, advisory, cloud_security, container_image).",
+ "schedule_period": "The cadence of the schedule that produced the scan, if any (e.g. daily, weekly, monthly, quarterly, one_off).",
+ },
+ },
+ "scan_schedules": {
+ "description": "A recurring schedule that automatically starts scans against your targets.",
+ "docs_url": "https://developers.intruder.io/reference/scans_schedules_list",
+ "columns": {
+ "id": "Unique identifier for the scan schedule.",
+ "name": "Name of the scan schedule.",
+ "schedule_period": "How often the schedule runs (e.g. daily, weekly, monthly, quarterly, one_off).",
+ "first_scan_time": "When the first scan in the schedule is (or was) due to run.",
+ "next_scan_date": "When the next scan in the schedule is due to run.",
+ "status": "Current status of the schedule.",
+ "web_ports_only": "Whether the schedule only scans web ports.",
+ "latest_scan_id": "Identifier of the most recent scan produced by this schedule.",
+ "latest_scan_status": "Status of the most recent scan produced by this schedule.",
+ "last_scan_start_time": "When the most recent scan produced by this schedule started.",
+ },
+ },
+ "issues": {
+ "description": "A distinct type of security weakness Intruder has found, aggregating all of its occurrences across your targets.",
+ "docs_url": "https://developers.intruder.io/reference/issues_list-1",
+ "columns": {
+ "id": "Unique identifier for the issue.",
+ "severity": "Severity of the issue (low, medium, high, or critical).",
+ "title": "Short title describing the issue.",
+ "description": "Detailed description of the security weakness.",
+ "remediation": "Recommended steps to fix the issue.",
+ "snoozed": "Whether the issue is currently snoozed.",
+ "snooze_reason": "Reason the issue was snoozed, if any.",
+ "snooze_until": "Date the snooze expires, if any.",
+ "occurrences": "URL to the list of occurrences for this issue.",
+ "exploit_likelihood": "Intruder's assessment of how likely the weakness is to be exploited.",
+ "cvss_score": "CVSS score quantifying the severity of the issue.",
+ },
+ },
+ "occurrences": {
+ "description": "A single instance of an issue found on a specific target. Fanned out per issue and tagged with its parent issue_id.",
+ "docs_url": "https://developers.intruder.io/reference/issues_occurrences_list-1",
+ "columns": {
+ "id": "Unique identifier for the occurrence.",
+ "issue_id": "Identifier of the parent issue this occurrence belongs to (added by the connector).",
+ "occurrence_id": "Stable identifier of the occurrence across scans.",
+ "target": "Address of the target the occurrence was found on.",
+ "display_address": "Human-readable address of the affected target.",
+ "port": "The port the occurrence was found on.",
+ "protocol": "The network protocol the occurrence was found on.",
+ "extra_info": "Additional scanner-provided context about the occurrence.",
+ "age": "How long the occurrence has existed.",
+ "snoozed": "Whether the occurrence is currently snoozed.",
+ "snooze_reason": "Reason the occurrence was snoozed, if any.",
+ "snooze_until": "Date the snooze expires, if any.",
+ "exploit_likelihood": "Intruder's assessment of how likely this occurrence is to be exploited.",
+ "cvss_score": "CVSS score quantifying the severity of this occurrence.",
+ "first_seen_at": "When the occurrence was first seen.",
+ "target_last_scanned_at": "When the affected target was last scanned.",
+ "cves": "CVE identifiers associated with the occurrence.",
+ },
+ },
+ "fixed_occurrences": {
+ "description": "An occurrence of an issue that has since been resolved (remediated).",
+ "docs_url": "https://developers.intruder.io/reference/occurrences_fixed_list",
+ "columns": {
+ "id": "Unique identifier for the fixed occurrence.",
+ "occurrence_id": "Stable identifier of the underlying occurrence.",
+ "display_address": "Human-readable address of the affected target.",
+ "affected_host": "Host the occurrence was found on.",
+ "affected_port": "Port the occurrence was found on.",
+ "cvss_score": "CVSS score quantifying the severity of the occurrence.",
+ "description": "Description of the resolved security weakness.",
+ "due_date": "Date by which the occurrence was expected to be remediated.",
+ "exploit_likelihood": "Intruder's assessment of how likely the weakness was to be exploited.",
+ "extra_info": "Additional scanner-provided context about the occurrence.",
+ "first_seen_at": "When the occurrence was first seen.",
+ "host_state": "State of the affected host.",
+ "remediated_at": "When the occurrence was remediated.",
+ "remediation": "Recommended steps that resolved the issue.",
+ "severity": "Severity of the occurrence (low, medium, high, or critical).",
+ "tags": "Tag names applied to the affected target.",
+ "target_last_scanned_at": "When the affected target was last scanned.",
+ "title": "Short title describing the resolved issue.",
+ },
+ },
+ "tags": {
+ "description": "A tag used to group and filter targets.",
+ "docs_url": "https://developers.intruder.io/reference/tags_list",
+ "columns": {
+ "name": "Name of the tag.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/intruder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/intruder.py
new file mode 100644
index 000000000000..ded69063ec71
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/intruder.py
@@ -0,0 +1,247 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlsplit
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from urllib3.util.retry import Retry
+
+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.intruder.settings import INTRUDER_ENDPOINTS
+
+INTRUDER_BASE_URL = "https://api.intruder.io/v1"
+# Intruder caps authenticated requests at 5000/hour, so we page as large as the API allows to keep
+# the request count down. Its list endpoints default to 25 per page and accept a `limit` param.
+PAGE_SIZE = 100
+
+_ALLOWED_URL = urlsplit(INTRUDER_BASE_URL)
+
+
+class IntruderRetryableError(Exception):
+ pass
+
+
+def _validate_url(url: str) -> str:
+ """Reject any request URL that isn't on the Intruder API origin.
+
+ Pagination `next` URLs — and the resumed cursor loaded from Redis state — come from data we
+ don't fully trust. A poisoned resume value or a malicious `next` returned by the API (or an
+ intermediary) would otherwise make the worker send the customer's `Authorization: Bearer ...`
+ header to an attacker-controlled host, leaking the token (SSRF). Only allow the exact
+ `https://api.intruder.io/v1/...` origin through.
+ """
+ parts = urlsplit(url)
+ if (
+ parts.scheme != _ALLOWED_URL.scheme
+ or parts.netloc != _ALLOWED_URL.netloc
+ or not parts.path.startswith(f"{_ALLOWED_URL.path}/")
+ ):
+ raise ValueError(f"Refusing to follow non-Intruder URL: {url}")
+ return url
+
+
+class IntruderResumeConfig:
+ # Full URL of the next page to fetch. Intruder returns a ready-to-follow `next` URL on every
+ # paginated response. None means "start this endpoint (or fan-out issue) from its first page".
+ next_url: str | None = None
+ # The issue currently being processed in the occurrences fan-out. A stable issue-ID bookmark
+ # (not a positional index) so issues added/removed between a crash and the retry can't resume us
+ # into the wrong issue. None for the standard (non-fan-out) endpoints.
+ issue_id: int | None = None
+
+
+def _get_headers(access_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {access_token}",
+ "Accept": "application/json",
+ }
+
+
+def _initial_url(path: str) -> str:
+ # First request for a collection; every subsequent page is fetched by following the `next` URL
+ # the API returns, which already carries the limit/offset.
+ return f"{INTRUDER_BASE_URL}{path}?limit={PAGE_SIZE}"
+
+
+def validate_credentials(access_token: str) -> bool:
+ # `/targets/` requires a valid token (401 otherwise) and returns 200 even for accounts with no
+ # targets, making it a cheap, side-effect-free probe. `/health/` can't be used for this — it
+ # returns 200 regardless of whether the token is valid.
+ url = f"{INTRUDER_BASE_URL}/targets/"
+ try:
+ response = make_tracked_session(redact_values=(access_token,)).get(
+ url, headers=_get_headers(access_token), params={"limit": 1}, timeout=10
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ IntruderRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:
+ # Validate before every request (not just on save/resume) so the origin allowlist is the single
+ # choke point covering initial, resumed, and API-returned `next` URLs. `allow_redirects=False`
+ # stops a 3xx from retargeting the authenticated request at another host.
+ response = session.get(_validate_url(url), headers=headers, timeout=60, allow_redirects=False)
+
+ # Pagination is driven by `next` URLs in the body, never HTTP redirects; an unexpected redirect
+ # is refused rather than followed, so the bearer token can't be forwarded off-origin.
+ if response.is_redirect:
+ raise requests.HTTPError(
+ f"Intruder API returned an unexpected redirect: status={response.status_code}, url={url}",
+ response=response,
+ )
+
+ # 429 (rate limit) and 5xx are transient — back off and retry rather than fail the whole sync.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise IntruderRetryableError(f"Intruder API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Intruder API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _iter_issue_ids(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> Iterator[int]:
+ """Page through `/issues/` and yield each issue's id, following the `next` links."""
+ url = _initial_url(INTRUDER_ENDPOINTS["issues"].path)
+ while True:
+ data = _fetch_page(session, url, headers, logger)
+ for item in data.get("results", []):
+ yield item["id"]
+ next_url = data.get("next")
+ if not next_url:
+ break
+ url = next_url
+
+
+def _get_occurrence_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[IntruderResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Fan out over every issue, materializing its occurrences as rows tagged with `issue_id`.
+
+ Full refresh only — the occurrences endpoint has no verifiable server-side incremental filter —
+ so re-pulled rows on resume are deduped by the `[issue_id, id]` primary key on merge.
+ """
+ issue_ids = list(_iter_issue_ids(session, headers, logger))
+
+ # Resolve the saved issue-ID bookmark to the slice of issues still to process. If the bookmarked
+ # issue no longer exists (deleted between runs), start over from the first issue — merge dedupes
+ # the re-pulled rows on the primary key. `resume_url` is consumed by the resumed-into issue only.
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = issue_ids
+ resume_url: str | None = None
+ if resume is not None and resume.issue_id is not None and resume.issue_id in issue_ids:
+ remaining = issue_ids[issue_ids.index(resume.issue_id) :]
+ resume_url = resume.next_url
+ logger.debug(f"Intruder: resuming occurrences from issue_id={resume.issue_id}, url={resume_url}")
+
+ for index, issue_id in enumerate(remaining):
+ path = INTRUDER_ENDPOINTS["occurrences"].path.format(issue_id=issue_id)
+ url = resume_url or _initial_url(path)
+ resume_url = None # only the resumed-into issue uses the saved URL; the rest start fresh
+
+ while True:
+ data = _fetch_page(session, url, headers, logger)
+ # Tag each occurrence with its parent issue so `[issue_id, id]` is unique table-wide.
+ results = [{**item, "issue_id": issue_id} for item in data.get("results", [])]
+ if results:
+ yield results
+
+ next_url = data.get("next")
+ if not next_url:
+ break
+ # Save AFTER yielding so a crash re-yields the last page (merge dedupes) rather than
+ # skipping it.
+ resumable_source_manager.save_state(IntruderResumeConfig(next_url=next_url, issue_id=issue_id))
+ url = next_url
+
+ # Advance the bookmark to the next issue so a crash between issues resumes correctly. Its
+ # first page URL is rebuilt when the loop reaches it.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(IntruderResumeConfig(next_url=None, issue_id=remaining[index + 1]))
+
+
+def get_rows(
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[IntruderResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = INTRUDER_ENDPOINTS[endpoint]
+ headers = _get_headers(access_token)
+ # One session reused across every page (and, for the fan-out, every issue) so urllib3 keeps the
+ # connection alive instead of re-handshaking per request. `retry=Retry(total=0)` disables the
+ # adapter's own retries so tenacity in `_fetch_page` is the single retry authority;
+ # `redact_values` masks the bearer token in logged URLs and captured samples.
+ session = make_tracked_session(retry=Retry(total=0), redact_values=(access_token,))
+
+ if config.fan_out_over_issues:
+ yield from _get_occurrence_rows(session, headers, logger, resumable_source_manager)
+ return
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.next_url:
+ url = resume.next_url
+ logger.debug(f"Intruder: resuming {endpoint} from URL: {url}")
+ else:
+ url = _initial_url(config.path)
+
+ while True:
+ data = _fetch_page(session, url, headers, logger)
+ results = data.get("results", [])
+ if results:
+ yield results
+
+ next_url = data.get("next")
+ if not next_url:
+ break
+ # Save AFTER yielding so a crash re-yields the last page (merge dedupes) rather than skipping it.
+ resumable_source_manager.save_state(IntruderResumeConfig(next_url=next_url))
+ url = next_url
+
+
+def intruder_source(
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[IntruderResumeConfig],
+) -> SourceResponse:
+ config = INTRUDER_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ access_token=access_token,
+ 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 config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/settings.py
new file mode 100644
index 000000000000..24aedda75d5f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/settings.py
@@ -0,0 +1,44 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class IntruderEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Stable, creation-time datetime field used for datetime partitioning. Never a field that can
+ # change over time (e.g. a "last seen"/"updated" column), which would rewrite partitions on
+ # every sync. `None` means the endpoint has no such field, so the table is left unpartitioned.
+ partition_key: str | None = None
+ should_sync_default: bool = True
+ # Fan out over every issue, calling `/issues/{issue_id}/occurrences/` per issue. When True,
+ # `path` is a template with an `{issue_id}` placeholder and each row is tagged with its parent
+ # `issue_id` so the composite primary key stays unique across the whole table.
+ fan_out_over_issues: bool = False
+
+
+# Intruder's REST API is full-refresh only: no list endpoint exposes a documented, verifiable
+# server-side "created/updated after" cursor we can persist between runs, so every endpoint
+# re-reads its full collection each sync (merge dedupes on the primary key). See source.py.
+INTRUDER_ENDPOINTS: dict[str, IntruderEndpointConfig] = {
+ "targets": IntruderEndpointConfig(name="targets", path="/targets/"),
+ "scans": IntruderEndpointConfig(name="scans", path="/scans/", partition_key="created_at"),
+ "scan_schedules": IntruderEndpointConfig(name="scan_schedules", path="/scans/schedules/"),
+ "issues": IntruderEndpointConfig(name="issues", path="/issues/"),
+ "occurrences": IntruderEndpointConfig(
+ name="occurrences",
+ path="/issues/{issue_id}/occurrences/",
+ primary_keys=["issue_id", "id"],
+ partition_key="first_seen_at",
+ fan_out_over_issues=True,
+ ),
+ "fixed_occurrences": IntruderEndpointConfig(
+ name="fixed_occurrences",
+ path="/occurrences/fixed/",
+ partition_key="first_seen_at",
+ ),
+ # Tags are returned as bare `{name}` objects with no numeric id, so `name` is the primary key.
+ "tags": IntruderEndpointConfig(name="tags", path="/tags/", primary_keys=["name"]),
+}
+
+ENDPOINTS = tuple(INTRUDER_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/source.py
index 4730e99c8e63..83d1590907d7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/source.py
@@ -1,19 +1,39 @@
-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 IntruderSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.intruder.intruder import (
+ IntruderResumeConfig,
+ intruder_source,
+ validate_credentials as validate_intruder_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.intruder.settings import ENDPOINTS
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class IntruderSource(SimpleSource[IntruderSourceConfig]):
+class IntruderSource(ResumableSource[IntruderSourceConfig, IntruderResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.INTRUDER
@@ -24,7 +44,88 @@ class IntruderSource(SimpleSource[IntruderSourceConfig]):
name=SchemaExternalDataSourceType.INTRUDER,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Intruder",
- iconPath="/static/services/intruder.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Intruder API access token to pull your attack-surface and vulnerability data into the PostHog Data warehouse.
+
+Create an access token under **My account > API Access Tokens** in your [Intruder account](https://portal.intruder.io/). The token is shown only once, so copy it immediately. API scanning of targets requires the appropriate Intruder plan license.""",
+ iconPath="/static/services/intruder.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/intruder",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="access_token",
+ label="API access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.intruder.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or expired access token surfaces as a requests HTTPError when `_fetch_page`
+ # calls `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the
+ # sync. Match the stable status text and base host, not the per-request path.
+ "401 Client Error: Unauthorized for url: https://api.intruder.io": "Your Intruder access token is invalid or has expired. Create a new token under My account > API Access Tokens in Intruder, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.intruder.io": "Your Intruder access token does not have permission to read this data. Check the token's permissions in Intruder, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: IntruderSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Intruder is full refresh only: no list endpoint exposes a verifiable server-side
+ # created/updated-after cursor we can persist between runs, so nothing supports incremental.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ 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: IntruderSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_intruder_credentials(config.access_token):
+ return True, None
+
+ return False, "Invalid Intruder API access token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[IntruderResumeConfig]:
+ return ResumableSourceManager[IntruderResumeConfig](inputs, IntruderResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: IntruderSourceConfig,
+ resumable_source_manager: ResumableSourceManager[IntruderResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return intruder_source(
+ access_token=config.access_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/tests/test_intruder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/tests/test_intruder.py
new file mode 100644
index 000000000000..0cdef879d681
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/tests/test_intruder.py
@@ -0,0 +1,372 @@
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+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.intruder import intruder
+from products.warehouse_sources.backend.temporal.data_imports.sources.intruder.intruder import (
+ IntruderResumeConfig,
+ get_rows,
+ intruder_source,
+ validate_credentials,
+)
+
+
+class _FakeResumableManager:
+ def __init__(self, state: IntruderResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[IntruderResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> IntruderResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: IntruderResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ endpoint: str,
+ pages: dict[str, Any],
+) -> list[dict]:
+ """Run get_rows against a fake page map (url -> response body or Exception)."""
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ result = pages[url]
+ if isinstance(result, Exception):
+ raise result
+ return result
+
+ monkeypatch.setattr(intruder, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(intruder, "make_tracked_session", lambda *a, **k: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ access_token="token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=cast(ResumableSourceManager[IntruderResumeConfig], manager),
+ ):
+ rows.extend(batch)
+ return rows
+
+
+class TestStandardPagination:
+ def test_follows_next_url_until_exhausted(self, monkeypatch: Any) -> None:
+ # A bug that dropped the `next` follow (or read the wrong key) would only return page one.
+ pages: dict[str, Any] = {
+ "https://api.intruder.io/v1/targets/?limit=100": {
+ "results": [{"id": 1}, {"id": 2}],
+ "next": "https://api.intruder.io/v1/targets/?limit=100&offset=100",
+ },
+ "https://api.intruder.io/v1/targets/?limit=100&offset=100": {
+ "results": [{"id": 3}],
+ "next": None,
+ },
+ }
+ rows = _collect(_FakeResumableManager(), monkeypatch, "targets", pages)
+ assert [r["id"] for r in rows] == [1, 2, 3]
+
+ def test_empty_first_page_terminates(self, monkeypatch: Any) -> None:
+ pages: dict[str, Any] = {"https://api.intruder.io/v1/scans/?limit=100": {"results": [], "next": None}}
+ rows = _collect(_FakeResumableManager(), monkeypatch, "scans", pages)
+ assert rows == []
+
+ def test_saves_state_after_each_page_but_not_after_last(self, monkeypatch: Any) -> None:
+ # State must be saved AFTER yielding a page and only when more pages remain, so a crash
+ # re-yields the last page (merge dedupes) rather than skipping it. Saving the final page's
+ # (absent) cursor would be wrong.
+ pages: dict[str, Any] = {
+ "https://api.intruder.io/v1/targets/?limit=100": {
+ "results": [{"id": 1}],
+ "next": "https://api.intruder.io/v1/targets/?limit=100&offset=100",
+ },
+ "https://api.intruder.io/v1/targets/?limit=100&offset=100": {"results": [{"id": 2}], "next": None},
+ }
+ manager = _FakeResumableManager()
+ _collect(manager, monkeypatch, "targets", pages)
+ assert [s.next_url for s in manager.saved] == ["https://api.intruder.io/v1/targets/?limit=100&offset=100"]
+
+ def test_resumes_from_saved_next_url(self, monkeypatch: Any) -> None:
+ # With saved state the first request must be the saved cursor, not the initial page.
+ pages: dict[str, Any] = {
+ "https://api.intruder.io/v1/targets/?limit=100&offset=100": {"results": [{"id": 2}], "next": None},
+ }
+ manager = _FakeResumableManager(
+ IntruderResumeConfig(next_url="https://api.intruder.io/v1/targets/?limit=100&offset=100")
+ )
+ rows = _collect(manager, monkeypatch, "targets", pages)
+ assert [r["id"] for r in rows] == [2]
+
+
+class TestOccurrencesFanOut:
+ @staticmethod
+ def _issue_page(ids: list[int], next_url: str | None) -> dict:
+ return {"results": [{"id": i} for i in ids], "next": next_url}
+
+ def test_injects_parent_issue_id_into_every_row(self, monkeypatch: Any) -> None:
+ # The occurrences endpoint response has no issue reference; without the injected issue_id the
+ # composite primary key [issue_id, id] collapses to id and duplicate rows accumulate.
+ pages: dict[str, Any] = {
+ "https://api.intruder.io/v1/issues/?limit=100": self._issue_page([10, 20], None),
+ "https://api.intruder.io/v1/issues/10/occurrences/?limit=100": {
+ "results": [{"id": 1}, {"id": 2}],
+ "next": None,
+ },
+ "https://api.intruder.io/v1/issues/20/occurrences/?limit=100": {"results": [{"id": 3}], "next": None},
+ }
+ rows = _collect(_FakeResumableManager(), monkeypatch, "occurrences", pages)
+ assert rows == [
+ {"id": 1, "issue_id": 10},
+ {"id": 2, "issue_id": 10},
+ {"id": 3, "issue_id": 20},
+ ]
+
+ def test_follows_occurrence_pagination_within_an_issue(self, monkeypatch: Any) -> None:
+ pages: dict[str, Any] = {
+ "https://api.intruder.io/v1/issues/?limit=100": self._issue_page([10], None),
+ "https://api.intruder.io/v1/issues/10/occurrences/?limit=100": {
+ "results": [{"id": 1}],
+ "next": "https://api.intruder.io/v1/issues/10/occurrences/?limit=100&offset=100",
+ },
+ "https://api.intruder.io/v1/issues/10/occurrences/?limit=100&offset=100": {
+ "results": [{"id": 2}],
+ "next": None,
+ },
+ }
+ rows = _collect(_FakeResumableManager(), monkeypatch, "occurrences", pages)
+ assert [r["id"] for r in rows] == [1, 2]
+
+ def test_resumes_from_bookmarked_issue(self, monkeypatch: Any) -> None:
+ # Resuming must skip already-processed issue 10 and pick up at issue 20.
+ pages: dict[str, Any] = {
+ "https://api.intruder.io/v1/issues/?limit=100": self._issue_page([10, 20], None),
+ "https://api.intruder.io/v1/issues/20/occurrences/?limit=100": {"results": [{"id": 3}], "next": None},
+ }
+ manager = _FakeResumableManager(IntruderResumeConfig(next_url=None, issue_id=20))
+ rows = _collect(manager, monkeypatch, "occurrences", pages)
+ assert rows == [{"id": 3, "issue_id": 20}]
+
+ def test_deleted_bookmarked_issue_restarts_from_first(self, monkeypatch: Any) -> None:
+ # If the bookmarked issue no longer exists, re-pull from the first issue (merge dedupes).
+ pages: dict[str, Any] = {
+ "https://api.intruder.io/v1/issues/?limit=100": self._issue_page([10, 20], None),
+ "https://api.intruder.io/v1/issues/10/occurrences/?limit=100": {"results": [{"id": 1}], "next": None},
+ "https://api.intruder.io/v1/issues/20/occurrences/?limit=100": {"results": [{"id": 3}], "next": None},
+ }
+ manager = _FakeResumableManager(IntruderResumeConfig(next_url=None, issue_id=999))
+ rows = _collect(manager, monkeypatch, "occurrences", pages)
+ assert [r["id"] for r in rows] == [1, 3]
+
+ def test_advances_bookmark_between_issues(self, monkeypatch: Any) -> None:
+ pages: dict[str, Any] = {
+ "https://api.intruder.io/v1/issues/?limit=100": self._issue_page([10, 20], None),
+ "https://api.intruder.io/v1/issues/10/occurrences/?limit=100": {"results": [{"id": 1}], "next": None},
+ "https://api.intruder.io/v1/issues/20/occurrences/?limit=100": {"results": [{"id": 3}], "next": None},
+ }
+ manager = _FakeResumableManager()
+ _collect(manager, monkeypatch, "occurrences", pages)
+ # After finishing issue 10, the bookmark advances to issue 20 (no in-issue cursor).
+ assert IntruderResumeConfig(next_url=None, issue_id=20) in manager.saved
+
+
+class TestFetchPageRetries:
+ @parameterized.expand(
+ [
+ ("rate_limited", 429),
+ ("server_error", 500),
+ ("bad_gateway", 503),
+ ]
+ )
+ def test_retryable_status_codes_retry(self, _name: str, status: int) -> None:
+ # 429/5xx must retry rather than fail the whole sync.
+ retryable = MagicMock()
+ retryable.status_code = status
+ retryable.ok = False
+ retryable.is_redirect = False
+ good = MagicMock()
+ good.status_code = 200
+ good.ok = True
+ good.is_redirect = False
+ good.json.return_value = {"results": []}
+
+ session = MagicMock()
+ session.get.side_effect = [retryable, good]
+
+ with patch.object(intruder._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = intruder._fetch_page(session, "https://api.intruder.io/v1/targets/", {}, MagicMock())
+
+ assert result == {"results": []}
+ assert session.get.call_count == 2
+
+ @parameterized.expand(
+ [
+ ("read_timeout", requests.ReadTimeout("Read timed out.")),
+ ("connection_error", requests.ConnectionError("Connection reset by peer")),
+ ]
+ )
+ def test_transient_network_errors_retry(self, _name: str, transient_error: Exception) -> None:
+ good = MagicMock()
+ good.status_code = 200
+ good.ok = True
+ good.is_redirect = False
+ good.json.return_value = {"results": []}
+
+ session = MagicMock()
+ session.get.side_effect = [transient_error, good]
+
+ with patch.object(intruder._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = intruder._fetch_page(session, "https://api.intruder.io/v1/targets/", {}, MagicMock())
+
+ assert result == {"results": []}
+ assert session.get.call_count == 2
+
+ def test_401_is_not_retried_and_raises(self) -> None:
+ # A 401 is a credential problem: raise immediately (surfaced as non-retryable upstream)
+ # instead of burning retries.
+ response = requests.Response()
+ response.status_code = 401
+ response.url = "https://api.intruder.io/v1/targets/"
+
+ session = MagicMock()
+ session.get.return_value = response
+
+ with pytest.raises(requests.HTTPError):
+ intruder._fetch_page(session, "https://api.intruder.io/v1/targets/", {}, MagicMock())
+
+ assert session.get.call_count == 1
+
+
+class TestUrlSafety:
+ @parameterized.expand(
+ [
+ ("http_downgrade", "http://api.intruder.io/v1/targets/"),
+ ("attacker_host", "https://evil.com/v1/targets/"),
+ ("attacker_subdomain", "https://api.intruder.io.evil.com/v1/targets/"),
+ ("userinfo_trick", "https://[email protected]/v1/targets/"),
+ ("wrong_path_prefix", "https://api.intruder.io/v2/targets/"),
+ ("root_path", "https://api.intruder.io/"),
+ ]
+ )
+ def test_validate_url_rejects_off_origin(self, _name: str, url: str) -> None:
+ # A poisoned resume cursor or a malicious API-returned `next` must never be followed with the
+ # bearer token — the allowlist is the SSRF guard.
+ with pytest.raises(ValueError):
+ intruder._validate_url(url)
+
+ @parameterized.expand(
+ [
+ ("collection", "https://api.intruder.io/v1/targets/"),
+ ("with_paging", "https://api.intruder.io/v1/issues/10/occurrences/?limit=100&offset=100"),
+ ]
+ )
+ def test_validate_url_allows_intruder_origin(self, _name: str, url: str) -> None:
+ assert intruder._validate_url(url) == url
+
+ def test_fetch_page_validates_before_requesting(self) -> None:
+ # Validation must run before the network call, so a bad URL never reaches the wire (and the
+ # session — carrying the token — is never contacted).
+ session = MagicMock()
+ with pytest.raises(ValueError):
+ intruder._fetch_page(session, "https://evil.com/v1/targets/", {}, MagicMock())
+ session.get.assert_not_called()
+
+ def test_fetch_page_refuses_redirects(self) -> None:
+ # Redirects could retarget the authenticated request off-origin; they must be refused, not
+ # followed. `allow_redirects=False` returns the 3xx, which we reject.
+ redirect = requests.Response()
+ redirect.status_code = 302
+ redirect.headers["Location"] = "https://evil.com"
+
+ session = MagicMock()
+ session.get.return_value = redirect
+
+ with pytest.raises(requests.HTTPError):
+ intruder._fetch_page(session, "https://api.intruder.io/v1/targets/", {}, MagicMock())
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ def test_status_maps_to_bool(self, _name: str, status: int, expected: bool) -> None:
+ response = MagicMock()
+ response.status_code = status
+ with patch.object(intruder, "make_tracked_session") as make_session:
+ make_session.return_value.get.return_value = response
+ assert validate_credentials("token") is expected
+
+ def test_network_error_is_not_valid(self) -> None:
+ with patch.object(intruder, "make_tracked_session") as make_session:
+ make_session.return_value.get.side_effect = requests.ConnectionError("boom")
+ assert validate_credentials("token") is False
+
+
+class TestSessionHardening:
+ def test_validate_credentials_redacts_token(self, monkeypatch: Any) -> None:
+ # Dropping redact_values would leak the bearer token into logged URLs / captured samples.
+ captured: dict[str, Any] = {}
+
+ def fake_session(*args: Any, **kwargs: Any) -> MagicMock:
+ captured.update(kwargs)
+ response = requests.Response()
+ response.status_code = 200
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ monkeypatch.setattr(intruder, "make_tracked_session", fake_session)
+ validate_credentials("secret-token")
+ assert captured.get("redact_values") == ("secret-token",)
+
+ def test_get_rows_redacts_token_and_disables_adapter_retries(self, monkeypatch: Any) -> None:
+ # tenacity in `_fetch_page` is the single retry authority; the adapter must not stack its own.
+ captured: dict[str, Any] = {}
+
+ def fake_session(*args: Any, **kwargs: Any) -> MagicMock:
+ captured.update(kwargs)
+ return MagicMock()
+
+ monkeypatch.setattr(intruder, "make_tracked_session", fake_session)
+ monkeypatch.setattr(intruder, "_fetch_page", lambda *a, **k: {"results": [], "next": None})
+
+ list(
+ get_rows(
+ access_token="secret-token",
+ endpoint="targets",
+ logger=MagicMock(),
+ resumable_source_manager=cast(ResumableSourceManager[IntruderResumeConfig], _FakeResumableManager()),
+ )
+ )
+ assert captured.get("redact_values") == ("secret-token",)
+ assert captured.get("retry") is not None and captured["retry"].total == 0
+
+
+class TestSourceResponse:
+ @parameterized.expand(
+ [
+ ("targets", ["id"], None),
+ ("scans", ["id"], ["created_at"]),
+ ("scan_schedules", ["id"], None),
+ ("issues", ["id"], None),
+ ("occurrences", ["issue_id", "id"], ["first_seen_at"]),
+ ("fixed_occurrences", ["id"], ["first_seen_at"]),
+ ("tags", ["name"], None),
+ ]
+ )
+ def test_primary_keys_and_partitioning(
+ self, endpoint: str, expected_pks: list[str], expected_partition_keys: list[str] | None
+ ) -> None:
+ response = intruder_source(
+ access_token="token", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == expected_pks
+ assert response.partition_keys == expected_partition_keys
+ assert response.partition_mode == ("datetime" if expected_partition_keys else None)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/tests/test_intruder_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/tests/test_intruder_source.py
new file mode 100644
index 000000000000..c37a298aeee1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intruder/tests/test_intruder_source.py
@@ -0,0 +1,112 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import IntruderSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.intruder import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.intruder.intruder import IntruderResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.intruder.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.intruder.source import IntruderSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestSourceConfig:
+ def test_source_type(self) -> None:
+ assert IntruderSource().source_type == ExternalDataSourceType.INTRUDER
+
+ def test_config_shape(self) -> None:
+ config = IntruderSource().get_source_config
+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # Kept behind the unreleased flag while the source is in alpha — hides it from the wizard.
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/intruder"
+
+ def test_single_secret_access_token_field(self) -> None:
+ # A single required, secret bearer-token field is the whole auth surface — a non-secret or
+ # non-required regression would leak or break the token input.
+ fields = IntruderSource().get_source_config.fields
+ assert len(fields) == 1
+ field = fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.name == "access_token"
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.required is True
+
+
+class TestGetSchemas:
+ def test_all_endpoints_are_full_refresh(self) -> None:
+ # Intruder exposes no verifiable server-side cursor, so every schema must ship full-refresh
+ # only. A stray supports_incremental=True would advertise a cursor the transport can't honor.
+ schemas = IntruderSource().get_schemas(IntruderSourceConfig(access_token="t"), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is False and s.supports_append is False for s in schemas)
+
+ def test_names_filter(self) -> None:
+ schemas = IntruderSource().get_schemas(
+ IntruderSourceConfig(access_token="t"), team_id=1, names=["targets", "tags"]
+ )
+ assert {s.name for s in schemas} == {"targets", "tags"}
+
+ def test_documented_tables_match_endpoints(self) -> None:
+ # lists_tables_without_credentials=True publishes the catalog to public docs with no I/O.
+ tables = IntruderSource().get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("valid", True), ("invalid", False)])
+ def test_delegates_to_transport(self, _name: str, transport_result: bool) -> None:
+ with patch.object(source_module, "validate_intruder_credentials", return_value=transport_result) as mock:
+ ok, error = IntruderSource().validate_credentials(IntruderSourceConfig(access_token="tok"), team_id=1)
+ mock.assert_called_once_with("tok")
+ assert ok is transport_result
+ assert (error is None) is transport_result
+
+
+class TestNonRetryableErrors:
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.intruder.io/v1/targets/"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.intruder.io/v1/issues/"),
+ ]
+ )
+ def test_auth_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable = IntruderSource().get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.intruder.io/v1/targets/"),
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.intruder.io/v1/scans/"),
+ ]
+ )
+ def test_transient_errors_stay_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable = IntruderSource().get_non_retryable_errors()
+ assert not any(key in observed_error for key in non_retryable)
+
+
+class TestPipelineWiring:
+ def test_resumable_manager_bound_to_resume_config(self) -> None:
+ inputs = MagicMock()
+ manager = IntruderSource().get_resumable_source_manager(inputs)
+ assert manager._data_class is IntruderResumeConfig
+
+ def test_source_for_pipeline_plumbs_token_and_endpoint(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "occurrences"
+ manager = MagicMock()
+ with patch.object(source_module, "intruder_source") as mock_source:
+ IntruderSource().source_for_pipeline(IntruderSourceConfig(access_token="tok"), manager, inputs)
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["access_token"] == "tok"
+ assert kwargs["endpoint"] == "occurrences"
+ assert kwargs["resumable_source_manager"] is manager