: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(warehouse_sources): support Qualys VMDR API version 4.0 (#80101)
Tom Owers4bae309cc8ba
diff --git a/.agents/skills/warehouse-source-new-version/SKILL.md b/.agents/skills/warehouse-source-new-version/SKILL.mdindex 31af03c42b3b..007e9e110b53 100644--- a/.agents/skills/warehouse-source-new-version/SKILL.md+++ b/.agents/skills/warehouse-source-new-version/SKILL.md@@ -50,6 +50,7 @@ Add it when any of these hold:3. **Dispatch on `SourceInputs.api_version`** at the request layer:- Keep it minimal. If the version is just a header/URL segment and response shapes are compatible, thread the version string down to where the client/URL is built (see Stripe: `StripeSource.source_for_pipeline` passes `self.resolve_api_version(inputs.api_version)` → `stripe_source(...)` → `StripeClient(stripe_version=...)`). Resolve through `resolve_api_version` at the source class — never hardcode a fallback version in the request layer.- Only introduce per-version modules/branches where behavior genuinely diverges (different pagination, different field mapping). Keep all version branching inside the source's own directory — never in shared layers.+ - A source can front several vendor API families versioned on independent tracks, so a source-level bump may move only a subset of its endpoints (and change auth for just those) — dispatch path and auth per endpoint against the resolved pin, leave the rest on their existing wire, and keep the table set identical, rather than rewriting every endpoint to the new label.- When the new version renames endpoints, changes primary keys, or reshapes responses, the divergence must actually be branched — never leave the old single-version request path serving the new default. All the relevant surfaces can vary by version: `get_rows` receives the resolved pin in `inputs.api_version`; credential fields can key off `default_version`.- Conversely, don't add inert scaffolding: an `api_version` param no caller varies, or a version→URL map with identical values, is a review finding, not forward-compat. Declaration-only (`supported_versions`/`default_version` and nothing else) is the correct shape just when the gate above passed on a non-wire reason — the old label is being retired, the vendor switches behavior account-side rather than per request, or the source already reads the vendor's newest generation under the framework's legacy unversioned label (verify the request paths the source actually builds, not the label — a legacy label can already ride the new wire, so the new label just formalizes it for new rows and both resolve identically). If the gate passed on nothing at all, there is no PR. When no-header requests resolve to a version bound to the credential account-side (not a moving "latest"), threading a version header is not merely inert — it overrides the customer's chosen version, the silent move this framework exists to prevent — so stay declaration-only and don't send one.- **Discovery and probe paths receive the pin — consume it.** The framework passes the resolved pin as the `api_version` parameter of `get_schemas`, `validate_credentials`, `get_endpoint_permissions`, and the webhook management methods. A multi-version source MUST build its discovery/probe/webhook clients from that parameter, not from `default_version` or a hardcoded header — otherwise a pinned source discovers/reconciles under the wrong version and its tables can disappear, duplicate, or fail reconciliation. Resolve it with `self.resolve_api_version(api_version)` — callers with a row pass an already-resolved value (mirroring `SourceInputs.api_version`), so the source-side resolve only covers pre-creation calls that pass `None`. Ignoring the parameter is only correct when you can state why the version makes no difference to that path.diff --git a/products/warehouse_sources/backend/migrations/0127_pin_qualys_vmdr_null_api_version_to_2_0.py b/products/warehouse_sources/backend/migrations/0127_pin_qualys_vmdr_null_api_version_to_2_0.pynew file mode 100644index 000000000000..3d777c77fea9--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0127_pin_qualys_vmdr_null_api_version_to_2_0.py@@ -0,0 +1,38 @@+from django.db import migrations++# Qualys VMDR's default vendor API version flips to "4.0" in the same change that adds this+# migration. Existing rows were pinned "2.0" by migration 0075, but a row created via a direct-ORM+# path that bypasses creation-time stamping could still have a NULL `api_version`, and a NULL pin+# resolves to `default_version` — so it would silently follow the flip to 4.0. On 4.0 the+# knowledge_base table authenticates with a gateway-minted JWT (a gateway URL the stored basic-auth+# credentials don't carry), so an unpinned source moved to 4.0 would fail that table. Pin any such+# rows back to "2.0" so the flip only affects newly created sources.+#+# This does NOT repin "2.0" customers to "4.0": that migration is not safe to script (4.0 needs a+# gateway URL that can't be derived from the stored credentials), so it is documented as a manual+# path in the PR. Only the source-level pin is touched — schema-level `ExternalDataSchema.api_version`+# overrides are user-managed (a customer intentionally pinned that schema) and are left alone; the+# schema-level deprecation warning prompts the user to migrate those.+QUALYS_VMDR_SOURCE_TYPE = "QualysVmdr"+QUALYS_VMDR_API_VERSION_2_0 = "2.0"+++def pin_null_qualys_vmdr_rows_to_2_0(apps, schema_editor):+ ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")++ # The isnull guard keeps it idempotent (safe under retries) and never overwrites a concrete pin.+ ExternalDataSource.objects.filter(source_type=QUALYS_VMDR_SOURCE_TYPE, api_version__isnull=True).update(+ api_version=QUALYS_VMDR_API_VERSION_2_0+ )+++class Migration(migrations.Migration):+ dependencies = [+ ("warehouse_sources", "0126_oom_created_idx"),+ ]++ operations = [+ # Reverse is a no-op: after this runs, the pinned rows are indistinguishable from natively+ # created 2.0 sources, so nulling "2.0" pins would also destroy legitimate creation-time stamps.+ migrations.RunPython(pin_null_qualys_vmdr_rows_to_2_0, migrations.RunPython.noop, elidable=True),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex 4f861e2dfb55..68c5845f2cdc 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0126_oom_created_idx+0127_pin_qualys_vmdr_null_api_version_to_2_0diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/qualysvmdr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/qualysvmdr.pyindex ff066268eaea..b15153e65ac7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/qualysvmdr.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/qualysvmdr.py@@ -9,3 +9,4 @@ class QualysVmdrSourceConfig(config.Config):api_server: strusername: strpassword: str+ gateway_server: str | None = Nonediff --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.pyindex 19847cdf2571..4d844fd22156 100644--- 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.py@@ -41,8 +41,17 @@ RESPONSE_CHUNK_BYTES = 256 * 1024# and far above a slow-drip stall.MAX_DOWNLOAD_SECONDS = 300+# The gateway /auth body is a single JWT (a few KiB at most), so it gets far tighter caps than a+# data page. The gateway server is user-supplied too, so the same unbounded-buffering and+# slow-drip concerns apply — a token exchange just has no legitimate reason to be big or slow.+MAX_JWT_RESPONSE_BYTES = 64 * 1024+MAX_JWT_DOWNLOAD_SECONDS = 30+RESPONSE_TOO_LARGE_ERROR = "Qualys API response body was too large"RESPONSE_TOO_SLOW_ERROR = "Qualys API response download was too slow"+# Raised when a JWT-authenticated endpoint (KnowledgeBase on 4.0) is synced but no gateway URL is+# configured — the token can't be minted without it. Non-retryable: retrying can't create the field.+MISSING_GATEWAY_ERROR = "Qualys API gateway URL is required for API version 4.0"# Qualys rejects any request without an X-Requested-With header._BASE_HEADERS = {"X-Requested-With": "PostHog Data Warehouse"}@@ -62,30 +71,35 @@ 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.+def _read_capped_body(+ response: requests.Response,+ max_bytes: int | None = None,+ max_seconds: int | None = None,+) -> bytes:+ """Stream the body into memory, aborting past `max_bytes` or `max_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.+ The hosts we talk to are 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. Defaults suit a data page; the gateway token exchange passes its own much+ tighter caps."""+ max_bytes = MAX_RESPONSE_BYTES if max_bytes is None else max_bytes+ max_seconds = MAX_DOWNLOAD_SECONDS if max_seconds is None else max_secondschunks: list[bytes] = []total = 0- deadline = time.monotonic() + MAX_DOWNLOAD_SECONDS+ deadline = time.monotonic() + max_secondstry: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"+ f"{RESPONSE_TOO_SLOW_ERROR}: exceeded {max_seconds}s download budget")if not chunk:continuetotal += len(chunk)- if total > MAX_RESPONSE_BYTES:- raise QualysVmdrResponseTooLargeError(- f"{RESPONSE_TOO_LARGE_ERROR}: exceeded {MAX_RESPONSE_BYTES} bytes"- )+ if total > max_bytes:+ raise QualysVmdrResponseTooLargeError(f"{RESPONSE_TOO_LARGE_ERROR}: exceeded {max_bytes} bytes")chunks.append(chunk)finally:response.close()@@ -122,15 +136,57 @@ def _format_since_value(value: Any) -> str:return str(value)-def _make_session(username: str, password: str) -> requests.Session:+def _make_session(username: str, password: str, bearer_token: str | None = None) -> 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)+ # redirects off keeps the credential on the validated host.+ redact = (password,) if bearer_token is None else (password, bearer_token)+ session = make_tracked_session(headers=_BASE_HEADERS, redact_values=redact, allow_redirects=False)+ if bearer_token is not None:+ # KnowledgeBase 4.0 authenticates with a gateway-minted JWT, not basic auth.+ session.headers["Authorization"] = f"Bearer {bearer_token}"+ else:+ session.auth = (username, password)return session+def _fetch_jwt(gateway_server: str, username: str, password: str, logger: FilteringBoundLogger) -> str:+ """Mint a Qualys JWT from the account gateway for JWT-authenticated endpoints (KnowledgeBase 4.0).++ The gateway host (`gateway.<platform>.apps.qualys.com`) is a different host from the FO API+ server and can't be reliably derived from it, so it is a separate user-supplied field and is+ SSRF-validated here before the credential leaves the worker. A single KnowledgeBase sync makes+ one authenticated request (no truncation pagination), well inside the token's lifetime, so the+ token is minted once per run and never refreshed mid-sync.+ """+ gateway_url = build_base_url(gateway_server)+ _check_url_allowed(gateway_url)+ # `capture=False`: the response body is the raw minted JWT, which the name-based sample+ # scrubbers can't recognise (and it doesn't exist yet to be listed in `redact_values`), so the+ # exchange is metered and logged but never written to HTTP sample storage.+ session = make_tracked_session(+ headers=_BASE_HEADERS, redact_values=(password,), allow_redirects=False, capture=False+ )+ # stream=True so a hostile gateway host can't make us buffer an unbounded body — the token is+ # read under the tight JWT caps below.+ response = session.post(+ f"{gateway_url}/auth",+ data={"username": username, "password": password, "token": "true"},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ timeout=30,+ stream=True,+ )+ if not response.ok:+ response.close()+ logger.error(f"Qualys gateway auth error: status={response.status_code}")+ response.raise_for_status()+ body = _read_capped_body(response, max_bytes=MAX_JWT_RESPONSE_BYTES, max_seconds=MAX_JWT_DOWNLOAD_SECONDS)+ token = body.decode(response.encoding or "utf-8", errors="replace").strip()+ if not token:+ raise ValueError("Qualys gateway returned an empty JWT")+ return token++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,@@ -275,6 +331,7 @@ def _next_batch_url(root: Element, base_url: str) -> str | None:def _build_initial_url(base_url: str,config: QualysVmdrEndpointConfig,+ api_version: str,should_use_incremental_field: bool,db_incremental_field_last_value: Any,) -> str:@@ -283,7 +340,7 @@ def _build_initial_url(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)}"+ return f"{base_url}{config.resolve_path(api_version)}?{urlencode(params)}"def get_rows(@@ -291,8 +348,10 @@ def get_rows(username: str,password: str,endpoint: str,+ api_version: str,logger: FilteringBoundLogger,resumable_source_manager: ResumableSourceManager[QualysVmdrResumeConfig],+ gateway_server: str | None = None,should_use_incremental_field: bool = False,db_incremental_field_last_value: Any = None,) -> Iterator[list[dict[str, Any]]]:@@ -301,14 +360,22 @@ def get_rows(# 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)++ if config.requires_jwt(api_version):+ if not gateway_server:+ raise ValueError(MISSING_GATEWAY_ERROR)+ session = _make_session(username, password, bearer_token=_fetch_jwt(gateway_server, username, password, logger))+ else:+ session = _make_session(username, password)resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Noneif resume is not None and resume.next_url:url = resume.next_urllogger.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)+ url = _build_initial_url(+ base_url, config, api_version, should_use_incremental_field, db_incremental_field_last_value+ )while True:root = _fetch_page(session, url, logger)@@ -360,8 +427,10 @@ def qualys_vmdr_source(username: str,password: str,endpoint: str,+ api_version: str,logger: FilteringBoundLogger,resumable_source_manager: ResumableSourceManager[QualysVmdrResumeConfig],+ gateway_server: Optional[str] = None,should_use_incremental_field: bool = False,db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:@@ -374,8 +443,10 @@ def qualys_vmdr_source(username=username,password=password,endpoint=endpoint,+ api_version=api_version,logger=logger,resumable_source_manager=resumable_source_manager,+ gateway_server=gateway_server,should_use_incremental_field=should_use_incremental_field,db_incremental_field_last_value=db_incremental_field_last_value,),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.pyindex 19ef92f4595d..6e657f77e2f4 100644--- 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.py@@ -3,11 +3,22 @@ from typing import Optionalfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+# Opaque vendor version labels — never parsed or ordered. Only the KnowledgeBase Vulnerability API+# is versioned past 2.0: Qualys is retiring its 2.0 (EOS Dec 2025) in favor of 4.0, which serves the+# same feed at `/api/4.0/fo/knowledge_base/vuln/` but requires JWT Bearer auth instead of basic auth.+# The FO Host List / Host List Detection / VM Scan APIs are a separate versioning track and stay on+# `/api/2.0/` with basic auth under both source-level pins.+QUALYS_VMDR_API_VERSION_2_0 = "2.0"+QUALYS_VMDR_API_VERSION_4_0 = "4.0"+# Declared oldest -> newest; the default is always the last entry.+QUALYS_VMDR_SUPPORTED_VERSIONS = (QUALYS_VMDR_API_VERSION_2_0, QUALYS_VMDR_API_VERSION_4_0)+QUALYS_VMDR_DEFAULT_VERSION = QUALYS_VMDR_API_VERSION_4_0+@dataclassclass QualysVmdrEndpointConfig:name: str- path: str # e.g. "/api/2.0/fo/asset/host/"+ path: str # version-independent request path, 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)@@ -22,6 +33,19 @@ class QualysVmdrEndpointConfig:# Flatten each HOST's DETECTION_LIST into one row per detection (Host List Detection only).flatten_host_detections: bool = Falseshould_sync_default: bool = True+ # Per-version path overrides for endpoints whose route moved between vendor versions. Absent+ # keys fall through to `path` — that is the correct version-independent route, not silent drift,+ # since only the KnowledgeBase endpoint diverges.+ path_overrides: dict[str, str] = field(default_factory=dict)+ # Source-level versions on which this endpoint authenticates with a JWT Bearer token minted at+ # the Qualys gateway, rather than HTTP basic auth. Empty = basic auth on every version.+ jwt_versions: frozenset[str] = frozenset()++ def resolve_path(self, api_version: str) -> str:+ return self.path_overrides.get(api_version, self.path)++ def requires_jwt(self, api_version: str) -> bool:+ return api_version in self.jwt_versionsQUALYS_VMDR_ENDPOINTS: dict[str, QualysVmdrEndpointConfig] = {@@ -109,6 +133,9 @@ QUALYS_VMDR_ENDPOINTS: dict[str, QualysVmdrEndpointConfig] = {primary_keys=["qid"],truncation_limit=None,should_sync_default=False,+ # Qualys is sunsetting KnowledgeBase 2.0; 4.0 serves the same feed but only over JWT Bearer.+ path_overrides={QUALYS_VMDR_API_VERSION_4_0: "/api/4.0/fo/knowledge_base/vuln/"},+ jwt_versions=frozenset({QUALYS_VMDR_API_VERSION_4_0}),),}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 a8f003bec381..abb6aafb7325 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,3 +1,4 @@+import datetimefrom typing import Optional, castfrom posthog.schema import (@@ -9,7 +10,11 @@ from posthog.schema import (SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ FieldType,+ ResumableSource,+ VersionDeprecation,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)@@ -21,6 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_QualysVmdrSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.qualys_vmdr.qualys_vmdr import (+ MISSING_GATEWAY_ERROR,QualysVmdrResumeConfig,qualys_vmdr_source,validate_credentials as validate_qualys_vmdr_credentials,@@ -28,7 +34,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.qualys_vmdfrom products.warehouse_sources.backend.temporal.data_imports.sources.qualys_vmdr.settings import (ENDPOINTS,INCREMENTAL_FIELDS,+ QUALYS_VMDR_API_VERSION_2_0,+ QUALYS_VMDR_DEFAULT_VERSION,QUALYS_VMDR_ENDPOINTS,+ QUALYS_VMDR_SUPPORTED_VERSIONS,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -36,8 +45,12 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass QualysVmdrSource(ResumableSource[QualysVmdrSourceConfig, QualysVmdrResumeConfig]):lists_tables_without_credentials = True # static endpoint catalog — safe for public docs- supported_versions = ("2.0",)- default_version = "2.0"+ supported_versions = QUALYS_VMDR_SUPPORTED_VERSIONS+ default_version = QUALYS_VMDR_DEFAULT_VERSION+ # Qualys is retiring KnowledgeBase 2.0 (End of Service Dec 2025, End of Life Dec 2026).+ deprecated_versions = (+ VersionDeprecation(version=QUALYS_VMDR_API_VERSION_2_0, sunset_at=datetime.date(2025, 12, 31)),+ )api_docs_url = "https://docs.qualys.com/en/vm/api/index.htm"@property@@ -46,9 +59,9 @@ class QualysVmdrSource(ResumableSource[QualysVmdrSourceConfig, QualysVmdrResumeC@propertydef 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"]+ # Both hosts receive the stored credentials (`api_server` for basic auth, `gateway_server`+ # to mint the KnowledgeBase 4.0 JWT), so retargeting either must re-require them.+ return ["api_server", "gateway_server"]@propertydef get_source_config(self) -> SourceConfig:@@ -62,7 +75,7 @@ class QualysVmdrSource(ResumableSource[QualysVmdrSourceConfig, QualysVmdrResumeCUse 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.""",+The `knowledge_base` table additionally requires the KnowledgeBase download option to be enabled on your Qualys subscription. On API version 4.0 it also needs your account's gateway URL (for example `gateway.qg2.apps.qualys.com`), which you can find under **Help > About** in the Qualys UI. Leave the gateway URL blank if you do not sync the `knowledge_base` table.""",iconPath="/static/services/qualys_vmdr.png",docsUrl="https://posthog.com/docs/cdp/sources/qualys-vmdr",fields=cast(@@ -92,6 +105,16 @@ The `knowledge_base` table additionally requires the KnowledgeBase download optiplaceholder="",secret=True,),+ # Optional: only the KnowledgeBase table on API version 4.0 needs it, so form-level+ # `required` can't express the dependency — it's enforced at sync time instead.+ SourceFieldInputConfig(+ name="gateway_server",+ label="Gateway URL",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="gateway.qg2.apps.qualys.com",+ secret=False,+ ),],),)@@ -112,6 +135,7 @@ The `knowledge_base` table additionally requires the KnowledgeBase download opti"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.",+ MISSING_GATEWAY_ERROR: "Syncing the knowledge_base table on API version 4.0 needs your Qualys gateway URL. Add it to the source configuration and reconnect.",}def get_schemas(@@ -169,8 +193,12 @@ The `knowledge_base` table additionally requires the KnowledgeBase download optiusername=config.username,password=config.password,endpoint=inputs.schema_name,+ # `inputs.api_version` is already resolved upstream; resolving again is idempotent and+ # keeps the source functional when called with a bare pin outside the sync pipeline.+ api_version=self.resolve_api_version(inputs.api_version),logger=inputs.logger,resumable_source_manager=resumable_source_manager,+ gateway_server=config.gateway_server,should_use_incremental_field=inputs.should_use_incremental_field,db_incremental_field_last_value=inputs.db_incremental_field_last_valueif inputs.should_use_incremental_fielddiff --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.pyindex 105049dd03c6..94d54e02a8a3 100644--- 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.py@@ -7,11 +7,13 @@ from unittest import mockfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.qualys_vmdr.qualys_vmdr import (+ MISSING_GATEWAY_ERROR,QualysVmdrResponseTooLargeError,QualysVmdrResumeConfig,QualysVmdrRetryableError,_build_initial_url,_extract_rows,+ _fetch_jwt,_fetch_page,_next_batch_url,_parse_xml,@@ -107,6 +109,18 @@ SIMPLE_RETURN_ERROR = """<?xml version="1.0" encoding="UTF-8" ?></RESPONSE></SIMPLE_RETURN>"""+KNOWLEDGE_BASE_PAGE = """<?xml version="1.0" encoding="UTF-8" ?>+<KNOWLEDGE_BASE_VULN_LIST_OUTPUT>+ <RESPONSE>+ <VULN_LIST>+ <VULN>+ <QID>38170</QID>+ <TITLE>Example vulnerability</TITLE>+ </VULN>+ </VULN_LIST>+ </RESPONSE>+</KNOWLEDGE_BASE_VULN_LIST_OUTPUT>"""+def _response(status_code: int = 200, text: str = "", headers: dict[str, str] | None = None) -> mock.MagicMock:response = mock.MagicMock()@@ -160,19 +174,35 @@ class TestQualysVmdr:],)def test_initial_url_includes_incremental_filter(self, value, expected_param):- url = _build_initial_url("https://example.com", QUALYS_VMDR_ENDPOINTS["hosts"], True, value)+ url = _build_initial_url("https://example.com", QUALYS_VMDR_ENDPOINTS["hosts"], "2.0", True, value)assert expected_param in urlassert "truncation_limit=1000" in urldef test_initial_url_full_refresh_has_no_incremental_filter(self):- url = _build_initial_url("https://example.com", QUALYS_VMDR_ENDPOINTS["hosts"], False, None)+ url = _build_initial_url("https://example.com", QUALYS_VMDR_ENDPOINTS["hosts"], "2.0", False, None)assert "vm_scan_since" not in urldef 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)+ url = _build_initial_url("https://example.com", QUALYS_VMDR_ENDPOINTS["scans"], "2.0", False, None)assert "truncation_limit" not in urlassert url.startswith("https://example.com/api/2.0/fo/scan/?")+ @pytest.mark.parametrize(+ "endpoint,api_version,expected_path",+ [+ # Only the KnowledgeBase endpoint moves to /api/4.0/ under the 4.0 pin.+ ("knowledge_base", "2.0", "/api/2.0/fo/knowledge_base/vuln/"),+ ("knowledge_base", "4.0", "/api/4.0/fo/knowledge_base/vuln/"),+ # The FO endpoints stay on /api/2.0/ regardless of the source-level pin.+ ("hosts", "2.0", "/api/2.0/fo/asset/host/"),+ ("hosts", "4.0", "/api/2.0/fo/asset/host/"),+ ("scans", "4.0", "/api/2.0/fo/scan/"),+ ],+ )+ def test_initial_url_resolves_path_per_version(self, endpoint, api_version, expected_path):+ url = _build_initial_url("https://example.com", QUALYS_VMDR_ENDPOINTS[endpoint], api_version, False, None)+ assert url.startswith(f"https://example.com{expected_path}?")+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"]))@@ -219,7 +249,7 @@ class TestQualysVmdr: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()+ "qualysapi.qualys.com", "user", "pass", "hosts", "2.0", mock.MagicMock(), manager.as_manager())first_batch = next(generator)@@ -249,7 +279,7 @@ class TestQualysVmdr: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())+ get_rows("qualysapi.qualys.com", "user", "pass", "hosts", "2.0", mock.MagicMock(), manager.as_manager()))assert session.get.call_args[0][0] == resume_url@@ -264,7 +294,9 @@ class TestQualysVmdr:):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())+ get_rows(+ "169.254.169.254", "user", "pass", "hosts", "2.0", mock.MagicMock(), _FakeManager().as_manager()+ ))session.get.assert_not_called()@@ -344,3 +376,166 @@ class TestQualysVmdr:assert ok is Falseassert error is not None and "not allowed" in errorsession.get.assert_not_called()++ def test_get_rows_knowledge_base_4_0_mints_jwt_and_uses_bearer(self):+ get_session = mock.MagicMock()+ get_session.get.return_value = _response(text=KNOWLEDGE_BASE_PAGE)+ gateway_session = mock.MagicMock()+ gateway_session.post.return_value = _response(status_code=200, text="jwt-token")++ with (+ mock.patch(f"{_MODULE}._make_session", return_value=get_session) as make_session,+ mock.patch(f"{_MODULE}.make_tracked_session", return_value=gateway_session),+ mock.patch(f"{_MODULE}.is_url_allowed", return_value=(True, None)),+ ):+ batches = list(+ get_rows(+ "qualysapi.qualys.com",+ "user",+ "pass",+ "knowledge_base",+ "4.0",+ mock.MagicMock(),+ _FakeManager().as_manager(),+ gateway_server="gateway.qg2.apps.qualys.com",+ )+ )++ # The JWT is minted at the gateway host, then threaded into the request session as a Bearer token+ assert gateway_session.post.call_args[0][0] == "https://gateway.qg2.apps.qualys.com/auth"+ assert gateway_session.post.call_args.kwargs["data"]["token"] == "true"+ assert make_session.call_args.kwargs["bearer_token"] == "jwt-token"+ # KnowledgeBase 4.0 is served from the FO host on the /api/4.0/ path+ assert get_session.get.call_args[0][0].startswith(+ "https://qualysapi.qualys.com/api/4.0/fo/knowledge_base/vuln/"+ )+ assert [row["qid"] for row in batches[0]] == ["38170"]++ def test_get_rows_knowledge_base_2_0_uses_basic_auth_and_2_0_path(self):+ get_session = mock.MagicMock()+ get_session.get.return_value = _response(text=KNOWLEDGE_BASE_PAGE)++ with (+ mock.patch(f"{_MODULE}._make_session", return_value=get_session) as make_session,+ mock.patch(f"{_MODULE}.make_tracked_session") as gateway,+ mock.patch(f"{_MODULE}.is_url_allowed", return_value=(True, None)),+ ):+ list(+ get_rows(+ "qualysapi.qualys.com",+ "user",+ "pass",+ "knowledge_base",+ "2.0",+ mock.MagicMock(),+ _FakeManager().as_manager(),+ )+ )++ # No JWT minting on 2.0 — the request session keeps basic auth+ gateway.assert_not_called()+ assert "bearer_token" not in make_session.call_args.kwargs+ assert get_session.get.call_args[0][0].startswith(+ "https://qualysapi.qualys.com/api/2.0/fo/knowledge_base/vuln/"+ )++ def test_get_rows_knowledge_base_4_0_without_gateway_raises_before_any_request(self):+ with (+ mock.patch(f"{_MODULE}._make_session") as make_session,+ mock.patch(f"{_MODULE}.make_tracked_session") as gateway,+ mock.patch(f"{_MODULE}.is_url_allowed", return_value=(True, None)),+ ):+ with pytest.raises(ValueError, match=MISSING_GATEWAY_ERROR):+ list(+ get_rows(+ "qualysapi.qualys.com",+ "user",+ "pass",+ "knowledge_base",+ "4.0",+ mock.MagicMock(),+ _FakeManager().as_manager(),+ gateway_server=None,+ )+ )++ gateway.assert_not_called()+ make_session.assert_not_called()++ def test_fetch_jwt_posts_credentials_to_gateway_and_strips_token(self):+ gateway_session = mock.MagicMock()+ gateway_session.post.return_value = _response(status_code=200, text=" jwt-token\n")++ with (+ mock.patch(f"{_MODULE}.make_tracked_session", return_value=gateway_session),+ mock.patch(f"{_MODULE}.is_url_allowed", return_value=(True, None)),+ ):+ token = _fetch_jwt("gateway.qg2.apps.qualys.com", "user", "pass", mock.MagicMock())++ assert token == "jwt-token"+ assert gateway_session.post.call_args[0][0] == "https://gateway.qg2.apps.qualys.com/auth"+ assert gateway_session.post.call_args.kwargs["data"] == {+ "username": "user",+ "password": "pass",+ "token": "true",+ }++ def test_fetch_jwt_session_opts_out_of_sample_capture(self):+ # The /auth response body is the raw minted JWT: the name-based sample scrubbers can't+ # recognise it and it can't be listed in `redact_values` (it doesn't exist yet), so the+ # exchange must be excluded from HTTP sample capture entirely.+ gateway_session = mock.MagicMock()+ gateway_session.post.return_value = _response(status_code=200, text="jwt-token")++ with (+ mock.patch(f"{_MODULE}.make_tracked_session", return_value=gateway_session) as make_tracked,+ mock.patch(f"{_MODULE}.is_url_allowed", return_value=(True, None)),+ ):+ _fetch_jwt("gateway.qg2.apps.qualys.com", "user", "pass", mock.MagicMock())++ assert make_tracked.call_args.kwargs["capture"] is False+ # The password is still redacted from the metered request, and the body is streamed+ # rather than buffered whole.+ assert make_tracked.call_args.kwargs["redact_values"] == ("pass",)+ assert gateway_session.post.call_args.kwargs["stream"] is True++ def test_fetch_jwt_refuses_an_oversized_gateway_body(self):+ # `gateway_server` is user-supplied, so a host that returns a huge (or slow-dripped) body+ # must not be able to exhaust a shared worker's memory.+ gateway_session = mock.MagicMock()+ response = _response(status_code=200)+ response.iter_content.return_value = iter([b"a" * 1024, b"b" * 1024])+ gateway_session.post.return_value = response++ with (+ mock.patch(f"{_MODULE}.make_tracked_session", return_value=gateway_session),+ mock.patch(f"{_MODULE}.is_url_allowed", return_value=(True, None)),+ mock.patch(f"{_MODULE}.MAX_JWT_RESPONSE_BYTES", 1500),+ ):+ with pytest.raises(QualysVmdrResponseTooLargeError):+ _fetch_jwt("gateway.qg2.apps.qualys.com", "user", "pass", mock.MagicMock())++ response.close.assert_called_once()++ def test_fetch_jwt_raises_on_empty_token(self):+ gateway_session = mock.MagicMock()+ gateway_session.post.return_value = _response(status_code=200, text=" ")++ with (+ mock.patch(f"{_MODULE}.make_tracked_session", return_value=gateway_session),+ mock.patch(f"{_MODULE}.is_url_allowed", return_value=(True, None)),+ ):+ with pytest.raises(ValueError, match="empty JWT"):+ _fetch_jwt("gateway.qg2.apps.qualys.com", "user", "pass", mock.MagicMock())++ def test_fetch_jwt_rejects_disallowed_gateway_before_any_request(self):+ gateway_session = mock.MagicMock()++ with (+ mock.patch(f"{_MODULE}.make_tracked_session", return_value=gateway_session),+ mock.patch(f"{_MODULE}.is_url_allowed", return_value=(False, "URL resolves to a private IP")),+ ):+ with pytest.raises(ValueError, match="not allowed"):+ _fetch_jwt("169.254.169.254", "user", "pass", mock.MagicMock())++ gateway_session.post.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.pyindex a23030046c5e..63427501e990 100644--- 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.py@@ -1,3 +1,5 @@+import datetime+import pytestfrom unittest import mock@@ -6,6 +8,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_QualysVmdrSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.qualys_vmdr.qualys_vmdr import (+ MISSING_GATEWAY_ERROR,QualysVmdrResumeConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.qualys_vmdr.source import QualysVmdrSource@@ -14,13 +17,16 @@ 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 _config(gateway_server: str | None = None) -> QualysVmdrSourceConfig:+ return QualysVmdrSourceConfig(+ api_server="qualysapi.qualys.com", username="user", password="pass", gateway_server=gateway_server+ )def _inputs(**overrides) -> mock.MagicMock:inputs = mock.MagicMock()inputs.schema_name = overrides.get("schema_name", "hosts")+ inputs.api_version = overrides.get("api_version", None)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@@ -99,6 +105,32 @@ class TestQualysVmdrSource: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"])+ @pytest.mark.parametrize(+ "expected_key",+ ["401 Client Error", "403 Client Error", "Unauthorized for url", MISSING_GATEWAY_ERROR],+ )def test_non_retryable_errors(self, expected_key):assert expected_key in self.source.get_non_retryable_errors()++ def test_default_version_is_4_0_and_2_0_is_deprecated(self):+ # New sources start on 4.0; 2.0 carries the vendor's announced sunset date and 4.0 is clean.+ assert self.source.default_version == "4.0"+ deprecation = self.source.get_version_deprecation("2.0")+ assert deprecation is not None and deprecation.sunset_at == datetime.date(2025, 12, 31)+ assert self.source.get_version_deprecation("4.0") is None++ @pytest.mark.parametrize(+ "pin,expected_version",+ [("2.0", "2.0"), ("4.0", "4.0"), (None, "4.0")],+ )+ def test_source_for_pipeline_threads_resolved_version_and_gateway(self, pin, expected_version):+ with mock.patch(f"{_MODULE}.qualys_vmdr_source") as transport:+ self.source.source_for_pipeline(+ _config(gateway_server="gateway.qg2.apps.qualys.com"),+ mock.MagicMock(),+ _inputs(schema_name="knowledge_base", api_version=pin),+ )++ # A NULL pin resolves to default_version (4.0); a present pin is honored verbatim.+ assert transport.call_args.kwargs["api_version"] == expected_version+ assert transport.call_args.kwargs["gateway_server"] == "gateway.qg2.apps.qualys.com"