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 config evaluation, score, and aggregator tables (#116964)

Tom Owersc220be4f252f
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 6d980a3e40db..4eeb6e098a75 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
@@ -1132,15 +1132,15 @@ Note: Compared the official botocore operation model with the static endpoint ma
## AWS Config — **thin**
-Today (4): `config_rules`, `conformance_packs`, `resources`, `rule_compliance`
+Today (7): `aggregated_resources`, `config_rules`, `conformance_pack_compliance_scores`, `conformance_packs`, `resources`, `rule_compliance`, `rule_evaluation_results`
Diffed against: <https://raw.githubusercontent.com/boto/botocore/develop/botocore/data/config/2014-11-12/service-2.json>
- [ ] `Resource configuration history (GetResourceConfigHistory, POST /)` — provides configuration changes, deleted resource states, and historical relationships for auditing and incident analysis (high)
-- [ ] `Rule evaluation results (GetComplianceDetailsByConfigRule, POST /)` — connects synced rules to evaluated resources, compliance outcomes, timestamps, and reasons for failures (high)
+- [x] `Rule evaluation results (GetComplianceDetailsByConfigRule, POST /)` — connects synced rules to evaluated resources, compliance outcomes, timestamps, and reasons for failures (high)
- [ ] `Conformance pack evaluation results (GetConformancePackComplianceDetails, POST /)` — connects synced packs, rules, and resources to detailed compliance outcomes (high)
-- [ ] `Conformance pack compliance scores (ListConformancePackComplianceScores, POST /)` — provides the percentage of compliant rule-resource combinations for compliance dashboards (high)
-- [ ] `Aggregated resource configurations (SelectAggregateResourceConfig, POST /)` — enables resource inventory and configuration analysis across accounts and regions (high)
+- [x] `Conformance pack compliance scores (ListConformancePackComplianceScores, POST /)` — provides the percentage of compliant rule-resource combinations for compliance dashboards (high)
+- [x] `Aggregated resource configurations (SelectAggregateResourceConfig, POST /)` — enables resource inventory and configuration analysis across accounts and regions (high)
- [ ] `Remediation execution status (DescribeRemediationExecutionStatus, POST /)` — shows remediation progress, step timestamps, and errors for noncompliant resources (medium)
- [ ] `Proactive resource evaluations (ListResourceEvaluations, POST /)` — tracks compliance evaluations before resources are deployed (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/aws_config.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/aws_config.py
index 6c67ef578c0e..8ef55e5c112c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/aws_config.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/aws_config.py
@@ -31,7 +31,15 @@ if TYPE_CHECKING:
_REGION = re.compile(r"[a-z]{2}(?:-[a-z]+)+-\d+")
_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
_THROTTLE_CODES = {"Throttling", "ThrottlingException", "TooManyRequestsException", "RequestLimitExceeded"}
-_TIMESTAMP_COLUMNS = {"configuration_item_capture_time", "resource_creation_time", "last_update_requested_time"}
+_TIMESTAMP_COLUMNS = {
+ "configuration_item_capture_time",
+ "resource_creation_time",
+ "last_update_requested_time",
+ "last_updated_time",
+ "result_recorded_time",
+ "config_rule_invoked_time",
+ "ordering_timestamp",
+}
# Config reads use POST, so the transport must retry this method for transient HTTP failures.
TRANSPORT_RETRY = BoundedRetry(
@@ -47,6 +55,9 @@ TRANSPORT_RETRY = BoundedRetry(
class AwsConfigResumeConfig:
next_token: str | None = None
complete: bool = False
+ # Fan-out tables: the parent page to fetch again, and the parent that `next_token` continues.
+ parent_next_token: str | None = None
+ parent_key: str | None = None
class AwsConfigError(Exception):
@@ -129,7 +140,7 @@ class AwsConfigClient:
def request_payload(endpoint: AwsConfigEndpoint, *, probe: bool = False) -> dict[str, Any]:
- payload: dict[str, Any] = {}
+ payload: dict[str, Any] = dict(endpoint.params or {})
if endpoint.page_size is not None:
payload["Limit"] = 1 if probe else endpoint.page_size
if endpoint.expression is not None:
@@ -137,8 +148,16 @@ def request_payload(endpoint: AwsConfigEndpoint, *, probe: bool = False) -> dict
return payload
-def normalize_row(item: dict[str, Any], region: str) -> dict[str, Any]:
- row = {_CAMEL_BOUNDARY.sub("_", key).lower(): value for key, value in item.items()}
+def snake_case(key: str) -> str:
+ return _CAMEL_BOUNDARY.sub("_", key).lower()
+
+
+def normalize_row(item: dict[str, Any], region: str, flatten: tuple[str, ...] = ()) -> dict[str, Any]:
+ for key in flatten:
+ nested = item.get(key)
+ if isinstance(nested, dict):
+ item = {**nested, **{name: value for name, value in item.items() if name != key}}
+ row = {snake_case(key): value for key, value in item.items()}
row["region"] = region
for key in _TIMESTAMP_COLUMNS & row.keys():
value = row[key]
@@ -149,6 +168,135 @@ def normalize_row(item: dict[str, Any], region: str) -> dict[str, Any]:
return row
+def parse_page(
+ endpoint: AwsConfigEndpoint, body: dict[str, Any], region: str, previous_token: str | None
+) -> tuple[list[dict[str, Any]], str | None]:
+ rows = []
+ for item in body.get(endpoint.result_key) or []:
+ if endpoint.expression is not None:
+ item = json.loads(item)
+ if not isinstance(item, dict):
+ raise ValueError("AWS Config returned an invalid resource. Try the sync again.")
+ rows.append(normalize_row(item, region, endpoint.flatten))
+ token = body.get("NextToken") or None
+ if token is not None and (not isinstance(token, str) or token == previous_token):
+ raise ValueError("AWS Config returned an invalid page token. Try the sync again.")
+ return rows, token
+
+
+def request_page(
+ client: AwsConfigClient,
+ operation: str,
+ payload: dict[str, Any],
+ manager: "ResumableSourceManager[AwsConfigResumeConfig]",
+ resumed: bool,
+) -> dict[str, Any]:
+ try:
+ return client.request(operation, payload)
+ except AwsConfigError as error:
+ if resumed and error.code == "InvalidNextTokenException":
+ # A fresh retry must restart the full-refresh destination as well as extraction.
+ manager.clear_state()
+ raise
+
+
+def get_page_rows(
+ client: AwsConfigClient,
+ endpoint: AwsConfigEndpoint,
+ manager: "ResumableSourceManager[AwsConfigResumeConfig]",
+ resume: AwsConfigResumeConfig | None,
+) -> Generator[list[dict[str, Any]]]:
+ next_token = resume.next_token if resume else None
+ restarting = next_token is not None
+ while True:
+ payload = request_payload(endpoint)
+ if next_token:
+ payload["NextToken"] = next_token
+ body = request_page(client, endpoint.operation, payload, manager, restarting)
+ restarting = False
+ rows, next_token = parse_page(endpoint, body, client.region, next_token)
+ manager.save_state(AwsConfigResumeConfig(next_token=next_token, complete=next_token is None))
+ if rows:
+ yield rows
+ manager.safe_point()
+ if next_token is None:
+ break
+
+
+def get_fan_out_rows(
+ client: AwsConfigClient,
+ endpoint: AwsConfigEndpoint,
+ manager: "ResumableSourceManager[AwsConfigResumeConfig]",
+ resume: AwsConfigResumeConfig | None,
+) -> Generator[list[dict[str, Any]]]:
+ parent, param = endpoint.parent, endpoint.parent_param
+ if parent is None or param is None:
+ raise ValueError(f"AWS Config table {endpoint.operation} has no parent.")
+ column = snake_case(param)
+ parent_token = resume.parent_next_token if resume else None
+ resume_key = resume.parent_key if resume else None
+ child_token = resume.next_token if resume else None
+ restarting_parent = parent_token is not None
+ restarting_child = child_token is not None
+ while True:
+ payload = request_payload(parent)
+ if parent_token:
+ payload["NextToken"] = parent_token
+ body = request_page(client, parent.operation, payload, manager, restarting_parent)
+ restarting_parent = False
+ names = [item.get(param) if isinstance(item, dict) else None for item in body.get(parent.result_key) or []]
+ if not all(isinstance(name, str) and name for name in names):
+ raise ValueError("AWS Config returned an invalid parent resource. Try the sync again.")
+ next_parent_token = body.get("NextToken") or None
+ if next_parent_token is not None and (
+ not isinstance(next_parent_token, str) or next_parent_token == parent_token
+ ):
+ raise ValueError("AWS Config returned an invalid page token. Try the sync again.")
+ if resume_key is not None and resume_key not in names:
+ # Replaying the page would append committed rows twice, so the retry must restart the destination.
+ manager.clear_state()
+ raise ValueError("An AWS Config parent resource changed during the sync. Try the sync again.")
+ start = names.index(resume_key) if resume_key is not None else 0
+ resume_key = None
+ if not names:
+ manager.save_state(
+ AwsConfigResumeConfig(parent_next_token=next_parent_token)
+ if next_parent_token is not None
+ else AwsConfigResumeConfig(complete=True)
+ )
+ manager.safe_point()
+ for index in range(start, len(names)):
+ name = names[index]
+ if index + 1 < len(names):
+ done = AwsConfigResumeConfig(parent_next_token=parent_token, parent_key=names[index + 1])
+ elif next_parent_token is not None:
+ done = AwsConfigResumeConfig(parent_next_token=next_parent_token)
+ else:
+ done = AwsConfigResumeConfig(complete=True)
+ while True:
+ child_payload = {**request_payload(endpoint), param: name}
+ if child_token:
+ child_payload["NextToken"] = child_token
+ child_body = request_page(client, endpoint.operation, child_payload, manager, restarting_child)
+ restarting_child = False
+ rows, child_token = parse_page(endpoint, child_body, client.region, child_token)
+ for row in rows:
+ row[column] = name
+ manager.save_state(
+ AwsConfigResumeConfig(parent_next_token=parent_token, parent_key=name, next_token=child_token)
+ if child_token is not None
+ else done
+ )
+ if rows:
+ yield rows
+ manager.safe_point()
+ if child_token is None:
+ break
+ if next_parent_token is None:
+ break
+ parent_token = next_parent_token
+
+
def get_rows(
config: "AwsConfigSourceConfig",
endpoint: AwsConfigEndpoint,
@@ -159,39 +307,12 @@ def get_rows(
if resume is not None and resume.complete:
manager.clear_state()
return
- next_token = resume.next_token if resume else None
- restarting = next_token is not None
client = AwsConfigClient(config, api_version)
try:
- while True:
- payload = request_payload(endpoint)
- if next_token:
- payload["NextToken"] = next_token
- try:
- body = client.request(endpoint.operation, payload)
- except AwsConfigError as error:
- if restarting and error.code == "InvalidNextTokenException":
- # A fresh retry must restart the full-refresh destination as well as extraction.
- manager.clear_state()
- raise
- restarting = False
- rows = []
- for item in body.get(endpoint.result_key) or []:
- if endpoint.expression is not None:
- item = json.loads(item)
- if not isinstance(item, dict):
- raise ValueError("AWS Config returned an invalid resource. Try the sync again.")
- rows.append(normalize_row(item, client.region))
- token = body.get("NextToken") or None
- if token is not None and (not isinstance(token, str) or token == next_token):
- raise ValueError("AWS Config returned an invalid page token. Try the sync again.")
- next_token = token
- manager.save_state(AwsConfigResumeConfig(next_token=next_token, complete=next_token is None))
- if rows:
- yield rows
- manager.safe_point()
- if next_token is None:
- break
+ if endpoint.parent is None:
+ yield from get_page_rows(client, endpoint, manager, resume)
+ else:
+ yield from get_fan_out_rows(client, endpoint, manager, resume)
manager.clear_state()
finally:
client.close()
@@ -207,13 +328,21 @@ def validate_credentials(
client = AwsConfigClient(config, api_version)
except ValueError as error:
return False, str(error)
+ probe = endpoint.parent or endpoint
+ operation = probe.operation
try:
- client.request(endpoint.operation, request_payload(endpoint, probe=True))
+ body = client.request(operation, request_payload(probe, probe=True))
+ if endpoint.parent is not None and endpoint.parent_param is not None:
+ parents = body.get(endpoint.parent.result_key) or []
+ name = parents[0].get(endpoint.parent_param) if parents and isinstance(parents[0], dict) else None
+ if name:
+ operation = endpoint.operation
+ client.request(operation, {**request_payload(endpoint, probe=True), endpoint.parent_param: name})
except AwsConfigError as error:
if error.code in {"AccessDenied", "AccessDeniedException"}:
if schema_name is None:
return True, None
- return False, f"Grant config:{endpoint.operation} to this IAM user or role to sync this table."
+ return False, f"Grant config:{operation} to this IAM user or role to sync this table."
return False, ERROR_MESSAGES.get(error.code, "Could not read AWS Config. Check the region and try again.")
except (requests.RequestException, ValueError):
return False, "Could not reach the AWS Config API. Check the region and try again."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/canonical_descriptions.py
index 9baf60bd2c0f..6b7f9846bd4a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/canonical_descriptions.py
@@ -60,4 +60,50 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"region": "AWS region selected for this import.",
},
},
+ "conformance_pack_compliance_scores": {
+ "description": "Compliance score for each conformance pack: the percentage of compliant rule and resource combinations.",
+ "docs_url": "https://docs.aws.amazon.com/config/latest/APIReference/API_ListConformancePackComplianceScores.html",
+ "columns": {
+ "conformance_pack_name": "Name of the conformance pack.",
+ "score": "Percentage of compliant rule and resource combinations, or INSUFFICIENT_DATA when no evaluation results exist.",
+ "last_updated_time": "Time when AWS Config last updated the compliance score.",
+ "region": "AWS region selected for this import.",
+ },
+ },
+ "rule_evaluation_results": {
+ "description": "Latest evaluation result for each resource that an AWS Config rule evaluated.",
+ "docs_url": "https://docs.aws.amazon.com/config/latest/APIReference/API_GetComplianceDetailsByConfigRule.html",
+ "columns": {
+ "config_rule_name": "Name of the AWS Config rule that evaluated the resource.",
+ "resource_type": "AWS resource type of the evaluated resource.",
+ "resource_id": "Identifier of the evaluated resource.",
+ "evaluation_mode": "Evaluation mode, DETECTIVE or PROACTIVE.",
+ "ordering_timestamp": "Time of the event that triggered the evaluation.",
+ "resource_evaluation_id": "Unique identifier of the evaluation result.",
+ "compliance_type": "Evaluation outcome, such as COMPLIANT or NON_COMPLIANT.",
+ "result_recorded_time": "Time when AWS Config recorded the evaluation result.",
+ "config_rule_invoked_time": "Time when the rule ran the evaluation.",
+ "annotation": "Additional information from the rule, such as the reason for noncompliance.",
+ "result_token": "Token that identifies the evaluation result.",
+ "region": "AWS region selected for this import.",
+ },
+ },
+ "aggregated_resources": {
+ "description": "Current configurations of resources across the source accounts and regions of each configuration aggregator.",
+ "docs_url": "https://docs.aws.amazon.com/config/latest/APIReference/API_SelectAggregateResourceConfig.html",
+ "columns": {
+ "configuration_aggregator_name": "Name of the configuration aggregator that returned the resource.",
+ "account_id": "AWS account that owns the resource.",
+ "aws_region": "AWS region where the resource exists.",
+ "region": "AWS region of the aggregator selected for this import.",
+ "arn": "Amazon Resource Name of the resource.",
+ "resource_id": "Resource identifier assigned by its AWS service.",
+ "resource_type": "AWS resource type, such as AWS::EC2::Instance.",
+ "resource_name": "Resource name, when the service provides one.",
+ "configuration": "Configuration properties recorded for the resource.",
+ "configuration_item_capture_time": "Time when AWS Config recorded this configuration.",
+ "resource_creation_time": "Time when the resource was created, when available.",
+ "tags": "Tags attached to the resource.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/settings.py
index b5dbe3fd601f..d850ad85aa69 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/settings.py
@@ -1,3 +1,6 @@
+from collections.abc import Mapping
+from typing import Any
+
from posthog.dataclasses import frozen
CONFIG_API_VERSION = "2014-11-12"
@@ -17,6 +20,27 @@ class AwsConfigEndpoint:
description: str
page_size: int | None = None
expression: str | None = None
+ params: Mapping[str, Any] | None = None
+ flatten: tuple[str, ...] = ()
+ # Child endpoints run once per parent row, passing the parent's `parent_param` value through.
+ parent: "AwsConfigEndpoint | None" = None
+ parent_param: str | None = None
+
+
+CONFIG_RULES = AwsConfigEndpoint(
+ operation="DescribeConfigRules",
+ result_key="ConfigRules",
+ primary_key=("config_rule_arn",),
+ description="AWS Config rules, their evaluation settings, and resource scopes.",
+)
+
+CONFIGURATION_AGGREGATORS = AwsConfigEndpoint(
+ operation="DescribeConfigurationAggregators",
+ result_key="ConfigurationAggregators",
+ primary_key=("configuration_aggregator_arn",),
+ description="Configuration aggregators in the selected region.",
+ page_size=100,
+)
AWS_CONFIG_ENDPOINTS: dict[str, AwsConfigEndpoint] = {
@@ -28,12 +52,7 @@ AWS_CONFIG_ENDPOINTS: dict[str, AwsConfigEndpoint] = {
page_size=100,
expression=RESOURCE_EXPRESSION,
),
- "config_rules": AwsConfigEndpoint(
- operation="DescribeConfigRules",
- result_key="ConfigRules",
- primary_key=("config_rule_arn",),
- description="AWS Config rules, their evaluation settings, and resource scopes.",
- ),
+ "config_rules": CONFIG_RULES,
"rule_compliance": AwsConfigEndpoint(
operation="DescribeComplianceByConfigRule",
result_key="ComplianceByConfigRules",
@@ -47,6 +66,35 @@ AWS_CONFIG_ENDPOINTS: dict[str, AwsConfigEndpoint] = {
description="Conformance packs and their deployment settings in the selected region.",
page_size=20,
),
+ "conformance_pack_compliance_scores": AwsConfigEndpoint(
+ operation="ListConformancePackComplianceScores",
+ result_key="ConformancePackComplianceScores",
+ primary_key=("region", "conformance_pack_name"),
+ description="Percentage of compliant rule and resource combinations in each conformance pack.",
+ page_size=20,
+ ),
+ "rule_evaluation_results": AwsConfigEndpoint(
+ operation="GetComplianceDetailsByConfigRule",
+ result_key="EvaluationResults",
+ primary_key=("region", "config_rule_name", "resource_type", "resource_id"),
+ description="Latest evaluation result for each resource that each AWS Config rule evaluated.",
+ page_size=100,
+ # INSUFFICIENT_DATA is not a valid filter value, so the three filterable outcomes are listed explicitly.
+ params={"ComplianceTypes": ["COMPLIANT", "NON_COMPLIANT", "NOT_APPLICABLE"]},
+ flatten=("EvaluationResultIdentifier", "EvaluationResultQualifier"),
+ parent=CONFIG_RULES,
+ parent_param="ConfigRuleName",
+ ),
+ "aggregated_resources": AwsConfigEndpoint(
+ operation="SelectAggregateResourceConfig",
+ result_key="Results",
+ primary_key=("configuration_aggregator_name", "account_id", "aws_region", "resource_type", "resource_id"),
+ description="Current configurations of resources across the accounts and regions of each configuration aggregator in the selected region.",
+ page_size=100,
+ expression=RESOURCE_EXPRESSION,
+ parent=CONFIGURATION_AGGREGATORS,
+ parent_param="ConfigurationAggregatorName",
+ ),
}
ENDPOINTS = tuple(AWS_CONFIG_ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/source.py
index b7ada904f248..c09be0cec3a0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/source.py
@@ -94,15 +94,19 @@ class AwsConfigSource(ResumableSource[AwsConfigSourceConfig, AwsConfigResumeConf
name=ExternalDataSourceType.AWSCONFIG,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="AWS Config",
- caption="""Sync resource configurations, rules, compliance status, and conformance packs from one AWS region.
+ caption="""Sync resource configurations, rules, compliance status and evaluation results, conformance packs, and aggregated resources from one AWS region.
Grant these IAM permissions for the tables you want to sync:
- `config:SelectResourceConfig`
- `config:DescribeConfigRules`
- `config:DescribeComplianceByConfigRule`
+- `config:GetComplianceDetailsByConfigRule`
- `config:DescribeConformancePacks`
+- `config:ListConformancePackComplianceScores`
+- `config:DescribeConfigurationAggregators` and `config:SelectAggregateResourceConfig`
Enable an AWS Config recorder for resource inventory. The resources table contains current configurations and excludes deleted resources.
+The aggregated resources table reads every configuration aggregator in the selected region.
Add a session token if you use temporary credentials. Replace temporary credentials when they expire.""",
iconPath="/static/services/aws_config.png",
docsUrl="https://docs.aws.amazon.com/config/latest/APIReference/Welcome.html",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/tests/test_aws_config.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/tests/test_aws_config.py
index 951c9c215778..2663606fec57 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/tests/test_aws_config.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_config/tests/test_aws_config.py
@@ -145,6 +145,14 @@ def test_signed_tracked_request(region: str | None, token: str | None, host: str
"conformance_pack_arn",
20,
),
+ (
+ "conformance_pack_compliance_scores",
+ "ConformancePackComplianceScores",
+ "ListConformancePackComplianceScores",
+ {"ConformancePackName": "example-pack", "Score": "87.5", "LastUpdatedTime": 1735689600},
+ "conformance_pack_name",
+ 20,
+ ),
],
)
def test_full_refresh_paginates_through_empty_and_terminal_pages(
@@ -168,6 +176,8 @@ def test_full_refresh_paginates_through_empty_and_terminal_pages(
assert batches[0][0]["configuration_item_capture_time"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)
if endpoint == "conformance_packs":
assert batches[0][0]["last_update_requested_time"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)
+ if endpoint == "conformance_pack_compliance_scores":
+ assert batches[0][0]["last_updated_time"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)
if endpoint == "rule_compliance":
assert batches[0][0]["compliance"] == {"ComplianceType": "NON_COMPLIANT"}
for call, token in zip(session.post.call_args_list, [None, "second", "third"], strict=True):
@@ -194,6 +204,130 @@ def test_full_refresh_paginates_through_empty_and_terminal_pages(
session.close.assert_called_once()
+FAN_OUT_CASES = [
+ (
+ "rule_evaluation_results",
+ ("DescribeConfigRules", "ConfigRules", "ConfigRuleName", None),
+ ("GetComplianceDetailsByConfigRule", "EvaluationResults"),
+ {"ComplianceTypes": ["COMPLIANT", "NON_COMPLIANT", "NOT_APPLICABLE"], "Limit": 100},
+ lambda parent, index: {
+ "EvaluationResultIdentifier": {
+ "EvaluationResultQualifier": {
+ "ConfigRuleName": parent,
+ "ResourceType": "AWS::S3::Bucket",
+ "ResourceId": f"bucket-{index}",
+ "EvaluationMode": "DETECTIVE",
+ },
+ "OrderingTimestamp": 1735689600,
+ },
+ "ComplianceType": "NON_COMPLIANT",
+ "ResultRecordedTime": 1735689600,
+ },
+ ),
+ (
+ "aggregated_resources",
+ ("DescribeConfigurationAggregators", "ConfigurationAggregators", "ConfigurationAggregatorName", 100),
+ ("SelectAggregateResourceConfig", "Results"),
+ {
+ "Limit": 100,
+ "Expression": (
+ "SELECT accountId, awsRegion, arn, resourceId, resourceType, resourceName, "
+ "configuration, configurationItemCaptureTime, resourceCreationTime, tags"
+ ),
+ },
+ lambda parent, index: json.dumps(
+ {
+ "accountId": "111111111111",
+ "awsRegion": "us-west-2",
+ "resourceType": "AWS::S3::Bucket",
+ "resourceId": f"bucket-{index}",
+ "configurationItemCaptureTime": "2025-01-01T00:00:00Z",
+ }
+ ),
+ ),
+]
+
+
[email protected]("endpoint,parent,child,child_params,make_item", FAN_OUT_CASES)
+def test_fan_out_walks_every_parent_and_child_page(
+ session: MagicMock, endpoint: str, parent: tuple, child: tuple, child_params: dict, make_item: Any
+) -> None:
+ parent_operation, parent_key, param, parent_limit = parent
+ child_operation, child_key = child
+ session.post.side_effect = [
+ make_response({parent_key: [{param: "a"}, {param: "b"}], "NextToken": "parent-2"}),
+ make_response({child_key: [make_item("a", 1)], "NextToken": "child-2"}),
+ make_response({child_key: [make_item("a", 2)]}),
+ make_response({child_key: []}),
+ make_response({parent_key: [{param: "c"}]}),
+ make_response({child_key: [make_item("c", 3)]}),
+ ]
+ manager = make_manager()
+ response = aws_config_source(make_config(), endpoint, "2014-11-12", manager)
+ batches = list(cast(Iterable[Any], response.items()))
+
+ rows = [row for batch in batches for row in batch]
+ assert [(row[aws_config.snake_case(param)], row["resource_id"]) for row in rows] == [
+ ("a", "bucket-1"),
+ ("a", "bucket-2"),
+ ("c", "bucket-3"),
+ ]
+ assert all(row.get(key) is not None for row in rows for key in response.primary_keys or [])
+ if endpoint == "rule_evaluation_results":
+ assert rows[0]["ordering_timestamp"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)
+ assert "evaluation_result_identifier" not in rows[0]
+ parent_params = {} if parent_limit is None else {"Limit": parent_limit}
+ expected_requests = [
+ (parent_operation, parent_params),
+ (child_operation, {**child_params, param: "a"}),
+ (child_operation, {**child_params, param: "a", "NextToken": "child-2"}),
+ (child_operation, {**child_params, param: "b"}),
+ (parent_operation, {**parent_params, "NextToken": "parent-2"}),
+ (child_operation, {**child_params, param: "c"}),
+ ]
+ assert [
+ (call.kwargs["headers"]["X-Amz-Target"].split(".")[1], json.loads(call.kwargs["data"]))
+ for call in session.post.call_args_list
+ ] == expected_requests
+ assert [call.args[0] for call in manager.save_state.call_args_list] == [
+ AwsConfigResumeConfig(parent_key="a", next_token="child-2"),
+ AwsConfigResumeConfig(parent_key="b"),
+ AwsConfigResumeConfig(parent_next_token="parent-2"),
+ AwsConfigResumeConfig(complete=True),
+ ]
+ assert manager.safe_point.call_count == 4
+ manager.clear_state.assert_called_once()
+
+
+def test_fan_out_resumes_at_saved_parent(session: MagicMock) -> None:
+ session.post.side_effect = [
+ make_response({"ConfigRules": [{"ConfigRuleName": "a"}, {"ConfigRuleName": "b"}]}),
+ make_response({"EvaluationResults": []}),
+ ]
+ manager = make_manager(AwsConfigResumeConfig(parent_next_token="parent-2", parent_key="b", next_token="child-2"))
+ list(
+ cast(Iterable[Any], aws_config_source(make_config(), "rule_evaluation_results", "2014-11-12", manager).items())
+ )
+
+ payloads = [json.loads(call.kwargs["data"]) for call in session.post.call_args_list]
+ assert payloads[0] == {"NextToken": "parent-2"}
+ assert [(payload["ConfigRuleName"], payload.get("NextToken")) for payload in payloads[1:]] == [("b", "child-2")]
+ manager.clear_state.assert_called_once()
+
+
+def test_fan_out_missing_saved_parent_clears_state_and_fails_attempt(session: MagicMock) -> None:
+ session.post.return_value = make_response({"ConfigRules": [{"ConfigRuleName": "a"}]})
+ manager = make_manager(AwsConfigResumeConfig(parent_key="deleted", next_token="child-2"))
+ response = aws_config_source(make_config(), "rule_evaluation_results", "2014-11-12", manager)
+
+ with pytest.raises(ValueError, match="changed during the sync"):
+ list(cast(Iterable[Any], response.items()))
+
+ session.post.assert_called_once()
+ manager.clear_state.assert_called_once()
+ manager.save_state.assert_not_called()
+
+
def test_expired_resume_token_clears_state_and_fails_attempt(session: MagicMock) -> None:
session.post.return_value = make_response({"__type": "InvalidNextTokenException"}, 400)
manager = make_manager(AwsConfigResumeConfig(next_token="expired-token"))
@@ -320,20 +454,46 @@ def test_credential_errors_are_actionable(code: str, message: str) -> None:
@pytest.mark.parametrize(
- "schema,operation,limit",
+ "schema,responses,expected",
[
- (None, "DescribeConfigRules", None),
- ("resources", "SelectResourceConfig", 1),
- ("conformance_packs", "DescribeConformancePacks", 1),
+ (None, [{}], [("DescribeConfigRules", None)]),
+ ("resources", [{}], [("SelectResourceConfig", 1)]),
+ ("conformance_packs", [{}], [("DescribeConformancePacks", 1)]),
+ ("rule_evaluation_results", [{}], [("DescribeConfigRules", None)]),
+ (
+ "rule_evaluation_results",
+ [{"ConfigRules": [{"ConfigRuleName": "example-rule"}]}, {}],
+ [("DescribeConfigRules", None), ("GetComplianceDetailsByConfigRule", 1)],
+ ),
+ (
+ "aggregated_resources",
+ [{"ConfigurationAggregators": [{"ConfigurationAggregatorName": "example-aggregator"}]}, {}],
+ [("DescribeConfigurationAggregators", 1), ("SelectAggregateResourceConfig", 1)],
+ ),
],
)
-def test_credential_probe_is_one_request(schema: str | None, operation: str, limit: int | None) -> None:
- with scripted_network([ScriptedResponse(json={})]) as network:
+def test_credential_probe_reads_parent_then_one_child(
+ schema: str | None, responses: list[dict[str, Any]], expected: list[tuple[str, int | None]]
+) -> None:
+ with scripted_network([ScriptedResponse(json=body) for body in responses]) as network:
assert validate_credentials(make_config(), "2014-11-12", schema) == (True, None)
- assert len(network.requests_log) == 1
- request = network.requests_log[0]
- assert request.headers["x-amz-target"] == f"StarlingDoveService.{operation}"
- assert request.json().get("Limit") == limit
+ assert [
+ (request.headers["x-amz-target"].split(".")[1], request.json().get("Limit")) for request in network.requests_log
+ ] == expected
+ if len(expected) == 2:
+ assert set(network.requests_log[1].json()) & {"ConfigRuleName", "ConfigurationAggregatorName"}
+
+
+def test_fan_out_access_denied_names_child_permission() -> None:
+ with scripted_network(
+ [
+ ScriptedResponse(json={"ConfigRules": [{"ConfigRuleName": "example-rule"}]}),
+ ScriptedResponse(status=400, json={"__type": "AccessDeniedException", "message": "Denied"}),
+ ]
+ ):
+ valid, reason = validate_credentials(make_config(), "2014-11-12", "rule_evaluation_results")
+ assert not valid
+ assert "config:GetComplianceDetailsByConfigRule" in (reason or "")
@pytest.mark.parametrize("region", ["https://example.com", "us-east-1.example.com/path", "us-east-1\n", "../us-east-1"])