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): add aws inspector cis, member, and cluster tables (#117715)

Tom Owers955bc082e4a3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index ef96d84efbc8..b8aa29279bf0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -1218,14 +1218,14 @@ Note: Compared the official botocore operation model with the static endpoint ma
## AWS Inspector — gaps
-Today (3): `coverage`, `coverage_statistics`, `findings`
+Today (7): `cis_scan_result_details`, `cis_scans`, `clusters_for_image`, `coverage`, `coverage_statistics`, `findings`, `members`
Diffed against: <https://raw.githubusercontent.com/boto/botocore/develop/botocore/data/inspector2/2020-06-08/service-2.json>
-- [ ] `Members (ListMembers, POST /members/list)` — links account IDs in findings and coverage to delegated administrators and membership status (high)
-- [ ] `CIS scans (ListCisScans, POST /cis/scan/list)` — tracks benchmark scan history and failed check counts beyond vulnerability findings (high)
-- [ ] `CIS scan result details (GetCisScanResultDetails, POST /cis/scan-result/details/get)` — provides individual benchmark check outcomes and remediation guidance for each scanned resource (high)
-- [ ] `Clusters for image (GetClustersForImage, POST /cluster/get)` — links vulnerable container images to running clusters for workload exposure analysis (medium)
+- [x] `Members (ListMembers, POST /members/list)` — links account IDs in findings and coverage to delegated administrators and membership status (high)
+- [x] `CIS scans (ListCisScans, POST /cis/scan/list)` — tracks benchmark scan history and failed check counts beyond vulnerability findings (high)
+- [x] `CIS scan result details (GetCisScanResultDetails, POST /cis/scan-result/details/get)` — provides individual benchmark check outcomes and remediation guidance for each scanned resource (high)
+- [x] `Clusters for image (GetClustersForImage, POST /cluster/get)` — links vulnerable container images to running clusters for workload exposure analysis (medium)
- [ ] `Usage totals (ListUsageTotals, POST /usage/list)` — reports scanning usage and estimated cost by account over the last 30 days (medium)
Note: Compared the official Inspector V2 botocore operation model with the static endpoint map and extraction code. CIS details require scan discovery, target traversal through ListCisScanResultsAggregatedByTargetResource, and calls for each target and account. Image associations require ECR resource IDs from synced findings; membership reads require administrator permissions. Scan configuration, filters, integration setup, and asynchronous exports were excluded.
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
index b8cbd8b915e5..ab5d831f0cbc 100644
--- 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
@@ -1,7 +1,7 @@
import re
import json
import datetime as dt
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from typing import Any
import requests
@@ -13,7 +13,10 @@ from posthog.dataclasses import frozen
from products.warehouse_sources.backend.temporal.data_imports.sources.aws_inspector.settings import (
AWS_INSPECTOR_ENDPOINTS,
+ CIS_SCAN_TARGETS_ENDPOINT,
+ CIS_SCANS_ENDPOINT,
ERROR_MESSAGES,
+ INCREMENTAL_FIELDS,
INSPECTOR_API_VERSION,
AwsInspectorEndpoint,
)
@@ -33,6 +36,10 @@ TRANSPORT_RETRY = BoundedRetry(
raise_on_status=False,
)
_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
+ECR_IMAGE_COVERAGE_FILTER = {
+ "resourceType": [{"comparison": "EQUALS", "value": "AWS_ECR_CONTAINER_IMAGE"}],
+ "scanType": [{"comparison": "EQUALS", "value": "PACKAGE"}],
+}
@frozen
@@ -40,6 +47,16 @@ class AwsInspectorResumeConfig:
next_token: str | None = None
updated_after: float | None = None
completed: bool = False
+ scan_arn: str | None = None
+ parent_token: str | None = None
+ parent_key: str | None = None
+
+
+@frozen
+class FanOutPosition:
+ parent_token: str | None = None
+ parent_key: str | None = None
+ next_token: str | None = None
class AwsInspectorError(Exception):
@@ -128,9 +145,36 @@ def request_payload(endpoint: AwsInspectorEndpoint, updated_after: float | None
payload["groupBy"] = "RESOURCE_TYPE"
if endpoint.operation == "ListFindings" and updated_after is not None:
payload["filterCriteria"] = {"updatedAt": [{"startInclusive": updated_after}]}
+ if endpoint.operation == "ListMembers":
+ payload["onlyAssociated"] = False
+ if endpoint.operation == "ListCisScans":
+ payload["sortBy"] = "SCAN_START_DATE"
+ payload["sortOrder"] = "ASC"
+ if updated_after is not None:
+ payload["filterCriteria"] = {"scanAtFilters": [{"earliestScanStartTime": updated_after}]}
+ if endpoint.operation == "ListCisScanResultsAggregatedByTargetResource":
+ payload["sortBy"] = "RESOURCE_ID"
+ payload["sortOrder"] = "ASC"
+ if endpoint.operation == "GetCisScanResultDetails":
+ payload["sortBy"] = "CHECK_ID"
+ payload["sortOrder"] = "ASC"
return payload
+def next_page_token(body: dict[str, Any], current: str | None) -> str | None:
+ token = body.get("nextToken") or None
+ if token is not None and (not isinstance(token, str) or token == current):
+ raise ValueError("AWS Inspector returned an invalid pagination token.")
+ return token
+
+
+def fetch_page(
+ client: AwsInspectorClient, endpoint: AwsInspectorEndpoint, payload: dict[str, Any], token: str | None
+) -> tuple[list[dict[str, Any]], str | None]:
+ body = client.request(endpoint, {**payload, "nextToken": token} if token else payload)
+ return list(body.get(endpoint.result_key) or []), next_page_token(body, token)
+
+
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:
@@ -160,9 +204,7 @@ def get_rows(
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.")
+ token = next_page_token(body, next_token)
manager.save_state(
AwsInspectorResumeConfig(
next_token=token,
@@ -180,6 +222,202 @@ def get_rows(
client.close()
+def fan_out(
+ client: AwsInspectorClient,
+ endpoint: AwsInspectorEndpoint,
+ parent_payload: dict[str, Any],
+ key_of: Callable[[dict[str, Any]], str],
+ child_payload: Callable[[dict[str, Any]], dict[str, Any]],
+ parent_fields: Callable[[dict[str, Any]], dict[str, Any]],
+ region: str,
+ position: FanOutPosition,
+ stage: Callable[[FanOutPosition | None], None],
+ manager: ResumableSourceManager[AwsInspectorResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk the parent listing and call `endpoint` once for each parent, from `position` on.
+
+ `stage` receives the position after each child page, or `None` once the walk is complete.
+ """
+ if endpoint.parent is None:
+ raise ValueError(f"AWS Inspector table has no parent listing: {endpoint.operation}")
+ parent_token, resume_key, resume_token = position.parent_token, position.parent_key, position.next_token
+ while True:
+ parents, next_parent_token = fetch_page(client, endpoint.parent, parent_payload, parent_token)
+ manager.safe_point()
+ keys = [key_of(parent) for parent in parents]
+ start = keys.index(resume_key) if resume_key in keys else 0
+ if resume_key not in keys:
+ resume_token = None
+ resume_key = None
+ for index in range(start, len(parents)):
+ token, resume_token = resume_token, None
+ payload = {**request_payload(endpoint), **child_payload(parents[index])}
+ while True:
+ items, next_token = fetch_page(client, endpoint, payload, token)
+ if next_token is not None:
+ stage(FanOutPosition(parent_token=parent_token, parent_key=keys[index], next_token=next_token))
+ elif index + 1 < len(parents):
+ stage(FanOutPosition(parent_token=parent_token, parent_key=keys[index + 1]))
+ elif next_parent_token is not None:
+ stage(FanOutPosition(parent_token=next_parent_token))
+ else:
+ stage(None)
+ fields = parent_fields(parents[index])
+ rows = [normalize_row(endpoint, {**item, **fields}, region) for item in items]
+ if rows:
+ yield rows
+ manager.safe_point()
+ if next_token is None:
+ break
+ token = next_token
+ if next_parent_token is None:
+ return
+ parent_token = next_parent_token
+
+
+def list_cis_scans(
+ client: AwsInspectorClient,
+ manager: ResumableSourceManager[AwsInspectorResumeConfig],
+ scans_after: float | None,
+ incremental: bool,
+) -> list[dict[str, Any]]:
+ payload = request_payload(CIS_SCANS_ENDPOINT, scans_after)
+ scans: list[dict[str, Any]] = []
+ token: str | None = None
+ while True:
+ items, token = fetch_page(client, CIS_SCANS_ENDPOINT, payload, token)
+ scans.extend(item for item in items if item.get("scanArn") and item.get("scanDate") is not None)
+ manager.safe_point()
+ if token is None:
+ break
+ if incremental:
+ # The watermark is the latest scan date synced, so an unfinished scan would be skipped for good
+ # once a later scan finishes. Stop before the earliest unfinished scan until it finishes.
+ unfinished = [timestamp(scan["scanDate"]) for scan in scans if scan.get("status") == "IN_PROGRESS"]
+ if unfinished:
+ scans = [scan for scan in scans if timestamp(scan["scanDate"]) < min(unfinished)]
+ return sorted(scans, key=lambda scan: (timestamp(scan["scanDate"]), scan["scanArn"]))
+
+
+def get_cis_scan_result_details(
+ config: AwsInspectorSourceConfig,
+ endpoint: AwsInspectorEndpoint,
+ manager: ResumableSourceManager[AwsInspectorResumeConfig],
+ scans_after: float | None,
+ incremental: bool,
+ 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
+ scans_after = state.updated_after if state else scans_after
+ client = AwsInspectorClient(config, api_version)
+ try:
+ scans = list_cis_scans(client, manager, scans_after, incremental)
+ arns = [scan["scanArn"] for scan in scans]
+ resumed = state is not None and state.scan_arn in arns
+ start = arns.index(state.scan_arn) if state is not None and resumed else 0
+ for index in range(start, len(scans)):
+ scan = scans[index]
+ position = (
+ FanOutPosition(
+ parent_token=state.parent_token, parent_key=state.parent_key, next_token=state.next_token
+ )
+ if state is not None and resumed and index == start
+ else FanOutPosition()
+ )
+
+ def stage(next_position: FanOutPosition | None, index: int = index) -> None:
+ if next_position is not None:
+ resume = AwsInspectorResumeConfig(
+ updated_after=scans_after,
+ scan_arn=arns[index],
+ parent_token=next_position.parent_token,
+ parent_key=next_position.parent_key,
+ next_token=next_position.next_token,
+ )
+ elif index + 1 < len(arns):
+ resume = AwsInspectorResumeConfig(updated_after=scans_after, scan_arn=arns[index + 1])
+ else:
+ resume = AwsInspectorResumeConfig(updated_after=scans_after, completed=True)
+ manager.save_state(resume)
+
+ def child_payload(target: dict[str, Any], scan_arn: str = arns[index]) -> dict[str, Any]:
+ return {
+ "scanArn": scan_arn,
+ "targetResourceId": target.get("targetResourceId"),
+ "accountId": target.get("accountId"),
+ }
+
+ def parent_fields(target: dict[str, Any], scan: dict[str, Any] = scan) -> dict[str, Any]:
+ return {
+ "scanArn": scan["scanArn"],
+ "scanDate": scan["scanDate"],
+ "accountId": target.get("accountId"),
+ "targetResourceId": target.get("targetResourceId"),
+ }
+
+ yield from fan_out(
+ client,
+ endpoint,
+ {**request_payload(CIS_SCAN_TARGETS_ENDPOINT), "scanArn": scan["scanArn"]},
+ key_of=lambda target: f"{target.get('accountId')}/{target.get('targetResourceId')}",
+ child_payload=child_payload,
+ parent_fields=parent_fields,
+ region=config.region,
+ position=position,
+ stage=stage,
+ manager=manager,
+ )
+ finally:
+ client.close()
+
+
+def get_clusters_for_image(
+ config: AwsInspectorSourceConfig,
+ endpoint: AwsInspectorEndpoint,
+ manager: ResumableSourceManager[AwsInspectorResumeConfig],
+ 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
+ position = (
+ FanOutPosition(parent_token=state.parent_token, parent_key=state.parent_key, next_token=state.next_token)
+ if state is not None
+ else FanOutPosition()
+ )
+
+ def stage(next_position: FanOutPosition | None) -> None:
+ manager.save_state(
+ AwsInspectorResumeConfig(
+ parent_token=next_position.parent_token,
+ parent_key=next_position.parent_key,
+ next_token=next_position.next_token,
+ )
+ if next_position is not None
+ else AwsInspectorResumeConfig(completed=True)
+ )
+
+ assert endpoint.parent is not None
+ client = AwsInspectorClient(config, api_version)
+ try:
+ yield from fan_out(
+ client,
+ endpoint,
+ {**request_payload(endpoint.parent), "filterCriteria": ECR_IMAGE_COVERAGE_FILTER},
+ key_of=lambda image: str(image.get("resourceId")),
+ child_payload=lambda image: {"filter": {"resourceId": image.get("resourceId")}},
+ parent_fields=lambda image: {"resourceId": image.get("resourceId")},
+ region=config.region,
+ position=position,
+ stage=stage,
+ manager=manager,
+ )
+ finally:
+ client.close()
+
+
def validate_credentials(
config: AwsInspectorSourceConfig,
schema_name: str | None = None,
@@ -188,20 +426,23 @@ def validate_credentials(
endpoint = AWS_INSPECTOR_ENDPOINTS.get(schema_name or "findings")
if endpoint is None:
return False, f"Unknown AWS Inspector table: {schema_name}"
+ probe = endpoint
+ while probe.parent is not None:
+ probe = probe.parent
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 = request_payload(probe)
+ if probe.page_size is not None:
payload["maxResults"] = 1
try:
- client.request(endpoint, payload)
+ client.request(probe, 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."
+ return False, f"Grant {', '.join(endpoint.iam_actions)} to read this table."
message = error_message(error)
if message:
return False, message
@@ -224,12 +465,21 @@ def aws_inspector_source(
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
+ if endpoint in INCREMENTAL_FIELDS and should_use_incremental_field and last_value is not None
else None
)
+ items: Callable[[], Iterator[list[dict[str, Any]]]]
+ if endpoint_config.operation == "GetCisScanResultDetails":
+ items = lambda: get_cis_scan_result_details(
+ config, endpoint_config, manager, updated_after, should_use_incremental_field, api_version
+ )
+ elif endpoint_config.operation == "GetClustersForImage":
+ items = lambda: get_clusters_for_image(config, endpoint_config, manager, api_version)
+ else:
+ items = lambda: get_rows(config, endpoint_config, manager, updated_after, api_version)
return SourceResponse(
name=endpoint,
- items=lambda: get_rows(config, endpoint_config, manager, updated_after, api_version),
+ items=items,
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,
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
index 16f29789c8ae..a40dba039e88 100644
--- 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
@@ -53,4 +53,62 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"region": "AWS region selected for this source.",
},
},
+ "members": {
+ "description": "Member accounts of the Amazon Inspector delegated administrator, with one row for each account.",
+ "docs_url": "https://docs.aws.amazon.com/inspector/v2/APIReference/API_Member.html",
+ "columns": {
+ "account_id": "AWS account ID of the member account.",
+ "relationship_status": "Status of the member account, such as enabled, disabled, or removed.",
+ "delegated_admin_account_id": "AWS account ID of the Amazon Inspector delegated administrator for this member.",
+ "updated_at": "Time when the member account was last updated.",
+ "region": "AWS region selected for this source.",
+ },
+ },
+ "cis_scans": {
+ "description": "CIS benchmark scans run by Amazon Inspector, with one row for each scan.",
+ "docs_url": "https://docs.aws.amazon.com/inspector/v2/APIReference/API_CisScan.html",
+ "columns": {
+ "scan_arn": "ARN that identifies the scan.",
+ "scan_configuration_arn": "ARN of the scan configuration that started the scan.",
+ "status": "Scan status: in progress, completed, cancelled, or failed.",
+ "scan_name": "Name of the scan.",
+ "scan_date": "Time when the scan started.",
+ "failed_checks": "Number of checks that failed in the scan.",
+ "total_checks": "Number of checks in the scan.",
+ "targets": "Accounts and resource tags that the scan targets.",
+ "scheduled_by": "Account or service that scheduled the scan.",
+ "security_level": "CIS security level of the scan.",
+ "region": "AWS region selected for this source.",
+ },
+ },
+ "cis_scan_result_details": {
+ "description": "Outcome of each CIS benchmark check, with one row for each scan, resource, and check.",
+ "docs_url": "https://docs.aws.amazon.com/inspector/v2/APIReference/API_CisScanResultDetails.html",
+ "columns": {
+ "scan_arn": "ARN of the scan that ran the check.",
+ "scan_date": "Time when the scan started.",
+ "account_id": "AWS account that owns the scanned resource.",
+ "target_resource_id": "Identifier of the scanned resource.",
+ "platform": "Operating system platform of the scanned resource.",
+ "status": "Check outcome: passed, failed, or skipped.",
+ "status_reason": "Reason for the check outcome.",
+ "check_id": "Identifier of the CIS check.",
+ "title": "Title of the CIS check.",
+ "check_description": "Description of the CIS check.",
+ "remediation": "Steps to correct a failed check.",
+ "level": "CIS security level of the check.",
+ "finding_arn": "ARN of the finding for the check.",
+ "region": "AWS region selected for this source.",
+ },
+ },
+ "clusters_for_image": {
+ "description": "Amazon ECS and Amazon EKS clusters that use each Amazon ECR image that Inspector covers.",
+ "docs_url": "https://docs.aws.amazon.com/inspector/v2/APIReference/API_GetClustersForImage.html",
+ "columns": {
+ "resource_id": "ARN of the Amazon ECR image.",
+ "cluster_arn": "ARN of the cluster that uses the image.",
+ "cluster_details": "Workloads in the cluster that use the image, with running and stopped unit counts and the time the image was last in use.",
+ "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
index 071bed61f870..3da7c68f506a 100644
--- 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
@@ -15,6 +15,40 @@ class AwsInspectorEndpoint:
page_size: int | None = None
timestamp_columns: tuple[str, ...] = ()
partition_key: str | None = None
+ # A fan-out table probes and walks this listing, then calls its own operation once per listed item.
+ parent: "AwsInspectorEndpoint | None" = None
+
+ @property
+ def iam_actions(self) -> tuple[str, ...]:
+ parent_actions = self.parent.iam_actions if self.parent else ()
+ return (*parent_actions, f"inspector2:{self.operation}")
+
+
+COVERAGE_ENDPOINT = 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",),
+)
+CIS_SCANS_ENDPOINT = AwsInspectorEndpoint(
+ operation="ListCisScans",
+ path="/cis/scan/list",
+ result_key="scans",
+ primary_keys=("scan_arn",),
+ page_size=100,
+ timestamp_columns=("scan_date",),
+ partition_key="scan_date",
+)
+CIS_SCAN_TARGETS_ENDPOINT = AwsInspectorEndpoint(
+ operation="ListCisScanResultsAggregatedByTargetResource",
+ path="/cis/scan-result/resource/list",
+ result_key="targetResourceAggregations",
+ primary_keys=("scan_arn", "account_id", "target_resource_id"),
+ page_size=100,
+ parent=CIS_SCANS_ENDPOINT,
+)
AWS_INSPECTOR_ENDPOINTS = {
@@ -27,20 +61,40 @@ AWS_INSPECTOR_ENDPOINTS = {
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": COVERAGE_ENDPOINT,
"coverage_statistics": AwsInspectorEndpoint(
operation="ListCoverageStatistics",
path="/coverage/statistics/list",
result_key="countsByGroup",
primary_keys=("region", "group_key"),
),
+ "members": AwsInspectorEndpoint(
+ operation="ListMembers",
+ path="/members/list",
+ result_key="members",
+ primary_keys=("region", "account_id"),
+ page_size=50,
+ timestamp_columns=("updated_at",),
+ ),
+ "cis_scans": CIS_SCANS_ENDPOINT,
+ "cis_scan_result_details": AwsInspectorEndpoint(
+ operation="GetCisScanResultDetails",
+ path="/cis/scan-result/details/get",
+ result_key="scanResultDetails",
+ primary_keys=("scan_arn", "account_id", "target_resource_id", "check_id"),
+ page_size=1000,
+ timestamp_columns=("scan_date",),
+ partition_key="scan_date",
+ parent=CIS_SCAN_TARGETS_ENDPOINT,
+ ),
+ "clusters_for_image": AwsInspectorEndpoint(
+ operation="GetClustersForImage",
+ path="/cluster/get",
+ result_key="cluster",
+ primary_keys=("resource_id", "cluster_arn"),
+ page_size=100,
+ parent=COVERAGE_ENDPOINT,
+ ),
}
ENDPOINTS = tuple(AWS_INSPECTOR_ENDPOINTS)
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
@@ -51,16 +105,28 @@ INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
"field": "updated_at",
"field_type": IncrementalFieldType.DateTime,
}
- ]
+ ],
+ "cis_scan_result_details": [
+ {
+ "label": "scan_date",
+ "type": IncrementalFieldType.DateTime,
+ "field": "scan_date",
+ "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.",
+ "members": "Member accounts of the Amazon Inspector delegated administrator, with their relationship status.",
+ "cis_scans": "CIS benchmark scans with their status and passed and failed check counts.",
+ "cis_scan_result_details": "Outcome of each CIS benchmark check for each scanned resource.",
+ "clusters_for_image": "Amazon ECS and Amazon EKS clusters that run each Amazon ECR image Inspector covers.",
}
ERROR_MESSAGES = {
- "AccessDenied": "Grant inspector2:ListFindings, inspector2:ListCoverage, or inspector2:ListCoverageStatistics for the tables you select.",
+ "AccessDenied": "AWS denied access. Grant the Amazon Inspector IAM permissions listed in the source setup 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.",
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 46b2647a7552..985a4b9b5160 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
@@ -126,10 +126,17 @@ class AwsInspectorSource(ResumableSource[AwsInspectorSourceConfig, AwsInspectorR
name=ExternalDataSourceType.AWSINSPECTOR,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="AWS Inspector",
- caption="""Sync Amazon Inspector findings and scan coverage into the PostHog Data warehouse.
+ caption="""Sync Amazon Inspector findings, scan coverage, and CIS scans 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`.
+
+- `findings`: `inspector2:ListFindings`
+- `coverage`: `inspector2:ListCoverage`
+- `coverage_statistics`: `inspector2:ListCoverageStatistics`
+- `members`: `inspector2:ListMembers` (delegated administrator account only)
+- `cis_scans`: `inspector2:ListCisScans`
+- `cis_scan_result_details`: `inspector2:ListCisScans`, `inspector2:ListCisScanResultsAggregatedByTargetResource`, and `inspector2:GetCisScanResultDetails`
+- `clusters_for_image`: `inspector2:ListCoverage` and `inspector2:GetClustersForImage`
Enter your access key ID and secret access key. Add a session token if you use temporary credentials.
This source reads one AWS region.""",
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
index 3fbc4018c90c..dd1b04e2d7e7 100644
--- 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
@@ -25,17 +25,102 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.tes
SourceDriver,
scripted_network,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing.fake_network import RecordedRequest
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing.responders import route
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"
+SERVICE_MODEL = Session().get_service_model("inspector2", api_version="2020-06-08")
+SCAN_ONE = "arn:aws:inspector2:eu-west-1:111111111111:owner/111111111111/cis-scan/00000000-0000-4000-8000-000000000001"
+SCAN_TWO = "arn:aws:inspector2:eu-west-1:111111111111:owner/111111111111/cis-scan/00000000-0000-4000-8000-000000000002"
+SCAN_THREE = (
+ "arn:aws:inspector2:eu-west-1:111111111111:owner/111111111111/cis-scan/00000000-0000-4000-8000-000000000003"
+)
+IMAGE_ONE = "arn:aws:ecr:eu-west-1:111111111111:repository/example/sha256:" + "a" * 64
+IMAGE_TWO = "arn:aws:ecr:eu-west-1:111111111111:repository/example/sha256:" + "b" * 64
def driver(config: AwsInspectorSourceConfig) -> SourceDriver:
return SourceDriver(AwsInspectorSource(), config)
+def assert_valid_request(request: RecordedRequest) -> dict[str, Any]:
+ operation = next(
+ SERVICE_MODEL.operation_model(name)
+ for name in SERVICE_MODEL.operation_names
+ if SERVICE_MODEL.operation_model(name).http["requestUri"] == request.path
+ )
+ payload = request.json()
+ assert operation.input_shape is not None
+ validate_parameters(payload, operation.input_shape)
+ return payload
+
+
+def details_script() -> dict[str, list[ScriptedResponse]]:
+ scans = [
+ {"scanArn": SCAN_TWO, "scanConfigurationArn": "example", "status": "COMPLETED", "scanDate": 1735776000},
+ {"scanArn": SCAN_THREE, "scanConfigurationArn": "example", "status": "IN_PROGRESS", "scanDate": 1735862400},
+ ]
+ return {
+ "/cis/scan/list": [
+ ScriptedResponse(
+ json={
+ "scans": [
+ {
+ "scanArn": SCAN_ONE,
+ "scanConfigurationArn": "example",
+ "status": "COMPLETED",
+ "scanDate": 1735689600,
+ }
+ ],
+ "nextToken": "scans-2",
+ }
+ ),
+ ScriptedResponse(json={"scans": scans}),
+ ],
+ "/cis/scan-result/resource/list": [
+ ScriptedResponse(
+ json={
+ "targetResourceAggregations": [
+ {"scanArn": SCAN_ONE, "accountId": "111111111111", "targetResourceId": "i-0000000000000001"}
+ ],
+ "nextToken": "targets-2",
+ }
+ ),
+ ScriptedResponse(
+ json={
+ "targetResourceAggregations": [
+ {"scanArn": SCAN_ONE, "accountId": "111111111111", "targetResourceId": "i-0000000000000002"}
+ ]
+ }
+ ),
+ ScriptedResponse(
+ json={
+ "targetResourceAggregations": [
+ {"scanArn": SCAN_TWO, "accountId": "222222222222", "targetResourceId": "i-0000000000000001"}
+ ]
+ }
+ ),
+ ScriptedResponse(
+ json={
+ "targetResourceAggregations": [
+ {"scanArn": SCAN_THREE, "accountId": "222222222222", "targetResourceId": "i-0000000000000001"}
+ ]
+ }
+ ),
+ ],
+ "/cis/scan-result/details/get": [
+ ScriptedResponse(json={"scanResultDetails": [{"scanArn": SCAN_ONE, "checkId": "1.1"}], "nextToken": "d-2"}),
+ ScriptedResponse(json={"scanResultDetails": [{"scanArn": SCAN_ONE, "checkId": "1.2", "status": "FAILED"}]}),
+ ScriptedResponse(json={"scanResultDetails": []}),
+ ScriptedResponse(json={"scanResultDetails": [{"scanArn": SCAN_TWO, "checkId": "1.1"}]}),
+ ScriptedResponse(json={"scanResultDetails": [{"scanArn": SCAN_THREE, "checkId": "1.1"}]}),
+ ],
+ }
+
+
def response(payload: object, status: int = 200, headers: dict[str, str] | None = None) -> requests.Response:
result = requests.Response()
result.status_code = status
@@ -74,6 +159,8 @@ def manager() -> MagicMock:
("findings", "ListFindings", "findings", "/findings/list", 25),
("coverage", "ListCoverage", "coveredResources", "/coverage/list", 200),
("coverage_statistics", "ListCoverageStatistics", "countsByGroup", "/coverage/statistics/list", None),
+ ("members", "ListMembers", "members", "/members/list", 50),
+ ("cis_scans", "ListCisScans", "scans", "/cis/scan/list", 100),
],
)
def test_signed_requests_and_pagination(
@@ -240,6 +327,7 @@ def test_invalid_pagination_does_not_complete(
("AccessDeniedException", 403, None, True, None),
("AccessDeniedException", 403, "coverage", False, "inspector2:ListCoverage"),
("AccessDenied", 403, "findings", False, "inspector2:ListFindings"),
+ ("AccessDeniedException", 403, "cis_scan_result_details", False, "inspector2:GetCisScanResultDetails"),
("UnrecognizedClientException", 403, None, False, "AWS rejected the credentials"),
("InvalidClientTokenId", 403, None, False, "access key ID"),
("InvalidSignatureException", 403, None, False, "signature"),
@@ -289,7 +377,13 @@ def test_transient_errors_propagate(config: AwsInspectorSourceConfig, status: in
@pytest.mark.parametrize(
- "schema,expected", [(None, {"maxResults": 1}), ("coverage_statistics", {"groupBy": "RESOURCE_TYPE"})]
+ "schema,expected",
+ [
+ (None, {"maxResults": 1}),
+ ("coverage_statistics", {"groupBy": "RESOURCE_TYPE"}),
+ ("cis_scan_result_details", {"maxResults": 1, "sortBy": "SCAN_START_DATE", "sortOrder": "ASC"}),
+ ("clusters_for_image", {"maxResults": 1}),
+ ],
)
def test_credential_probe_is_one_small_request(
config: AwsInspectorSourceConfig, schema: str | None, expected: dict[str, Any]
@@ -408,3 +502,127 @@ def test_malformed_response(config: AwsInspectorSourceConfig, http: MagicMock, s
with pytest.raises(AwsInspectorError, match="HTTP 503"):
validate_credentials(config)
http.close.assert_called_once()
+
+
[email protected]("incremental", [False, True])
+def test_cis_scan_result_details_walk_every_scan_target_and_page(
+ config: AwsInspectorSourceConfig, incremental: bool
+) -> None:
+ result = driver(config).run(
+ "cis_scan_result_details",
+ route(details_script()),
+ should_use_incremental_field=incremental,
+ db_incremental_field_last_value="2025-01-01T00:00:00Z" if incremental else None,
+ )
+ assert result.raised is None
+ payloads = [(request.path, assert_valid_request(request)) for request in result.requests]
+ scan_lists = [payload for path, payload in payloads if path == "/cis/scan/list"]
+ assert [payload.get("filterCriteria") for payload in scan_lists] == [
+ {"scanAtFilters": [{"earliestScanStartTime": 1735689600.0}]} if incremental else None
+ ] * 2
+ detail_calls = [
+ (payload["scanArn"], payload["accountId"], payload["targetResourceId"], payload.get("nextToken"))
+ for path, payload in payloads
+ if path == "/cis/scan-result/details/get"
+ ]
+ expected_calls = [
+ (SCAN_ONE, "111111111111", "i-0000000000000001", None),
+ (SCAN_ONE, "111111111111", "i-0000000000000001", "d-2"),
+ (SCAN_ONE, "111111111111", "i-0000000000000002", None),
+ (SCAN_TWO, "222222222222", "i-0000000000000001", None),
+ ]
+ # Incremental runs stop before an unfinished scan, so the watermark cannot pass it.
+ assert detail_calls == (
+ expected_calls if incremental else [*expected_calls, (SCAN_THREE, "222222222222", "i-0000000000000001", None)]
+ )
+ expected_rows = [
+ (SCAN_ONE, "i-0000000000000001", "1.1"),
+ (SCAN_ONE, "i-0000000000000001", "1.2"),
+ (SCAN_TWO, "i-0000000000000001", "1.1"),
+ ]
+ assert [(row["scan_arn"], row["target_resource_id"], row["check_id"]) for row in result.rows] == (
+ expected_rows if incremental else [*expected_rows, (SCAN_THREE, "i-0000000000000001", "1.1")]
+ )
+ first = result.rows[0]
+ assert first["account_id"] == "111111111111"
+ assert first["scan_date"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)
+ assert first["region"] == "eu-west-1"
+ assert result.final_state == AwsInspectorResumeConfig(
+ updated_after=1735689600.0 if incremental else None, completed=True
+ )
+
+
+def test_cis_scan_result_details_resume_from_saved_position(config: AwsInspectorSourceConfig) -> None:
+ script = details_script()
+ script["/cis/scan-result/resource/list"] = script["/cis/scan-result/resource/list"][1:]
+ script["/cis/scan-result/details/get"] = [
+ ScriptedResponse(json={"scanResultDetails": [{"scanArn": SCAN_ONE, "checkId": "1.3"}]}),
+ *script["/cis/scan-result/details/get"][3:],
+ ]
+ result = driver(config).run(
+ "cis_scan_result_details",
+ route(script),
+ resume_state=AwsInspectorResumeConfig(
+ scan_arn=SCAN_ONE, parent_token="targets-2", parent_key="111111111111/i-0000000000000002", next_token="d-3"
+ ),
+ )
+ assert result.raised is None
+ calls = [(request.path, request.json()) for request in result.requests]
+ assert calls[2] == ("/cis/scan-result/resource/list", {**calls[2][1], "nextToken": "targets-2"})
+ assert calls[3][1]["targetResourceId"] == "i-0000000000000002"
+ assert calls[3][1]["nextToken"] == "d-3"
+ assert [row["check_id"] for row in result.rows] == ["1.3", "1.1", "1.1"]
+ assert result.saved_states[0] == AwsInspectorResumeConfig(scan_arn=SCAN_TWO)
+
+
+def test_clusters_for_image_fan_out(config: AwsInspectorSourceConfig) -> None:
+ images = [{"resourceId": IMAGE_ONE, "resourceType": "AWS_ECR_CONTAINER_IMAGE"}]
+ result = driver(config).run(
+ "clusters_for_image",
+ route(
+ {
+ "/coverage/list": [
+ ScriptedResponse(json={"coveredResources": images, "nextToken": "images-2"}),
+ ScriptedResponse(json={"coveredResources": [{**images[0], "resourceId": IMAGE_TWO}]}),
+ ],
+ "/cluster/get": [
+ ScriptedResponse(
+ json={
+ "cluster": [{"clusterArn": "arn:aws:ecs:eu-west-1:111111111111:cluster/one"}],
+ "nextToken": "clusters-2",
+ }
+ ),
+ ScriptedResponse(
+ json={"cluster": [{"clusterArn": "arn:aws:ecs:eu-west-1:111111111111:cluster/two"}]}
+ ),
+ ScriptedResponse(json={"cluster": []}),
+ ],
+ }
+ ),
+ )
+ assert result.raised is None
+ payloads = [(request.path, assert_valid_request(request)) for request in result.requests]
+ assert [path for path, _ in payloads] == [
+ "/coverage/list",
+ "/cluster/get",
+ "/cluster/get",
+ "/coverage/list",
+ "/cluster/get",
+ ]
+ assert payloads[0][1]["filterCriteria"]["resourceType"] == [
+ {"comparison": "EQUALS", "value": "AWS_ECR_CONTAINER_IMAGE"}
+ ]
+ assert [payload["filter"]["resourceId"] for path, payload in payloads if path == "/cluster/get"] == [
+ IMAGE_ONE,
+ IMAGE_ONE,
+ IMAGE_TWO,
+ ]
+ assert [(row["resource_id"], row["cluster_arn"]) for row in result.rows] == [
+ (IMAGE_ONE, "arn:aws:ecs:eu-west-1:111111111111:cluster/one"),
+ (IMAGE_ONE, "arn:aws:ecs:eu-west-1:111111111111:cluster/two"),
+ ]
+ assert result.saved_states == [
+ AwsInspectorResumeConfig(parent_key=IMAGE_ONE, next_token="clusters-2"),
+ AwsInspectorResumeConfig(parent_token="images-2"),
+ AwsInspectorResumeConfig(completed=True),
+ ]