:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement qualys_vmdr import source (#71163)
Tom Owerse5d9e9bfebef
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex c2af4d689fe4..7472dba046e0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -368,6 +368,7 @@ the row lists both.| pylon | HTTP | requests | ✅ || pypi | HTTP | requests | ✅ || qualaroo | HTTP | requests | ✅ |+| qualys_vmdr | HTTP (XML responses) | requests | ✅ || recurly | HTTP | requests + `rest_source.RESTClient` | ✅ || ramp | HTTP | requests | ✅ || rapid7_insightvm | HTTP | requests | ✅ |@@ -823,7 +824,6 @@ doesn't conflict with concurrent PRs.- qdrant- qonto- qualtrics-- qualys_vmdr- quickbooks- railway- railzdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex e2b09ce607d1..0ca74192f177 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@@ -3364,7 +3364,9 @@ class QualtricsSourceConfig(config.Config):@config.configclass QualysVmdrSourceConfig(config.Config):- pass+ api_server: str+ username: str+ password: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/canonical_descriptions.pynew file mode 100644index 000000000000..7e787c64f33c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/canonical_descriptions.py@@ -0,0 +1,73 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_API_DOCS_URL = "https://docs.qualys.com/en/vm/api/index.htm"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "hosts": {+ "description": "Asset inventory: one row per host in the Qualys subscription, with tracking method, OS, and last-scan timestamps.",+ "docs_url": _API_DOCS_URL,+ "columns": {+ "id": "Unique Qualys host ID.",+ "ip": "IP address of the host.",+ "tracking_method": "How the host is tracked in Qualys (IP, DNS, NETBIOS, or agent).",+ "dns": "DNS hostname of the host.",+ "netbios": "NetBIOS name of the host.",+ "os": "Operating system detected on the host.",+ "last_vuln_scan_datetime": "When the host was last scanned by a VM scan.",+ "last_vm_scanned_date": "When the host was last successfully scanned for vulnerabilities.",+ },+ },+ "host_list_detection": {+ "description": "Per-host vulnerability detections: one row per (host, detection) with status, severity, and first/last found timestamps — the core VMDR remediation feed.",+ "docs_url": _API_DOCS_URL,+ "columns": {+ "unique_vuln_id": "Subscription-wide unique ID of the detection record.",+ "qid": "Qualys ID of the vulnerability (joins to the knowledge_base table).",+ "type": "Detection type: Confirmed, Potential, or Info.",+ "severity": "Severity level of the detection (1-5).",+ "status": "Detection status: New, Active, Fixed, or Re-Opened.",+ "port": "Port the vulnerability was detected on, if applicable.",+ "protocol": "Protocol the vulnerability was detected over, if applicable.",+ "results": "Scan test results/evidence for the detection.",+ "first_found_datetime": "When the vulnerability was first detected on the host.",+ "last_found_datetime": "When the vulnerability was most recently detected on the host.",+ "last_update_datetime": "When the detection record was last updated.",+ "times_found": "Number of times the vulnerability has been detected on the host.",+ "qds": "Qualys Detection Score (0-100) for the detection.",+ "host_id": "Unique Qualys host ID the detection belongs to (joins to the hosts table).",+ "host_ip": "IP address of the host the detection belongs to.",+ },+ },+ "scans": {+ "description": "VM scan history: one row per vulnerability scan with launch time, state, and target.",+ "docs_url": _API_DOCS_URL,+ "columns": {+ "ref": "Unique scan reference (for example scan/1234567890.12345).",+ "type": "How the scan was launched (On-Demand, Scheduled, or API).",+ "title": "Title of the scan.",+ "user_login": "Qualys user who launched the scan.",+ "launch_datetime": "When the scan was launched.",+ "duration": "How long the scan ran.",+ "state": "Scan state (for example Finished, Running, Canceled, or Error).",+ "target": "IPs/ranges the scan targeted.",+ "processed": "Whether the scan results have been processed (1) or not (0).",+ },+ },+ "knowledge_base": {+ "description": "Qualys KnowledgeBase: one row per vulnerability definition (QID) with severity, category, and CVE references.",+ "docs_url": _API_DOCS_URL,+ "columns": {+ "qid": "Qualys ID of the vulnerability definition.",+ "vuln_type": "Vulnerability type: Vulnerability, Potential Vulnerability, or Information Gathered.",+ "severity_level": "Severity level assigned by Qualys (1-5).",+ "title": "Title of the vulnerability.",+ "category": "Vulnerability category (for example Web server, Windows, or Database).",+ "cve_list": "CVE identifiers associated with the vulnerability (JSON).",+ "patchable": "Whether a patch is available for the vulnerability.",+ "published_datetime": "When the vulnerability definition was first published.",+ "last_service_modification_datetime": "When Qualys last modified the vulnerability definition.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/qualys_vmdr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/qualys_vmdr.pynew file mode 100644index 000000000000..425c6abfe7d9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/qualys_vmdr.py@@ -0,0 +1,391 @@+import json+import time+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode, urlsplit, urlunsplit++# nosemgrep: python.lang.security.use-defused-xml.use-defused-xml (Element is only the node type for annotations — all parsing goes through defusedxml below)+from xml.etree.ElementTree import Element++import requests+import defusedxml.ElementTree as DET+from structlog.types import FilteringBoundLogger+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.security.url_validation import is_url_allowed++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.qualys_vmdr.settings import (+ QUALYS_VMDR_ENDPOINTS,+ QualysVmdrEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 300 # long list requests stream slowly with keep-alive bytes+MAX_RATE_LIMIT_WAIT_SECONDS = 120++# The API server is user-supplied, so a malicious or misconfigured host could stream an unbounded+# body and exhaust a shared worker (requests buffers the whole body into memory by default, and the+# read timeout only guards idle gaps between reads, not a steady large transfer). Cap what we read+# into memory. Generous enough for a full truncated batch of host detections; anything past it is+# refused rather than buffered.+MAX_RESPONSE_BYTES = 256 * 1024 * 1024+RESPONSE_CHUNK_BYTES = 256 * 1024+# Wall-clock budget for downloading one page's body. requests' timeout only bounds each individual+# socket read, so a host that dribbles the body slowly could hold the connection (and a shared+# worker) open far longer than any read timeout while staying under MAX_RESPONSE_BYTES. This caps+# total transfer time — 256 MiB in 300s is a ~0.85 MiB/s floor, far below any real Qualys response+# and far above a slow-drip stall.+MAX_DOWNLOAD_SECONDS = 300++RESPONSE_TOO_LARGE_ERROR = "Qualys API response body was too large"+RESPONSE_TOO_SLOW_ERROR = "Qualys API response download was too slow"++# Qualys rejects any request without an X-Requested-With header.+_BASE_HEADERS = {"X-Requested-With": "PostHog Data Warehouse"}+++class QualysVmdrRetryableError(Exception):+ def __init__(self, message: str, wait_seconds: int | None = None):+ super().__init__(message)+ self.wait_seconds = wait_seconds+++class QualysVmdrResponseTooLargeError(Exception):+ """Non-retryable: re-fetching the same page yields the same oversized body."""+++class QualysVmdrResponseTooSlowError(Exception):+ """Non-retryable: a host dribbling one page's body will dribble it again on retry."""+++def _read_capped_body(response: requests.Response) -> bytes:+ """Stream the body into memory, aborting past MAX_RESPONSE_BYTES or MAX_DOWNLOAD_SECONDS.++ The API server is user-supplied, so a body must never be buffered unbounded (size cap) nor be+ allowed to hold the connection open indefinitely by dribbling under the per-read timeout (time+ cap). Both limits are non-retryable — re-fetching the same page yields the same oversized/slow+ body.+ """+ chunks: list[bytes] = []+ total = 0+ deadline = time.monotonic() + MAX_DOWNLOAD_SECONDS+ try:+ for chunk in response.iter_content(chunk_size=RESPONSE_CHUNK_BYTES):+ if time.monotonic() > deadline:+ raise QualysVmdrResponseTooSlowError(+ f"{RESPONSE_TOO_SLOW_ERROR}: exceeded {MAX_DOWNLOAD_SECONDS}s download budget"+ )+ if not chunk:+ continue+ total += len(chunk)+ if total > MAX_RESPONSE_BYTES:+ raise QualysVmdrResponseTooLargeError(+ f"{RESPONSE_TOO_LARGE_ERROR}: exceeded {MAX_RESPONSE_BYTES} bytes"+ )+ chunks.append(chunk)+ finally:+ response.close()+ return b"".join(chunks)+++class QualysVmdrResumeConfig:+ # Next truncated-batch URL (from the response's WARNING block), re-rooted onto the+ # configured API server. Carries the id_min cursor plus the original filter params.+ next_url: str+++def build_base_url(api_server: str) -> str:+ """Normalize the user-supplied platform host into an https base URL.++ Users supply their account's regional API server (e.g. `qualysapi.qualys.eu`), with or+ without a scheme or trailing slash. The FO API is only served over TLS, so any scheme is+ forced to https.+ """+ api_server = api_server.strip().rstrip("/")+ if "://" in api_server:+ api_server = api_server.split("://", 1)[1]+ return f"https://{api_server}"+++def _format_since_value(value: Any) -> str:+ """Format an incremental cursor as the `YYYY-MM-DDTHH:MM:SSZ` datetime Qualys expects."""+ if isinstance(value, datetime):+ utc_value = value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)+ return utc_value.strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%dT00:00:00Z")+ return str(value)+++def _make_session(username: str, password: str) -> requests.Session:+ # `allow_redirects=False` as defense-in-depth: the API server is user-supplied and a valid+ # Qualys platform responds directly, so there is no legitimate redirect to follow — pinning+ # redirects off keeps the basic-auth credential on the validated host.+ session = make_tracked_session(headers=_BASE_HEADERS, redact_values=(password,), allow_redirects=False)+ session.auth = (username, password)+ return session+++def _check_url_allowed(base_url: str) -> None:+ # Defense-in-depth SSRF check (the Smokescreen egress proxy is the load-bearing control):+ # the stored api_server is user-supplied, so reject localhost, cloud-metadata hosts,+ # internal domains, and private IPs before any authenticated request leaves the worker.+ allowed, reason = is_url_allowed(base_url)+ if not allowed:+ raise ValueError(f"Qualys API server URL is not allowed: {reason}")+++def _rate_limit_wait(retry_state: RetryCallState) -> float:+ """Honor the server-provided wait (X-RateLimit-ToWait-Sec) before falling back to backoff."""+ exception = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exception, QualysVmdrRetryableError) and exception.wait_seconds is not None:+ return float(min(exception.wait_seconds, MAX_RATE_LIMIT_WAIT_SECONDS))+ return wait_exponential_jitter(initial=1, max=30)(retry_state)+++def _parse_xml(text: str) -> Element:+ # Qualys streams keep-alive whitespace while generating long responses; strip it so the+ # XML declaration sits at the start of the document. defusedxml rejects entity-expansion+ # and external-entity payloads a compromised/spoofed server could embed.+ root: Element = DET.fromstring(text.strip())+ return root+++@retry(+ retry=retry_if_exception_type(+ (+ QualysVmdrRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=_rate_limit_wait,+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> Element:+ # stream=True so the body isn't buffered until we cap it — see _read_capped_body.+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS, stream=True)++ # Qualys signals per-subscription rate/concurrency limits with 409 plus X-RateLimit /+ # X-Concurrency headers telling us how long to wait. Close before raising so the connection is+ # released without pulling the (unneeded) body.+ if response.status_code in (409, 429) or response.status_code >= 500:+ response.close()+ wait_seconds: int | None = None+ for header in ("X-RateLimit-ToWait-Sec", "Retry-After"):+ raw_wait = response.headers.get(header)+ if raw_wait and raw_wait.isdigit():+ wait_seconds = int(raw_wait)+ break+ raise QualysVmdrRetryableError(+ f"Qualys API error (retryable): status={response.status_code}, url={response.url}",+ wait_seconds=wait_seconds,+ )++ body = _read_capped_body(response)+ text = body.decode(response.encoding or "utf-8", errors="replace")++ if not response.ok:+ logger.error(f"Qualys API error: status={response.status_code}, body={text[:2000]}")+ response.raise_for_status()++ root = _parse_xml(text)++ # Parameter/permission errors come back as HTTP 200 with a SIMPLE_RETURN error document.+ if root.tag == "SIMPLE_RETURN":+ error_text = root.findtext(".//TEXT") or "unknown error"+ raise ValueError(f"Qualys API returned an error: {error_text}")++ return root+++def _element_to_value(element: Element) -> Any:+ """Recursively convert an XML element to text, or a dict/list structure for nested elements."""+ children = list(element)+ if not children:+ return element.text++ result: dict[str, Any] = {}+ for child in children:+ key = child.tag.lower()+ value = _element_to_value(child)+ if key in result:+ if not isinstance(result[key], list):+ result[key] = [result[key]]+ result[key].append(value)+ else:+ result[key] = value+ return result+++def _element_to_row(element: Element, skip_tags: set[str] | None = None) -> dict[str, Any]:+ """Convert one record element to a flat row dict.++ Scalar children become string columns. Nested children (CVE_LIST, DNS_DATA, TAGS, ...) are+ JSON-encoded: element repetition varies per record (one CVE vs many), so materializing them+ as native structs would produce conflicting Arrow types within a batch.+ """+ row: dict[str, Any] = {}+ for child in element:+ key = child.tag.lower()+ if skip_tags and child.tag in skip_tags:+ continue+ value = _element_to_value(child)+ row[key] = json.dumps(value) if isinstance(value, dict | list) else value+ return row+++def _extract_rows(root: Element, config: QualysVmdrEndpointConfig) -> Iterator[dict[str, Any]]:+ for item in root.iter(config.item_tag):+ if not config.flatten_host_detections:+ yield _element_to_row(item)+ continue++ # One row per (host, detection): host scalars prefixed host_* merged with the+ # detection's own fields. `unique_vuln_id` is the subscription-wide detection id.+ host_fields = {+ f"host_{key}": value for key, value in _element_to_row(item, skip_tags={"DETECTION_LIST"}).items()+ }+ for detection in item.iter("DETECTION"):+ yield {**host_fields, **_element_to_row(detection)}+++def _next_batch_url(root: Element, base_url: str) -> str | None:+ """Resolve the truncation WARNING's next-batch URL, re-rooted onto the configured server.++ When a response is truncated, Qualys returns a WARNING block whose URL carries the same+ params plus an advanced id_min. The URL is re-rooted onto the user-configured API server so+ credentials are only ever sent to the host the user supplied.+ """+ warning_url = root.findtext(".//WARNING/URL")+ if not warning_url:+ return None+ next_parts = urlsplit(warning_url.strip())+ base_parts = urlsplit(base_url)+ return urlunsplit((base_parts.scheme, base_parts.netloc, next_parts.path, next_parts.query, ""))+++def _build_initial_url(+ base_url: str,+ config: QualysVmdrEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> str:+ params: dict[str, str] = dict(config.params)+ if config.truncation_limit:+ params["truncation_limit"] = str(config.truncation_limit)+ if should_use_incremental_field and db_incremental_field_last_value is not None and config.incremental_param:+ params[config.incremental_param] = _format_since_value(db_incremental_field_last_value)+ return f"{base_url}{config.path}?{urlencode(params)}"+++def get_rows(+ api_server: str,+ username: str,+ password: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[QualysVmdrResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = QUALYS_VMDR_ENDPOINTS[endpoint]+ base_url = build_base_url(api_server)+ # Re-validate on every sync, not just at source creation: the stored api_server can be+ # edited after the credential was saved.+ _check_url_allowed(base_url)+ session = _make_session(username, password)++ 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"Qualys VMDR: resuming from URL: {url}")+ else:+ url = _build_initial_url(base_url, config, should_use_incremental_field, db_incremental_field_last_value)++ while True:+ root = _fetch_page(session, url, logger)+ rows = list(_extract_rows(root, config))+ next_url = _next_batch_url(root, base_url)++ if rows:+ yield rows++ if not next_url:+ break++ # Save AFTER yielding so a crash re-yields the last batch (merge dedupes on the primary+ # key) rather than skipping it.+ resumable_source_manager.save_state(QualysVmdrResumeConfig(next_url=next_url))+ url = next_url+++def validate_credentials(api_server: str, username: str, password: str) -> tuple[bool, str | None]:+ """Cheap create-time probe: one host-list request capped at a single record.++ 403 is accepted — the credential authenticated but lacks the asset-listing scope; per-table+ scope problems surface at sync time. 409 (rate/concurrency limited) also proves the+ credential is genuine.+ """+ base_url = build_base_url(api_server)+ allowed, reason = is_url_allowed(base_url)+ if not allowed:+ return False, f"Qualys API server URL is not allowed: {reason}"++ url = f"{base_url}/api/2.0/fo/asset/host/?{urlencode({'action': 'list', 'truncation_limit': 1})}"+ try:+ # stream=True so a user-controlled host can't force us to buffer an unbounded probe body:+ # we only ever inspect the status line here, never the body.+ response = _make_session(username, password).get(url, timeout=30, stream=True)+ except Exception:+ return False, "Could not connect to the Qualys API server"++ try:+ if response.status_code in (200, 403, 409):+ return True, None+ return False, "Invalid Qualys credentials or API server URL"+ finally:+ response.close()+++def qualys_vmdr_source(+ api_server: str,+ username: str,+ password: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[QualysVmdrResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = QUALYS_VMDR_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_server=api_server,+ username=username,+ password=password,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=endpoint_config.primary_keys,+ # Batches are ordered by record id (id_min paging), not by the incremental datetime, so+ # the watermark must only persist at successful job end — never per batch.+ sort_mode="desc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" 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/qualys_vmdr/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/settings.pynew file mode 100644index 000000000000..19ef92f4595d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/settings.py@@ -0,0 +1,119 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class QualysVmdrEndpointConfig:+ name: str+ path: str # e.g. "/api/2.0/fo/asset/host/"+ item_tag: str # element tag of one record in the XML response (e.g. "HOST")+ # Static query params sent on every request (the FO API routes on `action=list`).+ params: dict[str, str] = field(default_factory=dict)+ # Server-side "since" filter param for incremental syncs (None = full refresh only).+ incremental_param: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Field to partition by — must be a STABLE field (first_found/launch style, never last_*).+ partition_key: Optional[str] = None+ # Records per truncated batch; None for endpoints that don't accept truncation_limit.+ truncation_limit: Optional[int] = None+ # Flatten each HOST's DETECTION_LIST into one row per detection (Host List Detection only).+ flatten_host_detections: bool = False+ should_sync_default: bool = True+++QUALYS_VMDR_ENDPOINTS: dict[str, QualysVmdrEndpointConfig] = {+ # Asset inventory: one row per host in the subscription. `vm_scan_since` is a server-side+ # filter on the host's last VM scan datetime, so incremental syncs only pick up hosts that+ # have been (re)scanned since the watermark.+ "hosts": QualysVmdrEndpointConfig(+ name="hosts",+ path="/api/2.0/fo/asset/host/",+ item_tag="HOST",+ params={"action": "list", "details": "All"},+ incremental_param="vm_scan_since",+ incremental_fields=[+ {+ "label": "last_vuln_scan_datetime",+ "type": IncrementalFieldType.DateTime,+ "field": "last_vuln_scan_datetime",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ primary_keys=["id"],+ truncation_limit=1000,+ ),+ # The core VMDR feed: one row per (host, detection). `detection_updated_since` is a+ # server-side filter on the detection's last update, so incremental syncs re-pull rows whose+ # status/severity changed. Lower truncation limit than the other endpoints because each host+ # record carries its full detection list (including RESULTS text).+ "host_list_detection": QualysVmdrEndpointConfig(+ name="host_list_detection",+ path="/api/2.0/fo/asset/host/vm/detection/",+ item_tag="HOST",+ params={"action": "list"},+ incremental_param="detection_updated_since",+ incremental_fields=[+ {+ "label": "last_update_datetime",+ "type": IncrementalFieldType.DateTime,+ "field": "last_update_datetime",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ primary_keys=["unique_vuln_id"],+ partition_key="first_found_datetime",+ truncation_limit=500,+ flatten_host_detections=True,+ ),+ # VM scan history. The scan list endpoint has no truncation pagination — it returns every+ # scan matching the filters in one response — so incremental filtering on launch datetime+ # is what keeps ongoing syncs cheap.+ "scans": QualysVmdrEndpointConfig(+ name="scans",+ path="/api/2.0/fo/scan/",+ item_tag="SCAN",+ params={"action": "list"},+ incremental_param="launched_after_datetime",+ incremental_fields=[+ {+ "label": "launch_datetime",+ "type": IncrementalFieldType.DateTime,+ "field": "launch_datetime",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ primary_keys=["ref"],+ partition_key="launch_datetime",+ truncation_limit=None,+ ),+ # Vulnerability definitions (QIDs). Requires the "KnowledgeBase download" option enabled on+ # the Qualys subscription, so it's off by default. `details=Basic` keeps rows compact+ # (skips the large DIAGNOSIS/CONSEQUENCE/SOLUTION HTML blobs).+ "knowledge_base": QualysVmdrEndpointConfig(+ name="knowledge_base",+ path="/api/2.0/fo/knowledge_base/vuln/",+ item_tag="VULN",+ params={"action": "list", "details": "Basic"},+ incremental_param="last_modified_after",+ incremental_fields=[+ {+ "label": "last_service_modification_datetime",+ "type": IncrementalFieldType.DateTime,+ "field": "last_service_modification_datetime",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ primary_keys=["qid"],+ truncation_limit=None,+ should_sync_default=False,+ ),+}++ENDPOINTS = tuple(QUALYS_VMDR_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in QUALYS_VMDR_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/source.pyindex 633c6b25a91a..9bb8480ced46 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/source.py@@ -1,30 +1,171 @@-from typing import cast+from typing import Optional, castfrom 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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import QualysVmdrSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.qualys_vmdr.qualys_vmdr import (+ QualysVmdrResumeConfig,+ qualys_vmdr_source,+ validate_credentials as validate_qualys_vmdr_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.qualys_vmdr.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ QUALYS_VMDR_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class QualysVmdrSource(SimpleSource[QualysVmdrSourceConfig]):+class QualysVmdrSource(ResumableSource[QualysVmdrSourceConfig, QualysVmdrResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.QUALYSVMDR+ @property+ def connection_host_fields(self) -> list[str]:+ # `api_server` is where the stored username/password are sent; retargeting it must+ # re-require the credentials.+ return ["api_server"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.QUALYS_VMDR,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- label="Qualys, Inc. (Qualys VMDR)",+ label="Qualys VMDR",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["qualys", "vmdr", "vulnerability management", "security"],+ caption="""Enter your Qualys API credentials to sync your VMDR vulnerability management data into the PostHog Data warehouse.++Use your account's regional API server URL (for example `qualysapi.qualys.com`, `qualysapi.qg2.apps.qualys.com`, or `qualysapi.qualys.eu`) — you can find it under **Help > About** in the Qualys UI. The user needs API access enabled (a Manager role, or a role granted API access).++The `knowledge_base` table additionally requires the KnowledgeBase download option to be enabled on your Qualys subscription.""",iconPath="/static/services/qualys_vmdr.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/qualys-vmdr",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_server",+ label="API server URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="qualysapi.qualys.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="username",+ label="Username",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="password",+ label="Password",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.qualys_vmdr.canonical_descriptions import ( # noqa: PLC0415 — lazy sibling import per the canonical-descriptions pattern+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # The API server host is user-configured, so match on the stable status text only.+ return {+ "401 Client Error": "Your Qualys credentials are invalid or the account is locked. Check the username and password and reconnect.",+ "403 Client Error": "Your Qualys user does not have API access to this data. Grant the user API access (or the required module permissions) and reconnect.",+ "Unauthorized for url": "Your Qualys credentials are invalid or the account is locked. Check the username and password and reconnect.",+ "Qualys API server URL is not allowed": "The configured API server URL points at a blocked or internal address. Set it to your Qualys account's regional API server and reconnect.",+ "Qualys API response body was too large": "The Qualys API server returned an unexpectedly large response. Confirm the configured API server URL points at your Qualys account's regional API server and reconnect.",+ "Qualys API response download was too slow": "The Qualys API server was too slow to return a response. Confirm the configured API server URL points at your Qualys account's regional API server and reconnect.",+ }++ def get_schemas(+ self,+ config: QualysVmdrSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ if endpoint == "knowledge_base":+ return "Requires the KnowledgeBase download option enabled on your Qualys subscription"+ return None++ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ # Every endpoint re-pulls updated versions of existing rows (rescanned hosts,+ # updated detections, edited scans/QIDs), so append would materialize duplicates.+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=QUALYS_VMDR_ENDPOINTS[endpoint].should_sync_default,+ description=_description(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: QualysVmdrSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_qualys_vmdr_credentials(config.api_server, config.username, config.password)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[QualysVmdrResumeConfig]:+ return ResumableSourceManager[QualysVmdrResumeConfig](inputs, QualysVmdrResumeConfig)++ def source_for_pipeline(+ self,+ config: QualysVmdrSourceConfig,+ resumable_source_manager: ResumableSourceManager[QualysVmdrResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return qualys_vmdr_source(+ api_server=config.api_server,+ username=config.username,+ password=config.password,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/tests/test_qualys_vmdr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/tests/test_qualys_vmdr.pynew file mode 100644index 000000000000..105049dd03c6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/tests/test_qualys_vmdr.py@@ -0,0 +1,346 @@+import json+from datetime import UTC, date, datetime+from typing import cast++import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.qualys_vmdr.qualys_vmdr import (+ QualysVmdrResponseTooLargeError,+ QualysVmdrResumeConfig,+ QualysVmdrRetryableError,+ _build_initial_url,+ _extract_rows,+ _fetch_page,+ _next_batch_url,+ _parse_xml,+ _read_capped_body,+ build_base_url,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.qualys_vmdr.settings import QUALYS_VMDR_ENDPOINTS++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.qualys_vmdr.qualys_vmdr"++# tenacity exposes the undecorated function via `__wrapped__`, so status classification can be+# asserted without sitting through retry backoff.+_fetch_page_unwrapped = _fetch_page.__wrapped__ # type: ignore[attr-defined]++HOST_LIST_PAGE_1 = """<?xml version="1.0" encoding="UTF-8" ?>+<HOST_LIST_OUTPUT>+ <RESPONSE>+ <DATETIME>2026-07-15T00:00:00Z</DATETIME>+ <HOST_LIST>+ <HOST>+ <ID>1001</ID>+ <IP>10.0.0.1</IP>+ <TRACKING_METHOD>IP</TRACKING_METHOD>+ <LAST_VULN_SCAN_DATETIME>2026-07-01T10:00:00Z</LAST_VULN_SCAN_DATETIME>+ <TAGS>+ <TAG>+ <TAG_ID>1</TAG_ID>+ <NAME>prod</NAME>+ </TAG>+ <TAG>+ <TAG_ID>2</TAG_ID>+ <NAME>web</NAME>+ </TAG>+ </TAGS>+ </HOST>+ </HOST_LIST>+ <WARNING>+ <CODE>1980</CODE>+ <TEXT>1 record limit exceeded. Use URL to get next batch of results.</TEXT>+ <URL><![CDATA[https://qualysapi.qualys.com/api/2.0/fo/asset/host/?action=list&details=All&truncation_limit=1000&id_min=1002]]></URL>+ </WARNING>+ </RESPONSE>+</HOST_LIST_OUTPUT>"""++HOST_LIST_PAGE_2 = """<?xml version="1.0" encoding="UTF-8" ?>+<HOST_LIST_OUTPUT>+ <RESPONSE>+ <DATETIME>2026-07-15T00:00:01Z</DATETIME>+ <HOST_LIST>+ <HOST>+ <ID>1002</ID>+ <IP>10.0.0.2</IP>+ </HOST>+ </HOST_LIST>+ </RESPONSE>+</HOST_LIST_OUTPUT>"""++DETECTION_PAGE = """<?xml version="1.0" encoding="UTF-8" ?>+<HOST_LIST_VM_DETECTION_OUTPUT>+ <RESPONSE>+ <DATETIME>2026-07-15T00:00:00Z</DATETIME>+ <HOST_LIST>+ <HOST>+ <ID>1001</ID>+ <IP>10.0.0.1</IP>+ <DETECTION_LIST>+ <DETECTION>+ <UNIQUE_VULN_ID>111</UNIQUE_VULN_ID>+ <QID>38170</QID>+ <STATUS>Active</STATUS>+ <FIRST_FOUND_DATETIME>2026-01-01T00:00:00Z</FIRST_FOUND_DATETIME>+ <LAST_UPDATE_DATETIME>2026-07-01T00:00:00Z</LAST_UPDATE_DATETIME>+ </DETECTION>+ <DETECTION>+ <UNIQUE_VULN_ID>112</UNIQUE_VULN_ID>+ <QID>91234</QID>+ <STATUS>New</STATUS>+ </DETECTION>+ </DETECTION_LIST>+ </HOST>+ </HOST_LIST>+ </RESPONSE>+</HOST_LIST_VM_DETECTION_OUTPUT>"""++SIMPLE_RETURN_ERROR = """<?xml version="1.0" encoding="UTF-8" ?>+<SIMPLE_RETURN>+ <RESPONSE>+ <DATETIME>2026-07-15T00:00:00Z</DATETIME>+ <CODE>2011</CODE>+ <TEXT>Bad parameter value</TEXT>+ </RESPONSE>+</SIMPLE_RETURN>"""+++def _response(status_code: int = 200, text: str = "", headers: dict[str, str] | None = None) -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.text = text+ response.encoding = "utf-8"+ # _fetch_page reads the body via stream=True + iter_content, not response.text.+ response.iter_content.return_value = iter([text.encode("utf-8")]) if text else iter([])+ response.headers = headers or {}+ response.url = "https://qualysapi.qualys.com/api/2.0/fo/asset/host/"+ return response+++class _FakeManager:+ def __init__(self, state: QualysVmdrResumeConfig | None = None):+ self.state = state+ self.saved: list[QualysVmdrResumeConfig] = []++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> QualysVmdrResumeConfig | None:+ return self.state++ def save_state(self, data: QualysVmdrResumeConfig) -> None:+ self.saved.append(data)++ def as_manager(self) -> ResumableSourceManager[QualysVmdrResumeConfig]:+ return cast(ResumableSourceManager[QualysVmdrResumeConfig], self)+++class TestQualysVmdr:+ @pytest.mark.parametrize(+ "api_server,expected",+ [+ ("qualysapi.qualys.com", "https://qualysapi.qualys.com"),+ ("https://qualysapi.qualys.eu/", "https://qualysapi.qualys.eu"),+ ("http://qualysapi.qg2.apps.qualys.com", "https://qualysapi.qg2.apps.qualys.com"),+ (" qualysapi.qualys.ca ", "https://qualysapi.qualys.ca"),+ ],+ )+ def test_build_base_url_normalizes_and_forces_https(self, api_server, expected):+ assert build_base_url(api_server) == expected++ @pytest.mark.parametrize(+ "value,expected_param",+ [+ (datetime(2026, 7, 1, 10, 30, 0, tzinfo=UTC), "vm_scan_since=2026-07-01T10%3A30%3A00Z"),+ (date(2026, 7, 1), "vm_scan_since=2026-07-01T00%3A00%3A00Z"),+ ],+ )+ def test_initial_url_includes_incremental_filter(self, value, expected_param):+ url = _build_initial_url("https://example.com", QUALYS_VMDR_ENDPOINTS["hosts"], True, value)+ assert expected_param in url+ assert "truncation_limit=1000" in url++ def test_initial_url_full_refresh_has_no_incremental_filter(self):+ url = _build_initial_url("https://example.com", QUALYS_VMDR_ENDPOINTS["hosts"], False, None)+ assert "vm_scan_since" not in url++ def test_initial_url_omits_truncation_limit_when_endpoint_does_not_support_it(self):+ url = _build_initial_url("https://example.com", QUALYS_VMDR_ENDPOINTS["scans"], False, None)+ assert "truncation_limit" not in url+ assert url.startswith("https://example.com/api/2.0/fo/scan/?")++ def test_extract_rows_lowercases_scalars_and_json_encodes_nested(self):+ root = _parse_xml(HOST_LIST_PAGE_1)+ rows = list(_extract_rows(root, QUALYS_VMDR_ENDPOINTS["hosts"]))++ assert len(rows) == 1+ assert rows[0]["id"] == "1001"+ assert rows[0]["last_vuln_scan_datetime"] == "2026-07-01T10:00:00Z"+ # Repeated nested elements are JSON strings, not structs (arrow type stability)+ tags = json.loads(rows[0]["tags"])+ assert [t["name"] for t in tags["tag"]] == ["prod", "web"]++ def test_extract_detection_rows_flatten_one_row_per_detection_with_host_prefix(self):+ root = _parse_xml(DETECTION_PAGE)+ rows = list(_extract_rows(root, QUALYS_VMDR_ENDPOINTS["host_list_detection"]))++ assert [row["unique_vuln_id"] for row in rows] == ["111", "112"]+ assert all(row["host_id"] == "1001" and row["host_ip"] == "10.0.0.1" for row in rows)+ assert rows[0]["last_update_datetime"] == "2026-07-01T00:00:00Z"+ # The host's DETECTION_LIST must not leak into the flattened row+ assert "host_detection_list" not in rows[0]++ def test_parse_xml_tolerates_keepalive_whitespace(self):+ root = _parse_xml("\n \n" + HOST_LIST_PAGE_2)+ assert root.tag == "HOST_LIST_OUTPUT"++ def test_next_batch_url_is_rerooted_onto_configured_server(self):+ root = _parse_xml(HOST_LIST_PAGE_1)+ next_url = _next_batch_url(root, "https://qualysapi.qualys.eu")++ assert next_url is not None+ assert next_url.startswith("https://qualysapi.qualys.eu/api/2.0/fo/asset/host/?")+ assert "id_min=1002" in next_url++ def test_next_batch_url_none_without_warning(self):+ assert _next_batch_url(_parse_xml(HOST_LIST_PAGE_2), "https://example.com") is None++ def test_get_rows_paginates_and_saves_state_after_yield(self):+ manager = _FakeManager()+ session = mock.MagicMock()+ session.get.side_effect = [_response(text=HOST_LIST_PAGE_1), _response(text=HOST_LIST_PAGE_2)]++ with (+ mock.patch(f"{_MODULE}._make_session", return_value=session),+ mock.patch(f"{_MODULE}.is_url_allowed", return_value=(True, None)),+ ):+ generator = get_rows(+ "qualysapi.qualys.com", "user", "pass", "hosts", mock.MagicMock(), manager.as_manager()+ )++ first_batch = next(generator)+ assert [row["id"] for row in first_batch] == ["1001"]+ # State is saved only once the consumer resumes after the yield — a crash while the+ # batch is being processed re-yields it instead of skipping it+ assert len(manager.saved) == 0++ second_batch = next(generator)+ assert [row["id"] for row in second_batch] == ["1002"]+ assert len(manager.saved) == 1+ assert "id_min=1002" in manager.saved[0].next_url+ with pytest.raises(StopIteration):+ next(generator)++ # No further state saved for the final page+ assert len(manager.saved) == 1++ def test_get_rows_resumes_from_saved_state(self):+ resume_url = "https://qualysapi.qualys.com/api/2.0/fo/asset/host/?action=list&id_min=1002"+ manager = _FakeManager(state=QualysVmdrResumeConfig(next_url=resume_url))+ session = mock.MagicMock()+ session.get.return_value = _response(text=HOST_LIST_PAGE_2)++ with (+ mock.patch(f"{_MODULE}._make_session", return_value=session),+ mock.patch(f"{_MODULE}.is_url_allowed", return_value=(True, None)),+ ):+ batches = list(+ get_rows("qualysapi.qualys.com", "user", "pass", "hosts", mock.MagicMock(), manager.as_manager())+ )++ assert session.get.call_args[0][0] == resume_url+ assert [row["id"] for row in batches[0]] == ["1002"]++ def test_get_rows_rejects_disallowed_api_server_before_any_request(self):+ session = mock.MagicMock()++ with (+ mock.patch(f"{_MODULE}._make_session", return_value=session),+ mock.patch(f"{_MODULE}.is_url_allowed", return_value=(False, "URL resolves to a private IP")),+ ):+ with pytest.raises(ValueError, match="Qualys API server URL is not allowed"):+ list(+ get_rows("169.254.169.254", "user", "pass", "hosts", mock.MagicMock(), _FakeManager().as_manager())+ )++ session.get.assert_not_called()++ def test_fetch_page_rate_limit_carries_server_wait(self):+ session = mock.MagicMock()+ session.get.return_value = _response(status_code=409, headers={"X-RateLimit-ToWait-Sec": "42"})++ with pytest.raises(QualysVmdrRetryableError) as exc_info:+ _fetch_page_unwrapped(session, "https://example.com", mock.MagicMock())++ assert exc_info.value.wait_seconds == 42++ def test_read_capped_body_refuses_bodies_over_the_size_cap(self):+ # A user-controlled host must not be able to make us buffer an unbounded body — the cap+ # aborts the read (and closes the response) instead of holding it all in memory.+ response = mock.MagicMock()+ response.iter_content.return_value = iter([b"a" * 1024, b"b" * 1024])++ with mock.patch(f"{_MODULE}.MAX_RESPONSE_BYTES", 1500):+ with pytest.raises(QualysVmdrResponseTooLargeError):+ _read_capped_body(response)++ response.close.assert_called_once()++ def test_fetch_page_raises_on_simple_return_error_document(self):+ session = mock.MagicMock()+ session.get.return_value = _response(text=SIMPLE_RETURN_ERROR)++ with pytest.raises(ValueError, match="Bad parameter value"):+ _fetch_page_unwrapped(session, "https://example.com", mock.MagicMock())++ @pytest.mark.parametrize(+ "status_code,expected",+ [+ (200, True),+ (403, True), # authenticated but missing the asset-list scope — still a valid credential+ (409, True), # rate limited — the credential authenticated+ (401, False),+ ],+ )+ def test_validate_credentials_status_mapping(self, status_code, expected):+ session = mock.MagicMock()+ session.get.return_value = _response(status_code=status_code, text="<x/>")++ with (+ mock.patch(f"{_MODULE}._make_session", return_value=session),+ mock.patch(f"{_MODULE}.is_url_allowed", return_value=(True, None)),+ ):+ ok, error = validate_credentials("qualysapi.qualys.com", "user", "pass")++ assert ok is expected+ assert (error is None) is expected++ def test_validate_credentials_false_on_connection_error(self):+ session = mock.MagicMock()+ session.get.side_effect = ConnectionError("dns failure")++ with (+ mock.patch(f"{_MODULE}._make_session", return_value=session),+ mock.patch(f"{_MODULE}.is_url_allowed", return_value=(True, None)),+ ):+ ok, error = validate_credentials("nonexistent.example.com", "user", "pass")++ assert ok is False+ assert error is not None++ def test_validate_credentials_rejects_disallowed_api_server_before_any_request(self):+ session = mock.MagicMock()++ with (+ mock.patch(f"{_MODULE}._make_session", return_value=session),+ mock.patch(f"{_MODULE}.is_url_allowed", return_value=(False, "URL resolves to a private IP")),+ ):+ ok, error = validate_credentials("localhost", "user", "pass")++ assert ok is False+ assert error is not None and "not allowed" in error+ session.get.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/tests/test_qualys_vmdr_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/tests/test_qualys_vmdr_source.pynew file mode 100644index 000000000000..7802c1f2913c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qualys_vmdr/tests/test_qualys_vmdr_source.py@@ -0,0 +1,102 @@+import pytest+from unittest import mock++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 QualysVmdrSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.qualys_vmdr.qualys_vmdr import (+ QualysVmdrResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.qualys_vmdr.source import QualysVmdrSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.qualys_vmdr.source"+++def _config() -> QualysVmdrSourceConfig:+ return QualysVmdrSourceConfig(api_server="qualysapi.qualys.com", username="user", password="pass")+++def _inputs(**overrides) -> mock.MagicMock:+ inputs = mock.MagicMock()+ inputs.schema_name = overrides.get("schema_name", "hosts")+ inputs.should_use_incremental_field = overrides.get("should_use_incremental_field", False)+ inputs.db_incremental_field_last_value = overrides.get("db_incremental_field_last_value", None)+ return inputs+++class TestQualysVmdrSource:+ def setup_method(self):+ self.source = QualysVmdrSource()++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.QUALYSVMDR++ def test_source_is_released(self):+ config = self.source.get_source_config+ assert not config.unreleasedSource++ def test_api_server_is_a_connection_host_field(self):+ # Retargeting `api_server` must force re-entry of the stored credentials+ assert "api_server" in self.source.connection_host_fields++ def test_get_schemas(self):+ schemas = {s.name: s for s in self.source.get_schemas(_config(), team_id=1)}++ assert set(schemas.keys()) == {"hosts", "host_list_detection", "scans", "knowledge_base"}+ assert all(s.supports_incremental for s in schemas.values())+ # Every endpoint re-pulls updated rows, so append mode would materialize duplicates+ assert all(not s.supports_append for s in schemas.values())+ # KnowledgeBase needs a subscription add-on, so it must not be on by default+ assert not schemas["knowledge_base"].should_sync_default++ def test_get_schemas_filters_by_names(self):+ schemas = self.source.get_schemas(_config(), team_id=1, names=["scans"])+ assert [s.name for s in schemas] == ["scans"]++ @pytest.mark.parametrize(+ "transport_result",+ [(True, None), (False, "Invalid Qualys credentials or API server URL")],+ )+ def test_validate_credentials(self, transport_result):+ with mock.patch(f"{_MODULE}.validate_qualys_vmdr_credentials", return_value=transport_result) as validate:+ result = self.source.validate_credentials(_config(), team_id=1)++ assert result == transport_result+ validate.assert_called_once_with("qualysapi.qualys.com", "user", "pass")++ def test_get_resumable_source_manager_binds_resume_config(self):+ manager = self.source.get_resumable_source_manager(_inputs())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is QualysVmdrResumeConfig++ @pytest.mark.parametrize(+ "endpoint,expected_primary_keys,expected_partition_keys",+ [+ ("hosts", ["id"], None),+ ("host_list_detection", ["unique_vuln_id"], ["first_found_datetime"]),+ ("scans", ["ref"], ["launch_datetime"]),+ ("knowledge_base", ["qid"], None),+ ],+ )+ def test_source_for_pipeline_response_shape(self, endpoint, expected_primary_keys, expected_partition_keys):+ manager = mock.MagicMock()+ response = self.source.source_for_pipeline(_config(), manager, _inputs(schema_name=endpoint))++ assert response.name == endpoint+ assert response.primary_keys == expected_primary_keys+ assert response.partition_keys == expected_partition_keys+ # Rows arrive in record-id order, not incremental-field order — the watermark must only+ # persist at successful job end+ assert response.sort_mode == "desc"++ def test_source_for_pipeline_ignores_watermark_when_incremental_disabled(self):+ with mock.patch(f"{_MODULE}.qualys_vmdr_source") as transport:+ inputs = _inputs(should_use_incremental_field=False, db_incremental_field_last_value="2026-01-01")+ self.source.source_for_pipeline(_config(), mock.MagicMock(), inputs)++ assert transport.call_args.kwargs["db_incremental_field_last_value"] is None++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error", "Unauthorized for url"])+ def test_non_retryable_errors(self, expected_key):+ assert expected_key in self.source.get_non_retryable_errors()