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 the aws inspector import source (#110801)

Tom Owers8c1706eb37b9
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 b274456b72e6..47577edac2c2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -108,6 +108,7 @@ the row lists both.
| aws_cost_anomaly_detection | HTTP | requests | ✅ |
| aws_cost_explorer | HTTP | requests | ✅ |
| aws_glue_data_catalog | HTTP | requests | ✅ |
+| aws_inspector | HTTP | requests | ✅ |
| aws_organizations | HTTP | requests | ✅ |
| aws_security_hub | HTTP | requests | ✅ |
| aws_ses | HTTP | requests | ✅ |
@@ -925,7 +926,6 @@ doesn't conflict with concurrent PRs.
- aws_guardduty
- aws_health
- aws_iam_access_analyzer
-- aws_inspector
- aws_macie
- aws_rds_performance_insights
- aws_sagemaker
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_inspector/aws_inspector.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_inspector/aws_inspector.py
new file mode 100644
index 000000000000..b8cbd8b915e5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_inspector/aws_inspector.py
@@ -0,0 +1,241 @@
+import re
+import json
+import datetime as dt
+from collections.abc import Iterator
+from typing import Any
+
+import requests
+from botocore.auth import SigV4Auth
+from botocore.awsrequest import AWSRequest
+from botocore.credentials import Credentials
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_inspector.settings import (
+ AWS_INSPECTOR_ENDPOINTS,
+ ERROR_MESSAGES,
+ INSPECTOR_API_VERSION,
+ AwsInspectorEndpoint,
+)
+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.http.transport import BoundedRetry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsinspector import (
+ AwsInspectorSourceConfig,
+)
+
+TRANSPORT_RETRY = BoundedRetry(
+ total=3,
+ backoff_factor=1,
+ status_forcelist=(429, 500, 502, 503, 504),
+ allowed_methods=frozenset(["POST"]),
+ raise_on_status=False,
+)
+_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
+
+
+@frozen
+class AwsInspectorResumeConfig:
+ next_token: str | None = None
+ updated_after: float | None = None
+ completed: bool = False
+
+
+class AwsInspectorError(Exception):
+ def __init__(self, code: str, message: str) -> None:
+ super().__init__(f"AWS Inspector request failed: {code} - {message}")
+ self.code = code
+ self.message = message
+
+
+def error_for_response(response: requests.Response) -> AwsInspectorError:
+ try:
+ body = response.json()
+ except ValueError:
+ body = {}
+ if not isinstance(body, dict):
+ body = {}
+ raw_code = response.headers.get("x-amzn-ErrorType") or body.get("__type") or body.get("code")
+ code = str(raw_code or f"HTTP {response.status_code}").split(":")[0].split("#")[-1]
+ message = str(body.get("message") or body.get("Message") or response.reason or "")[:500]
+ if response.status_code in (400, 403) and any(
+ phrase in message.lower() for phrase in ("not subscribed", "not enabled", "subscription is required")
+ ):
+ code = "SubscriptionRequiredException"
+ return AwsInspectorError(code, message)
+
+
+def error_message(error: AwsInspectorError) -> str | None:
+ return next((message for code, message in ERROR_MESSAGES.items() if error.code.startswith(code)), None)
+
+
+class AwsInspectorClient:
+ def __init__(self, config: AwsInspectorSourceConfig, api_version: str = INSPECTOR_API_VERSION) -> None:
+ if api_version != INSPECTOR_API_VERSION:
+ raise ValueError(f"Unsupported AWS Inspector API version: {api_version}")
+ if not re.fullmatch(r"[a-z]{2}(?:-[a-z]+)+-\d+", config.region):
+ raise ValueError("Enter an AWS region code, such as us-east-1.")
+ if not config.aws_access_key_id or not config.aws_secret_access_key:
+ raise ValueError("Enter both an AWS access key ID and a secret access key.")
+ suffix = "amazonaws.com.cn" if config.region.startswith("cn-") else "amazonaws.com"
+ self._base_url = f"https://inspector2.{config.region}.{suffix}"
+ self._signer = SigV4Auth(
+ Credentials(config.aws_access_key_id, config.aws_secret_access_key, config.aws_session_token or None),
+ "inspector2",
+ config.region,
+ )
+ self._session = make_tracked_session(
+ retry=TRANSPORT_RETRY,
+ redact_values=tuple(
+ value
+ for value in (config.aws_access_key_id, config.aws_secret_access_key, config.aws_session_token)
+ if value
+ ),
+ )
+
+ def close(self) -> None:
+ self._session.close()
+
+ def request(self, endpoint: AwsInspectorEndpoint, payload: dict[str, Any]) -> dict[str, Any]:
+ body = json.dumps(payload).encode("utf-8")
+ url = self._base_url + endpoint.path
+ request = AWSRequest(method="POST", url=url, data=body, headers={"Content-Type": "application/json"})
+ self._signer.add_auth(request)
+ response = self._session.post(url, data=body, headers=dict(request.headers), timeout=60, allow_redirects=False)
+ if response.status_code != 200:
+ raise error_for_response(response)
+ parsed = response.json()
+ if not isinstance(parsed, dict):
+ raise ValueError("AWS Inspector returned an invalid response.")
+ return parsed
+
+
+def timestamp(value: dt.datetime | str | int | float) -> float:
+ if isinstance(value, int | float):
+ return float(value)
+ parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00")) if isinstance(value, str) else value
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=dt.UTC)
+ return parsed.timestamp()
+
+
+def request_payload(endpoint: AwsInspectorEndpoint, updated_after: float | None = None) -> dict[str, Any]:
+ payload: dict[str, Any] = {}
+ if endpoint.page_size is not None:
+ payload["maxResults"] = endpoint.page_size
+ if endpoint.operation == "ListCoverageStatistics":
+ payload["groupBy"] = "RESOURCE_TYPE"
+ if endpoint.operation == "ListFindings" and updated_after is not None:
+ payload["filterCriteria"] = {"updatedAt": [{"startInclusive": updated_after}]}
+ return payload
+
+
+def normalize_row(endpoint: AwsInspectorEndpoint, item: dict[str, Any], region: str) -> dict[str, Any]:
+ row = {_CAMEL_BOUNDARY.sub("_", key).lower(): value for key, value in item.items()}
+ for column in endpoint.timestamp_columns:
+ if row.get(column) is not None:
+ row[column] = dt.datetime.fromtimestamp(timestamp(row[column]), tz=dt.UTC)
+ row["region"] = region
+ return row
+
+
+def get_rows(
+ config: AwsInspectorSourceConfig,
+ endpoint: AwsInspectorEndpoint,
+ manager: ResumableSourceManager[AwsInspectorResumeConfig],
+ updated_after: float | None,
+ api_version: str,
+) -> Iterator[list[dict[str, Any]]]:
+ state = manager.load_state() if manager.can_resume() else None
+ if state is not None and state.completed:
+ return
+ next_token = state.next_token if state else None
+ payload = request_payload(endpoint, state.updated_after if state else updated_after)
+ client = AwsInspectorClient(config, api_version)
+ try:
+ while True:
+ request_body = dict(payload)
+ if next_token:
+ request_body["nextToken"] = next_token
+ body = client.request(endpoint, request_body)
+ rows = [normalize_row(endpoint, item, config.region) for item in body.get(endpoint.result_key, [])]
+ token = body.get("nextToken") or None
+ if token is not None and (not isinstance(token, str) or token == next_token):
+ raise ValueError("AWS Inspector returned an invalid pagination token.")
+ manager.save_state(
+ AwsInspectorResumeConfig(
+ next_token=token,
+ updated_after=state.updated_after if state else updated_after,
+ completed=token is None,
+ )
+ )
+ if rows:
+ yield rows
+ manager.safe_point()
+ if token is None:
+ break
+ next_token = token
+ finally:
+ client.close()
+
+
+def validate_credentials(
+ config: AwsInspectorSourceConfig,
+ schema_name: str | None = None,
+ api_version: str = INSPECTOR_API_VERSION,
+) -> tuple[bool, str | None]:
+ endpoint = AWS_INSPECTOR_ENDPOINTS.get(schema_name or "findings")
+ if endpoint is None:
+ return False, f"Unknown AWS Inspector table: {schema_name}"
+ try:
+ client = AwsInspectorClient(config, api_version)
+ except ValueError as error:
+ return False, str(error)
+ payload = request_payload(endpoint)
+ if endpoint.page_size is not None:
+ payload["maxResults"] = 1
+ try:
+ client.request(endpoint, payload)
+ except AwsInspectorError as error:
+ if error.code.startswith("AccessDenied") or error.code == "HTTP 403":
+ if schema_name is None:
+ return True, None
+ return False, f"Grant inspector2:{endpoint.operation} to read this table."
+ message = error_message(error)
+ if message:
+ return False, message
+ raise
+ finally:
+ client.close()
+ return True, None
+
+
+def aws_inspector_source(
+ config: AwsInspectorSourceConfig,
+ endpoint: str,
+ manager: ResumableSourceManager[AwsInspectorResumeConfig],
+ should_use_incremental_field: bool,
+ last_value: dt.datetime | str | int | float | None,
+ api_version: str = INSPECTOR_API_VERSION,
+) -> SourceResponse:
+ endpoint_config = AWS_INSPECTOR_ENDPOINTS.get(endpoint)
+ if endpoint_config is None:
+ raise ValueError(f"Unknown AWS Inspector table: {endpoint}")
+ updated_after = (
+ timestamp(last_value)
+ if endpoint == "findings" and should_use_incremental_field and last_value is not None
+ else None
+ )
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(config, endpoint_config, manager, updated_after, api_version),
+ primary_keys=list(endpoint_config.primary_keys),
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
+ # Inspector filters by updatedAt but cannot sort by it.
+ # "desc" saves the watermark once at job end, so unordered rows cannot strand older ones.
+ sort_mode="desc",
+ on_complete=manager.clear_state,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_inspector/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_inspector/canonical_descriptions.py
new file mode 100644
index 000000000000..16f29789c8ae
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_inspector/canonical_descriptions.py
@@ -0,0 +1,56 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "findings": {
+ "description": "Amazon Inspector findings for vulnerabilities and network reachability.",
+ "docs_url": "https://docs.aws.amazon.com/inspector/v2/APIReference/API_Finding.html",
+ "columns": {
+ "finding_arn": "ARN that identifies the finding.",
+ "aws_account_id": "AWS account that owns the affected resource.",
+ "type": "Type of finding, such as a package vulnerability.",
+ "title": "Short title of the finding.",
+ "description": "Description of the finding.",
+ "severity": "Severity assigned to the finding.",
+ "status": "Finding status: active, suppressed, or closed.",
+ "first_observed_at": "Time when Inspector first detected the finding.",
+ "last_observed_at": "Time when Inspector last detected the finding.",
+ "updated_at": "Time when Inspector last updated the finding.",
+ "resources": "Resources affected by the finding.",
+ "remediation": "Recommendations to correct the finding.",
+ "package_vulnerability_details": "Package vulnerability details, including affected packages and vulnerability identifiers.",
+ "network_reachability_details": "Network paths and ports associated with the finding.",
+ "code_vulnerability_details": "Code vulnerability details associated with the finding.",
+ "inspector_score": "Risk score calculated by Amazon Inspector.",
+ "fix_available": "Whether a fix is available for the vulnerability.",
+ "exploit_available": "Whether a known exploit exists for the vulnerability.",
+ "epss": "Probability score for exploitation of the vulnerability.",
+ "region": "AWS region selected for this source.",
+ },
+ },
+ "coverage": {
+ "description": "Resources monitored by Inspector, with one row for each resource and scan type.",
+ "docs_url": "https://docs.aws.amazon.com/inspector/v2/APIReference/API_CoveredResource.html",
+ "columns": {
+ "account_id": "AWS account that owns the resource.",
+ "resource_id": "Identifier of the monitored resource.",
+ "resource_type": "Type of monitored resource.",
+ "scan_type": "Type of scan applied to the resource.",
+ "scan_status": "Scan status and the reason for that status.",
+ "scan_mode": "Scanning method used for the resource.",
+ "last_scanned_at": "Time when Inspector last scanned the resource.",
+ "resource_metadata": "Details specific to the resource type.",
+ "region": "AWS region selected for this source.",
+ },
+ },
+ "coverage_statistics": {
+ "description": "Counts of resources monitored by Inspector, grouped by resource type.",
+ "docs_url": "https://docs.aws.amazon.com/inspector/v2/APIReference/API_ListCoverageStatistics.html",
+ "columns": {
+ "group_key": "Resource type used to group the count.",
+ "count": "Number of resources in the group.",
+ "region": "AWS region selected for this source.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_inspector/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_inspector/settings.py
new file mode 100644
index 000000000000..071bed61f870
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_inspector/settings.py
@@ -0,0 +1,73 @@
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+INSPECTOR_API_VERSION = "2020-06-08"
+DEFAULT_REGION = "us-east-1"
+
+
+@frozen
+class AwsInspectorEndpoint:
+ operation: str
+ path: str
+ result_key: str
+ primary_keys: tuple[str, ...]
+ page_size: int | None = None
+ timestamp_columns: tuple[str, ...] = ()
+ partition_key: str | None = None
+
+
+AWS_INSPECTOR_ENDPOINTS = {
+ "findings": AwsInspectorEndpoint(
+ operation="ListFindings",
+ path="/findings/list",
+ result_key="findings",
+ primary_keys=("finding_arn",),
+ page_size=25,
+ timestamp_columns=("first_observed_at", "last_observed_at", "updated_at"),
+ partition_key="first_observed_at",
+ ),
+ "coverage": AwsInspectorEndpoint(
+ operation="ListCoverage",
+ path="/coverage/list",
+ result_key="coveredResources",
+ primary_keys=("region", "account_id", "resource_type", "resource_id", "scan_type"),
+ page_size=200,
+ timestamp_columns=("last_scanned_at",),
+ ),
+ "coverage_statistics": AwsInspectorEndpoint(
+ operation="ListCoverageStatistics",
+ path="/coverage/statistics/list",
+ result_key="countsByGroup",
+ primary_keys=("region", "group_key"),
+ ),
+}
+ENDPOINTS = tuple(AWS_INSPECTOR_ENDPOINTS)
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "findings": [
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ]
+}
+ENDPOINT_DESCRIPTIONS = {
+ "findings": "Vulnerability and network reachability findings for resources in the selected AWS region.",
+ "coverage": "Resources and scan types monitored by Amazon Inspector in the selected AWS region.",
+ "coverage_statistics": "Resource counts grouped by resource type in the selected AWS region.",
+}
+
+ERROR_MESSAGES = {
+ "AccessDenied": "Grant inspector2:ListFindings, inspector2:ListCoverage, or inspector2:ListCoverageStatistics for the tables you select.",
+ "UnrecognizedClientException": "AWS rejected the credentials. Check the access key ID, secret access key, and session token.",
+ "InvalidClientTokenId": "AWS rejected the access key ID. Check that the key is correct and active.",
+ "InvalidSignatureException": "AWS rejected the signature. Check the secret access key and session token.",
+ "SignatureDoesNotMatch": "AWS rejected the signature. Check the secret access key and session token.",
+ "ExpiredToken": "The AWS session token expired. Connect again with new credentials.",
+ "SubscriptionRequiredException": "Enable Amazon Inspector in the selected AWS region, then try again.",
+ "OptInRequired": "Enable Amazon Inspector in the selected AWS region, then try again.",
+ "HTTP 401": "AWS rejected the credentials. Check the access key ID, secret access key, and session token.",
+ "HTTP 403": "AWS denied access. Check the IAM permissions for the selected tables.",
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_inspector/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_inspector/source.py
index a0b3a756dea4..34724daae69f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_inspector/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_inspector/source.py
@@ -1,8 +1,39 @@
from typing import cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_inspector.aws_inspector import (
+ AwsInspectorResumeConfig,
+ aws_inspector_source,
+ validate_credentials as validate_aws_inspector_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_inspector.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_inspector.settings import (
+ DEFAULT_REGION,
+ ENDPOINT_DESCRIPTIONS,
+ ENDPOINTS,
+ ERROR_MESSAGES,
+ INCREMENTAL_FIELDS,
+ INSPECTOR_API_VERSION,
+)
+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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsinspector import (
AwsInspectorSourceConfig,
)
@@ -10,18 +41,121 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AwsInspectorSource(SimpleSource[AwsInspectorSourceConfig]):
+class AwsInspectorSource(ResumableSource[AwsInspectorSourceConfig, AwsInspectorResumeConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = (INSPECTOR_API_VERSION,)
+ default_version = INSPECTOR_API_VERSION
+ api_docs_url = "https://docs.aws.amazon.com/inspector/v2/APIReference/Welcome.html"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AWSINSPECTOR
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {f"AWS Inspector request failed: {code}": message for code, message in ERROR_MESSAGES.items()}
+
+ def get_retryable_errors(self) -> set[str]:
+ return {
+ "AWS Inspector request failed: ThrottlingException",
+ "AWS Inspector request failed: InternalServerException",
+ "AWS Inspector request failed: HTTP 429",
+ "AWS Inspector request failed: HTTP 5",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AwsInspectorSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, descriptions=ENDPOINT_DESCRIPTIONS)
+
+ def validate_credentials(
+ self,
+ config: AwsInspectorSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_aws_inspector_credentials(config, schema_name, self.resolve_api_version(api_version))
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AwsInspectorResumeConfig]:
+ return ResumableSourceManager(inputs, AwsInspectorResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AwsInspectorSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AwsInspectorResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return aws_inspector_source(
+ config=config,
+ endpoint=inputs.schema_name,
+ manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ last_value=inputs.db_incremental_field_last_value,
+ api_version=self.resolve_api_version(inputs.api_version),
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.AWSINSPECTOR,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="Amazon Web Services (Amazon Inspector)",
+ label="AWS Inspector",
+ caption="""Sync Amazon Inspector findings and scan coverage into the PostHog Data warehouse.
+
+Enable Amazon Inspector in the region you select. Grant these IAM permissions for the tables you select:
+`inspector2:ListFindings`, `inspector2:ListCoverage`, and `inspector2:ListCoverageStatistics`.
+
+Enter your access key ID and secret access key. Add a session token if you use temporary credentials.
+This source reads one AWS region.""",
iconPath="/static/services/aws_inspector.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/aws-inspector",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["aws", "inspector", "security", "vulnerabilities"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="aws_access_key_id",
+ label="AWS access key ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="AKIA...",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="aws_secret_access_key",
+ label="AWS secret access key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="aws_session_token",
+ label="AWS session token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="Only needed for temporary credentials",
+ caption="Temporary credentials expire. Connect again with new credentials when the session token expires.",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="region",
+ label="AWS region",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder=DEFAULT_REGION,
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_inspector/tests/test_aws_inspector.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_inspector/tests/test_aws_inspector.py
new file mode 100644
index 000000000000..f20a8173062d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_inspector/tests/test_aws_inspector.py
@@ -0,0 +1,364 @@
+import json
+import datetime as dt
+from collections.abc import Iterable, Iterator
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from botocore.session import Session
+from botocore.validate import validate_parameters
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_inspector.aws_inspector import (
+ AwsInspectorClient,
+ AwsInspectorError,
+ AwsInspectorResumeConfig,
+ aws_inspector_source,
+ error_for_response,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_inspector.source import AwsInspectorSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsinspector import (
+ AwsInspectorSourceConfig,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.aws_inspector.aws_inspector"
+
+
+def response(payload: object, status: int = 200, headers: dict[str, str] | None = None) -> requests.Response:
+ result = requests.Response()
+ result.status_code = status
+ result._content = json.dumps(payload).encode()
+ result.headers.update(headers or {})
+ return result
+
+
+def config() -> AwsInspectorSourceConfig:
+ return AwsInspectorSourceConfig(
+ aws_access_key_id="AKIAEXAMPLE",
+ aws_secret_access_key="example-secret",
+ aws_session_token="example-session",
+ region="eu-west-1",
+ )
+
+
+def http() -> Iterator[MagicMock]:
+ with patch(f"{MODULE}.make_tracked_session") as factory:
+ factory.return_value.post.return_value = response({})
+ yield factory.return_value
+
+
+def manager() -> MagicMock:
+ result = MagicMock(spec=ResumableSourceManager)
+ result.can_resume.return_value = False
+ return result
+
+
+ "endpoint,operation,result_key,path,page_size",
+ [
+ ("findings", "ListFindings", "findings", "/findings/list", 25),
+ ("coverage", "ListCoverage", "coveredResources", "/coverage/list", 200),
+ ("coverage_statistics", "ListCoverageStatistics", "countsByGroup", "/coverage/statistics/list", None),
+ ],
+)
+def test_signed_requests_and_pagination(
+ config: AwsInspectorSourceConfig,
+ http: MagicMock,
+ manager: MagicMock,
+ endpoint: str,
+ operation: str,
+ result_key: str,
+ path: str,
+ page_size: int | None,
+) -> None:
+ http.post.side_effect = [
+ response({result_key: [{"resourceId": "example-one"}], "nextToken": "page-2"}),
+ response({result_key: [], "nextToken": "page-3"}),
+ response({result_key: [{"resourceId": "example-two"}], "nextToken": ""}),
+ ]
+ resource = aws_inspector_source(config, endpoint, manager, False, None)
+ batches = list(cast(Iterable[Any], resource.items()))
+ assert batches == [
+ [{"resource_id": "example-one", "region": "eu-west-1"}],
+ [{"resource_id": "example-two", "region": "eu-west-1"}],
+ ]
+ model = Session().get_service_model("inspector2", api_version="2020-06-08").operation_model(operation)
+ for index, call in enumerate(http.post.call_args_list):
+ assert call.args == (f"https://inspector2.eu-west-1.amazonaws.com{path}",)
+ assert path == model.http["requestUri"]
+ payload = json.loads(call.kwargs["data"])
+ assert model.input_shape is not None
+ validate_parameters(payload, model.input_shape)
+ assert payload.get("maxResults") == page_size
+ assert payload.get("nextToken") == [None, "page-2", "page-3"][index]
+ assert "filterCriteria" not in payload
+ if endpoint == "coverage_statistics":
+ assert payload["groupBy"] == "RESOURCE_TYPE"
+ headers = call.kwargs["headers"]
+ assert headers["Content-Type"] == "application/json"
+ assert "X-Amz-Target" not in headers
+ assert headers["X-Amz-Security-Token"] == "example-session"
+ assert "/eu-west-1/inspector2/aws4_request" in headers["Authorization"]
+ assert headers["X-Amz-Date"]
+ assert call.kwargs["allow_redirects"] is False
+ assert manager.safe_point.call_count == 3
+ assert manager.save_state.call_args.args[0].completed
+ manager.clear_state.assert_not_called()
+ assert resource.on_complete is not None
+ resource.on_complete()
+ manager.clear_state.assert_called_once()
+ http.close.assert_called_once()
+
+
[email protected]("incremental", [True, False])
[email protected]("endpoint", ["findings", "coverage", "coverage_statistics"])
+def test_incremental_filter_survives_pagination_and_full_refresh_omits_it(
+ config: AwsInspectorSourceConfig, http: MagicMock, manager: MagicMock, incremental: bool, endpoint: str
+) -> None:
+ http.post.side_effect = [response({"nextToken": "page-2"}), response({})]
+ resource = aws_inspector_source(config, endpoint, manager, incremental, "2025-01-01T00:00:00Z")
+ list(cast(Iterable[Any], resource.items()))
+ for call in http.post.call_args_list:
+ payload = json.loads(call.kwargs["data"])
+ if incremental and endpoint == "findings":
+ assert payload["filterCriteria"] == {"updatedAt": [{"startInclusive": 1735689600.0}]}
+ else:
+ assert "filterCriteria" not in payload
+ assert "sortCriteria" not in payload
+ assert resource.sort_mode == "desc"
+
+
[email protected]("completed", [False, True])
+def test_resume_retains_original_filter_and_stages_before_yield(
+ config: AwsInspectorSourceConfig, http: MagicMock, manager: MagicMock, completed: bool
+) -> None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = AwsInspectorResumeConfig(
+ next_token="saved-page", updated_after=1735689600.0, completed=completed
+ )
+ http.post.return_value = response(
+ {"findings": [{"findingArn": "arn:aws:inspector2:eu-west-1:111111111111:finding/example"}]}
+ )
+ resource = aws_inspector_source(config, "findings", manager, True, "2025-02-01T00:00:00Z")
+ rows = iter(cast(Iterable[Any], resource.items()))
+ if completed:
+ assert list(rows) == []
+ http.post.assert_not_called()
+ else:
+ next(rows)
+ assert json.loads(http.post.call_args.kwargs["data"]) == {
+ "maxResults": 25,
+ "nextToken": "saved-page",
+ "filterCriteria": {"updatedAt": [{"startInclusive": 1735689600.0}]},
+ }
+ manager.save_state.assert_called_once_with(AwsInspectorResumeConfig(updated_after=1735689600.0, completed=True))
+ assert list(rows) == []
+ manager.clear_state.assert_not_called()
+
+
[email protected]("value", [1735689600, 1735689600.0, "2025-01-01T00:00:00Z", "2025-01-01T00:00:00"])
+def test_timestamps_and_nested_details(
+ config: AwsInspectorSourceConfig, http: MagicMock, manager: MagicMock, value: str | int | float
+) -> None:
+ details = {"vulnerabilityId": "CVE-2025-0001", "vulnerablePackages": [{"name": "example"}]}
+ http.post.return_value = response(
+ {
+ "findings": [
+ {
+ "findingArn": "example",
+ "firstObservedAt": value,
+ "updatedAt": value,
+ "packageVulnerabilityDetails": details,
+ }
+ ]
+ }
+ )
+ resource = aws_inspector_source(config, "findings", manager, True, value)
+ row = next(iter(cast(Iterable[Any], resource.items())))[0]
+ assert row["updated_at"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)
+ assert row["first_observed_at"] == row["updated_at"]
+ assert row["package_vulnerability_details"] == details
+ assert resource.primary_keys == ["finding_arn"]
+ assert resource.partition_keys == ["first_observed_at"]
+
+
[email protected]("token", ["same", 42])
+def test_invalid_pagination_does_not_complete(
+ config: AwsInspectorSourceConfig, http: MagicMock, manager: MagicMock, token: str | int
+) -> None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = AwsInspectorResumeConfig(next_token="same")
+ http.post.return_value = response({"nextToken": token})
+ with pytest.raises(ValueError, match="invalid pagination token"):
+ list(cast(Iterable[Any], aws_inspector_source(config, "findings", manager, False, None).items()))
+ manager.save_state.assert_not_called()
+ manager.clear_state.assert_not_called()
+ http.close.assert_called_once()
+
+
+ "code,status,schema,success,message",
+ [
+ ("AccessDeniedException", 403, None, True, None),
+ ("AccessDeniedException", 403, "coverage", False, "inspector2:ListCoverage"),
+ ("AccessDenied", 403, "findings", False, "inspector2:ListFindings"),
+ ("UnrecognizedClientException", 403, None, False, "AWS rejected the credentials"),
+ ("InvalidClientTokenId", 403, None, False, "access key ID"),
+ ("InvalidSignatureException", 403, None, False, "signature"),
+ ("SignatureDoesNotMatch", 403, None, False, "signature"),
+ ("ExpiredTokenException", 403, None, False, "expired"),
+ ("SubscriptionRequiredException", 400, None, False, "Enable Amazon Inspector"),
+ ("OptInRequired", 403, None, False, "Enable Amazon Inspector"),
+ ],
+)
+def test_credential_errors(
+ config: AwsInspectorSourceConfig,
+ http: MagicMock,
+ code: str,
+ status: int,
+ schema: str | None,
+ success: bool,
+ message: str | None,
+) -> None:
+ http.post.return_value = response({"message": "example error"}, status, {"x-amzn-ErrorType": f"{code}:details"})
+ valid, reason = validate_credentials(config, schema)
+ assert valid is success
+ if message:
+ assert reason is not None and message in reason
+ else:
+ assert reason is None
+ error = error_for_response(http.post.return_value)
+ matches = [
+ text for pattern, text in AwsInspectorSource().get_non_retryable_errors().items() if pattern in str(error)
+ ]
+ assert matches
+ assert all(matches)
+ http.close.assert_called_once()
+
+
+ "status,code", [(429, "ThrottlingException"), (500, "InternalServerException"), (503, "HTTP 503")]
+)
+def test_transient_errors_propagate(config: AwsInspectorSourceConfig, http: MagicMock, status: int, code: str) -> None:
+ http.post.return_value = response({"__type": code}, status)
+ with pytest.raises(AwsInspectorError, match=code):
+ validate_credentials(config)
+ assert not any(
+ pattern in f"AWS Inspector request failed: {code}"
+ for pattern in AwsInspectorSource().get_non_retryable_errors()
+ )
+
+
+ "schema,expected", [(None, {"maxResults": 1}), ("coverage_statistics", {"groupBy": "RESOURCE_TYPE"})]
+)
+def test_credential_probe_is_one_small_request(
+ config: AwsInspectorSourceConfig, http: MagicMock, schema: str | None, expected: dict[str, Any]
+) -> None:
+ assert validate_credentials(config, schema) == (True, None)
+ http.post.assert_called_once()
+ assert json.loads(http.post.call_args.kwargs["data"]) == expected
+
+
[email protected]("region", ["https://example.com", "us-east-1.example.com", "us-east-1/", "", "US-EAST-1"])
+def test_invalid_region_never_sends_credentials(config: AwsInspectorSourceConfig, http: MagicMock, region: str) -> None:
+ config.region = region
+ valid, reason = validate_credentials(config)
+ assert not valid
+ assert reason and "region code" in reason
+ http.post.assert_not_called()
+
+
[email protected]("field", ["aws_access_key_id", "aws_secret_access_key"])
+def test_missing_credentials(config: AwsInspectorSourceConfig, http: MagicMock, field: str) -> None:
+ setattr(config, field, "")
+ assert validate_credentials(config) == (False, "Enter both an AWS access key ID and a secret access key.")
+ http.post.assert_not_called()
+
+
+def test_unknown_schema_and_version(config: AwsInspectorSourceConfig, http: MagicMock, manager: MagicMock) -> None:
+ assert validate_credentials(config, "unknown") == (False, "Unknown AWS Inspector table: unknown")
+ assert validate_credentials(config, api_version="1999-01-01") == (
+ False,
+ "Unsupported AWS Inspector API version: 1999-01-01",
+ )
+ with pytest.raises(ValueError, match="Unknown AWS Inspector table"):
+ aws_inspector_source(config, "unknown", manager, False, None)
+ http.post.assert_not_called()
+
+
[email protected]("region,suffix", [("cn-north-1", "amazonaws.com.cn"), ("us-gov-west-1", "amazonaws.com")])
+def test_regional_signing_without_session_token(
+ config: AwsInspectorSourceConfig, http: MagicMock, region: str, suffix: str
+) -> None:
+ config.region = region
+ config.aws_session_token = None
+ assert validate_credentials(config) == (True, None)
+ assert http.post.call_args.args == (f"https://inspector2.{region}.{suffix}/findings/list",)
+ headers = http.post.call_args.kwargs["headers"]
+ assert "X-Amz-Security-Token" not in headers
+ assert f"/{region}/inspector2/aws4_request" in headers["Authorization"]
+
+
+ "payload,headers,status,code",
+ [
+ ({"__type": "com.amazonaws#UnrecognizedClientException"}, {}, 400, "UnrecognizedClientException"),
+ ({"code": "InvalidSignatureException"}, {}, 400, "InvalidSignatureException"),
+ ({"message": "Amazon Inspector is not enabled for this account"}, {}, 403, "SubscriptionRequiredException"),
+ ([], {}, 503, "HTTP 503"),
+ ({}, {}, 401, "HTTP 401"),
+ ],
+)
+def test_error_shapes(payload: object, headers: dict[str, str], status: int, code: str) -> None:
+ assert error_for_response(response(payload, status, headers)).code == code
+
+
+def test_transport_retries_read_only_posts_and_redacts_credentials(config: AwsInspectorSourceConfig) -> None:
+ with patch(f"{MODULE}.make_tracked_session") as factory:
+ AwsInspectorClient(config)
+ retry = factory.call_args.kwargs["retry"]
+ assert retry.is_retry("POST", 429, has_retry_after=True)
+ assert retry.is_retry("POST", 500)
+ assert not retry.is_retry("POST", 403)
+ assert not retry.is_retry("POST", 400)
+ assert factory.call_args.kwargs["redact_values"] == ("AKIAEXAMPLE", "example-secret", "example-session")
+
+
+def test_coverage_keys_keep_scan_types_distinct(
+ config: AwsInspectorSourceConfig, http: MagicMock, manager: MagicMock
+) -> None:
+ resource_fields = {"accountId": "111111111111", "resourceId": "i-example", "resourceType": "AWS_EC2_INSTANCE"}
+ http.post.return_value = response(
+ {
+ "coveredResources": [
+ {**resource_fields, "scanType": "PACKAGE", "lastScannedAt": 1735689600},
+ {**resource_fields, "scanType": "NETWORK", "lastScannedAt": None},
+ ]
+ }
+ )
+ resource = aws_inspector_source(config, "coverage", manager, False, None)
+ rows = next(iter(cast(Iterable[Any], resource.items())))
+ assert resource.primary_keys is not None
+ assert len({tuple(row[key] for key in resource.primary_keys) for row in rows}) == 2
+ assert rows[0]["last_scanned_at"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)
+ assert rows[1]["last_scanned_at"] is None
+
+
[email protected]("status", [200, 503])
+def test_malformed_response(config: AwsInspectorSourceConfig, http: MagicMock, status: int) -> None:
+ http.post.return_value = response([], status)
+ if status == 200:
+ with pytest.raises(ValueError, match="invalid response"):
+ validate_credentials(config)
+ else:
+ http.post.return_value._content = b"not JSON"
+ with pytest.raises(AwsInspectorError, match="HTTP 503"):
+ validate_credentials(config)
+ http.close.assert_called_once()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsinspector.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsinspector.py
index 3fad265e2642..204f14147902 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsinspector.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsinspector.py
@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class AwsInspectorSourceConfig(config.Config):
- pass
+ aws_access_key_id: str
+ aws_secret_access_key: str
+ region: str
+ aws_session_token: str | None = None