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(warehouse-sources): add aws iam access analyzer endpoint tables (#117699)

Tom Owersb852b1bd35b2
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 9764f95e5fdb..1aef1e84f96f 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
@@ -1217,9 +1217,9 @@ Today (3): `analyzers`, `archive_rules`, `findings`
Diffed against: <https://raw.githubusercontent.com/boto/botocore/develop/botocore/data/accessanalyzer/2019-11-01/service-2.json>
-- [ ] `Analyzed resources (ListAnalyzedResources, POST /analyzed-resource)` — resolves resource ARNs in findings and identifies analyzed resources without findings (high)
-- [ ] `Finding access details (GetFindingV2, GET /findingv2/{id})` — provides principals, actions, and unused permission records that finding summaries omit (high)
-- [ ] `Finding recommendations (GetFindingRecommendation, GET /recommendation/{id})` — provides remediation steps for unused permissions so findings can be assessed against recommended actions (medium)
+- [x] `Analyzed resources (ListAnalyzedResources, POST /analyzed-resource)` — resolves resource ARNs in findings and identifies analyzed resources without findings (high)
+- [x] `Finding access details (GetFindingV2, GET /findingv2/{id})` — provides principals, actions, and unused permission records that finding summaries omit (high)
+- [x] `Finding recommendations (GetFindingRecommendation, GET /recommendation/{id})` — provides remediation steps for unused permissions so findings can be assessed against recommended actions (medium)
Note: Compared the official botocore operation model with the static endpoint map and extraction code. Findings currently use ListFindingsV2 summaries; GetFindingV2 supplies separate, paginated access details. Analyzed resources need analyzer traversal; GetAnalyzedResource hydration applies only to external analyzers. Recommendation reads need existing generated results; policy generation and preview plumbing were excluded.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/aws_iam_access_analyzer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/aws_iam_access_analyzer.py
index 1c668a2a1690..1722ef04ddc1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/aws_iam_access_analyzer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/aws_iam_access_analyzer.py
@@ -19,7 +19,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.aws_iam_ac
ENDPOINTS,
ERROR_MESSAGES,
PAGE_SIZE,
- PARTITION_KEY,
TIMESTAMP_COLUMNS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
@@ -38,6 +37,7 @@ class AwsIamAccessAnalyzerResumeConfig:
next_token: str | None = None
analyzers_next_token: str | None = None
pending_analyzers: list[dict[str, str]] = field(default_factory=list)
+ pending_findings: list[str] = field(default_factory=list)
finished: bool = False
@@ -86,6 +86,7 @@ class AwsIamAccessAnalyzerClient:
endpoint: str,
*,
analyzer: dict[str, str] | None = None,
+ finding_id: str | None = None,
next_token: str | None = None,
page_size: int = PAGE_SIZE,
) -> dict[str, Any]:
@@ -97,10 +98,14 @@ class AwsIamAccessAnalyzerClient:
if endpoint != "analyzers":
if analyzer is None:
raise ValueError(f"An analyzer is required for {endpoint}.")
- if endpoint == "findings":
- payload["analyzerArn"] = analyzer["arn"]
- else:
+ if "{analyzer_name}" in path:
path = path.format(analyzer_name=quote(analyzer["name"], safe=""))
+ else:
+ payload["analyzerArn"] = analyzer["arn"]
+ if "{id}" in path:
+ if finding_id is None:
+ raise ValueError(f"A finding ID is required for {endpoint}.")
+ path = path.format(id=quote(finding_id, safe=""))
url = self.url + path
body = None
if definition.method == "GET":
@@ -143,6 +148,63 @@ def normalize_row(row: dict[str, Any], region: str, analyzer: dict[str, str] | N
return result
+def select_analyzers(endpoint: str, rows: list[dict[str, Any]]) -> list[dict[str, str]]:
+ types = ENDPOINTS[endpoint].analyzer_types
+ return [{"arn": row["arn"], "name": row["name"]} for row in rows if types is None or row.get("type") in types]
+
+
+def select_finding_ids(endpoint: str, rows: list[dict[str, Any]]) -> list[str]:
+ types = ENDPOINTS[endpoint].finding_types
+ return [row["id"] for row in rows if types is None or row.get("findingType") in types]
+
+
+def advance(
+ state: AwsIamAccessAnalyzerResumeConfig, next_token: str | None, pending_findings: list[str]
+) -> AwsIamAccessAnalyzerResumeConfig:
+ analyzer_done = next_token is None and not pending_findings
+ pending = state.pending_analyzers[1:] if analyzer_done else state.pending_analyzers
+ return AwsIamAccessAnalyzerResumeConfig(
+ next_token=next_token,
+ pending_analyzers=pending,
+ pending_findings=pending_findings,
+ analyzers_next_token=state.analyzers_next_token,
+ finished=not pending and state.analyzers_next_token is None,
+ )
+
+
+def get_finding_row(
+ client: AwsIamAccessAnalyzerClient,
+ endpoint: str,
+ analyzer: dict[str, str],
+ finding_id: str,
+ manager: ResumableSourceManager[AwsIamAccessAnalyzerResumeConfig],
+) -> dict[str, Any] | None:
+ result_key = ENDPOINTS[endpoint].result_key
+ row: dict[str, Any] = {}
+ items: list[Any] = []
+ next_token = None
+ while True:
+ try:
+ page = client.request(endpoint, analyzer=analyzer, finding_id=finding_id, next_token=next_token)
+ except AwsIamAccessAnalyzerError as error:
+ # The finding was deleted, or no recommendation was generated for it.
+ if error.code == "ResourceNotFoundException":
+ return None
+ raise
+ if not row:
+ row = {key: value for key, value in page.items() if key != "nextToken"}
+ items.extend(page.get(result_key) or [])
+ next_token = page.get("nextToken") or None
+ if next_token is None:
+ break
+ manager.safe_point()
+ row[result_key] = items
+ result = normalize_row(row, client.region, analyzer)
+ if endpoint == "finding_recommendations":
+ result["finding_id"] = finding_id
+ return result
+
+
def get_rows(
config: AwsIamAccessAnalyzerSourceConfig,
endpoint: str,
@@ -160,7 +222,7 @@ def get_rows(
if endpoint != "analyzers":
if not state.pending_analyzers:
parent_page = client.request("analyzers", next_token=state.analyzers_next_token)
- parents = [{"arn": row["arn"], "name": row["name"]} for row in parent_page["analyzers"]]
+ parents = select_analyzers(endpoint, parent_page["analyzers"])
parent_token = parent_page.get("nextToken") or None
state = AwsIamAccessAnalyzerResumeConfig(
pending_analyzers=parents,
@@ -172,6 +234,25 @@ def get_rows(
manager.safe_point()
continue
analyzer = state.pending_analyzers[0]
+ if analyzer is not None and ENDPOINTS[endpoint].per_finding:
+ if state.pending_findings:
+ row = get_finding_row(client, endpoint, analyzer, state.pending_findings[0], manager)
+ state = advance(state, state.next_token, state.pending_findings[1:])
+ manager.save_state(state)
+ if row is not None:
+ yield [row]
+ else:
+ try:
+ page = client.request("findings", analyzer=analyzer, next_token=state.next_token)
+ except AwsIamAccessAnalyzerError as error:
+ if error.code != "ResourceNotFoundException":
+ raise
+ page = {"findings": []}
+ finding_ids = select_finding_ids(endpoint, page["findings"])
+ state = advance(state, page.get("nextToken") or None, finding_ids)
+ manager.save_state(state)
+ manager.safe_point()
+ continue
try:
page = client.request(endpoint, analyzer=analyzer, next_token=state.next_token)
except AwsIamAccessAnalyzerError as error:
@@ -183,13 +264,7 @@ def get_rows(
if endpoint == "analyzers":
state = AwsIamAccessAnalyzerResumeConfig(next_token=next_token, finished=next_token is None)
else:
- pending = state.pending_analyzers if next_token else state.pending_analyzers[1:]
- state = AwsIamAccessAnalyzerResumeConfig(
- next_token=next_token,
- pending_analyzers=pending,
- analyzers_next_token=state.analyzers_next_token,
- finished=not pending and state.analyzers_next_token is None,
- )
+ state = advance(state, next_token, [])
manager.save_state(state)
if rows:
yield rows
@@ -210,10 +285,26 @@ def validate_credentials(
try:
page = client.request("analyzers", page_size=1)
if schema_name is not None and schema_name != "analyzers":
- while not page["analyzers"] and page.get("nextToken"):
+ analyzers = select_analyzers(schema_name, page["analyzers"])
+ while not analyzers and page.get("nextToken"):
page = client.request("analyzers", page_size=1, next_token=page["nextToken"])
- if page["analyzers"]:
- client.request(schema_name, analyzer=page["analyzers"][0], page_size=1)
+ analyzers = select_analyzers(schema_name, page["analyzers"])
+ if analyzers and ENDPOINTS[schema_name].per_finding:
+ findings_page = client.request("findings", analyzer=analyzers[0])
+ finding_ids = select_finding_ids(schema_name, findings_page["findings"])
+ while not finding_ids and findings_page.get("nextToken"):
+ findings_page = client.request(
+ "findings", analyzer=analyzers[0], next_token=findings_page["nextToken"]
+ )
+ finding_ids = select_finding_ids(schema_name, findings_page["findings"])
+ if finding_ids:
+ try:
+ client.request(schema_name, analyzer=analyzers[0], finding_id=finding_ids[0], page_size=1)
+ except AwsIamAccessAnalyzerError as error:
+ if error.code != "ResourceNotFoundException":
+ raise
+ elif analyzers:
+ client.request(schema_name, analyzer=analyzers[0], page_size=1)
return True, None
finally:
client.close()
@@ -235,13 +326,14 @@ def aws_iam_access_analyzer_source(
) -> SourceResponse:
if endpoint not in ENDPOINTS:
raise ValueError(f"Unknown AWS IAM Access Analyzer table: {endpoint}")
+ partition_key = ENDPOINTS[endpoint].partition_key
return SourceResponse(
name=endpoint,
items=lambda: get_rows(config, endpoint, manager, api_version),
primary_keys=list(ENDPOINTS[endpoint].primary_keys),
- partition_keys=[PARTITION_KEY],
- partition_mode="datetime",
- partition_format="month",
+ partition_keys=[partition_key] if partition_key else None,
+ partition_mode="datetime" if partition_key else None,
+ partition_format="month" if partition_key else None,
sort_mode=None,
on_complete=manager.clear_state,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/canonical_descriptions.py
index ff5b319868f8..6920c20248e5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/canonical_descriptions.py
@@ -50,4 +50,50 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"region": "The AWS region queried by this source.",
},
},
+ "analyzed_resources": {
+ "description": "Resources that each external access analyzer analyzed, with or without findings.",
+ "docs_url": "https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_AnalyzedResourceSummary.html",
+ "columns": {
+ "resource_arn": "The ARN of the analyzed resource.",
+ "analyzer_arn": "The ARN of the analyzer that analyzed the resource.",
+ "resource_owner_account": "The AWS account ID that owns the resource.",
+ "resource_type": "The type of resource that was analyzed.",
+ "region": "The AWS region queried by this source.",
+ },
+ },
+ "finding_details": {
+ "description": "Full findings with the access details that finding summaries omit.",
+ "docs_url": "https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_GetFindingV2.html",
+ "columns": {
+ "id": "The finding ID within the analyzer.",
+ "analyzer_arn": "The ARN of the analyzer that returned this finding.",
+ "finding_type": "The type of access that the finding identifies.",
+ "finding_details": "The external access, internal access, or unused access details of the finding, such as principals, actions, conditions, and unused permissions.",
+ "resource": "The resource that the finding applies to.",
+ "resource_type": "The AWS resource type.",
+ "resource_owner_account": "The AWS account that owns the resource.",
+ "status": "The finding status: ACTIVE, ARCHIVED, or RESOLVED.",
+ "created_at": "The time when AWS created the finding.",
+ "updated_at": "The time when AWS last updated the finding.",
+ "analyzed_at": "The time of the analysis that generated the finding.",
+ "error": "An error that prevented the analysis.",
+ "region": "The AWS region queried by this source.",
+ },
+ },
+ "finding_recommendations": {
+ "description": "Generated remediation recommendations for unused permission findings.",
+ "docs_url": "https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_GetFindingRecommendation.html",
+ "columns": {
+ "finding_id": "The ID of the finding that the recommendation is for.",
+ "analyzer_arn": "The ARN of the unused access analyzer that owns the finding.",
+ "resource_arn": "The ARN of the resource in the finding.",
+ "recommendation_type": "The type of recommendation.",
+ "recommended_steps": "The steps to remediate the unused permissions, such as a policy to create or detach.",
+ "status": "The status of the recommendation: SUCCEEDED, FAILED, or IN_PROGRESS.",
+ "error": "The reason that AWS could not generate the recommendation.",
+ "started_at": "The time when AWS started to generate the recommendation.",
+ "completed_at": "The time when AWS finished generating the recommendation.",
+ "region": "The AWS region queried by this source.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/settings.py
index 505213005b24..1de6a50b7629 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/settings.py
@@ -7,7 +7,16 @@ DEFAULT_REGION = "us-east-1"
PAGE_SIZE = 100
API_DOCS_URL = "https://docs.aws.amazon.com/access-analyzer/latest/APIReference/"
PARTITION_KEY = "created_at"
-TIMESTAMP_COLUMNS = {"created_at", "updated_at", "analyzed_at", "last_resource_analyzed_at"}
+TIMESTAMP_COLUMNS = {
+ "created_at",
+ "updated_at",
+ "analyzed_at",
+ "last_resource_analyzed_at",
+ "started_at",
+ "completed_at",
+}
+EXTERNAL_ACCESS_ANALYZER_TYPES = frozenset({"ACCOUNT", "ORGANIZATION"})
+UNUSED_ACCESS_ANALYZER_TYPES = frozenset({"ACCOUNT_UNUSED_ACCESS", "ORGANIZATION_UNUSED_ACCESS"})
@frozen
@@ -17,6 +26,12 @@ class Endpoint:
result_key: str
primary_keys: tuple[str, ...]
description: str
+ partition_key: str | None = PARTITION_KEY
+ # Analyzer types that support the endpoint. None means every type.
+ analyzer_types: frozenset[str] | None = None
+ # Detail endpoints make one request per finding from ListFindingsV2.
+ per_finding: bool = False
+ finding_types: frozenset[str] | None = None
ENDPOINTS: dict[str, Endpoint] = {
@@ -41,11 +56,46 @@ ENDPOINTS: dict[str, Endpoint] = {
primary_keys=("analyzer_arn", "rule_name"),
description="Rules that automatically archive findings for each analyzer.",
),
+ "analyzed_resources": Endpoint(
+ method="POST",
+ path="/analyzed-resource",
+ result_key="analyzedResources",
+ primary_keys=("analyzer_arn", "resource_arn"),
+ description="Resources that each external access analyzer analyzed, with or without findings.",
+ partition_key=None,
+ # ListAnalyzedResources rejects unused and internal access analyzers.
+ analyzer_types=EXTERNAL_ACCESS_ANALYZER_TYPES,
+ ),
+ "finding_details": Endpoint(
+ method="GET",
+ path="/findingv2/{id}",
+ result_key="findingDetails",
+ primary_keys=("analyzer_arn", "id"),
+ description="Full findings with the principals, actions, and unused permissions behind each finding.",
+ per_finding=True,
+ ),
+ "finding_recommendations": Endpoint(
+ method="GET",
+ path="/recommendation/{id}",
+ result_key="recommendedSteps",
+ primary_keys=("analyzer_arn", "finding_id"),
+ description="Remediation steps for unused permission findings that already have a generated recommendation.",
+ partition_key=None,
+ analyzer_types=UNUSED_ACCESS_ANALYZER_TYPES,
+ per_finding=True,
+ finding_types=frozenset({"UnusedPermission"}),
+ ),
}
+ACCESS_DENIED_MESSAGE = (
+ "AWS denied access. Grant access-analyzer:ListAnalyzers, access-analyzer:ListFindings, "
+ "access-analyzer:ListArchiveRules, access-analyzer:ListAnalyzedResources, access-analyzer:GetFinding, "
+ "and access-analyzer:GetFindingRecommendation for the tables you select."
+)
+
ERROR_MESSAGES = {
- "AccessDenied": "AWS denied access. Grant access-analyzer:ListAnalyzers, access-analyzer:ListFindings, and access-analyzer:ListArchiveRules for the tables you select.",
- "AccessDeniedException": "AWS denied access. Grant access-analyzer:ListAnalyzers, access-analyzer:ListFindings, and access-analyzer:ListArchiveRules for the tables you select.",
+ "AccessDenied": ACCESS_DENIED_MESSAGE,
+ "AccessDeniedException": ACCESS_DENIED_MESSAGE,
"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 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_iam_access_analyzer/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/source.py
index 1a6011f7eff4..bc192e1f250e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/source.py
@@ -121,13 +121,14 @@ class AwsIamAccessAnalyzerSource(ResumableSource[AwsIamAccessAnalyzerSourceConfi
name=ExternalDataSourceType.AWSIAMACCESSANALYZER,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="AWS IAM Access Analyzer",
- caption="""Sync access analyzers, findings, and archive rules from one AWS region.
+ caption="""Sync access analyzers, findings, archive rules, analyzed resources, finding details, and finding recommendations from one AWS region.
-Grant `access-analyzer:ListAnalyzers`, `access-analyzer:ListFindings`, and `access-analyzer:ListArchiveRules` for the tables you select.
+Grant `access-analyzer:ListAnalyzers`, `access-analyzer:ListFindings`, `access-analyzer:ListArchiveRules`, `access-analyzer:ListAnalyzedResources`, `access-analyzer:GetFinding`, and `access-analyzer:GetFindingRecommendation` for the tables you select.
Enter an access key ID and secret access key. Add a session token for temporary credentials.
Temporary credentials expire, so update them before later syncs.
-All tables use full refresh. The API does not support a date-range filter for findings.""",
+All tables use full refresh. The API does not support a date-range filter for findings.
+Finding recommendations only include recommendations that you already generated in AWS. The sync does not generate new ones.""",
iconPath="/static/services/aws_iam_access_analyzer.png",
docsUrl=API_DOCS_URL,
releaseStatus=ReleaseStatus.ALPHA,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/tests/test_aws_iam_access_analyzer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/tests/test_aws_iam_access_analyzer.py
index e8a17de2461b..25a188d15c7f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/tests/test_aws_iam_access_analyzer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/tests/test_aws_iam_access_analyzer.py
@@ -3,6 +3,7 @@ import datetime as dt
from collections.abc import Iterable
from dataclasses import asdict
from typing import Any, cast
+from urllib.parse import quote
import pytest
from unittest.mock import patch
@@ -44,6 +45,12 @@ CONFIG = AwsIamAccessAnalyzerSourceConfig(
)
PARENT_A = {"arn": "arn:aws:access-analyzer:eu-west-1:123456789012:analyzer/example-a", "name": "example-a"}
PARENT_B = {"arn": "arn:aws:access-analyzer:eu-west-1:123456789012:analyzer/example-b", "name": "example-b"}
+UNUSED_PARENT = {
+ "arn": "arn:aws:access-analyzer:eu-west-1:123456789012:analyzer/example-unused",
+ "name": "example-unused",
+ "type": "ACCOUNT_UNUSED_ACCESS",
+}
+EXTERNAL_PARENT = {**PARENT_A, "type": "ACCOUNT"}
def driver() -> SourceDriver:
@@ -87,6 +94,24 @@ def response(body: dict[str, Any], status: int = 200, headers: dict[str, str] |
("analyzers", "GET", "/analyzer?maxResults=100&nextToken=a%2B%2F%3D", None),
("findings", "POST", "/findingv2", {"maxResults": 100, "nextToken": "a+/=", "analyzerArn": PARENT_A["arn"]}),
("archive_rules", "GET", "/analyzer/example-a/archive-rule?maxResults=100&nextToken=a%2B%2F%3D", None),
+ (
+ "analyzed_resources",
+ "POST",
+ "/analyzed-resource",
+ {"maxResults": 100, "nextToken": "a+/=", "analyzerArn": PARENT_A["arn"]},
+ ),
+ (
+ "finding_details",
+ "GET",
+ "/findingv2/finding%2F1?maxResults=100&nextToken=a%2B%2F%3D&analyzerArn=arn%3Aaws%3Aaccess-analyzer%3Aeu-west-1%3A123456789012%3Aanalyzer%2Fexample-a",
+ None,
+ ),
+ (
+ "finding_recommendations",
+ "GET",
+ "/recommendation/finding%2F1?maxResults=100&nextToken=a%2B%2F%3D&analyzerArn=arn%3Aaws%3Aaccess-analyzer%3Aeu-west-1%3A123456789012%3Aanalyzer%2Fexample-a",
+ None,
+ ),
],
)
def test_requests_use_rest_json_and_sign_the_exact_url_and_body(
@@ -97,9 +122,9 @@ def test_requests_use_rest_json_and_sign_the_exact_url_and_body(
) as network:
client = AwsIamAccessAnalyzerClient(CONFIG, API_VERSION)
try:
- client.request(endpoint, analyzer=PARENT_A, next_token="a+/=")
+ client.request(endpoint, analyzer=PARENT_A, finding_id="finding/1", next_token="a+/=")
with pytest.raises(AwsIamAccessAnalyzerError) as caught:
- client.request(endpoint, analyzer=PARENT_A, next_token="a+/=")
+ client.request(endpoint, analyzer=PARENT_A, finding_id="finding/1", next_token="a+/=")
finally:
client.close()
@@ -191,6 +216,97 @@ def test_child_pages_resume_with_remaining_analyzers_and_parent_cursor(
assert resumed.saved_states[-1].finished
+def test_recommendations_fan_out_over_unused_permission_findings_of_unused_access_analyzers() -> None:
+ result = driver().run(
+ "finding_recommendations",
+ [
+ ScriptedResponse(json={"analyzers": [EXTERNAL_PARENT, UNUSED_PARENT]}),
+ ScriptedResponse(
+ json={
+ "findings": [
+ {"id": "unused-role", "findingType": "UnusedIAMRole"},
+ {"id": "not-generated", "findingType": "UnusedPermission"},
+ {"id": "generated", "findingType": "UnusedPermission"},
+ ]
+ }
+ ),
+ ScriptedResponse(status=404, json={"__type": "ResourceNotFoundException"}),
+ ScriptedResponse(
+ json={
+ "resourceArn": "arn:aws:iam::123456789012:role/example",
+ "status": "SUCCEEDED",
+ "startedAt": "2025-01-01T00:00:00Z",
+ "recommendedSteps": [{"step": 1}],
+ "nextToken": "steps-2",
+ }
+ ),
+ ScriptedResponse(json={"recommendedSteps": [{"step": 2}]}),
+ ],
+ )
+
+ assert result.raised is None
+ assert len(result.rows) == 1
+ row = result.rows[0]
+ assert row["finding_id"] == "generated"
+ assert row["analyzer_arn"] == UNUSED_PARENT["arn"]
+ assert row["recommended_steps"] == [{"step": 1}, {"step": 2}]
+ assert row["started_at"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)
+ assert "next_token" not in row
+ assert [request.url.split("?")[0].rsplit("/", 1)[-1] for request in result.requests[2:]] == [
+ "not-generated",
+ "generated",
+ "generated",
+ ]
+ assert result.requests[-1].url.endswith("nextToken=steps-2&analyzerArn=" + quote(UNUSED_PARENT["arn"], safe=""))
+ assert result.saved_states[-1].finished
+
+
+def test_analyzed_resources_skip_analyzers_that_do_not_support_them() -> None:
+ result = driver().run(
+ "analyzed_resources",
+ [
+ ScriptedResponse(json={"analyzers": [UNUSED_PARENT, EXTERNAL_PARENT]}),
+ ScriptedResponse(json={"analyzedResources": [{"resourceArn": "arn:aws:s3:::example"}]}),
+ ],
+ )
+
+ assert result.raised is None
+ assert result.rows == [
+ {"resource_arn": "arn:aws:s3:::example", "region": "eu-west-1", "analyzer_arn": EXTERNAL_PARENT["arn"]}
+ ]
+ assert result.requests[1].json() == {"maxResults": 100, "analyzerArn": EXTERNAL_PARENT["arn"]}
+
+
+def test_finding_details_resume_with_remaining_findings_and_findings_cursor() -> None:
+ first = driver().run(
+ "finding_details",
+ [
+ ScriptedResponse(json={"analyzers": [PARENT_A]}),
+ ScriptedResponse(json={"findings": [{"id": "f-1"}, {"id": "f-2"}], "nextToken": "findings-2"}),
+ ScriptedResponse(json={"id": "f-1", "findingDetails": [{"unusedPermissionDetails": {}}]}),
+ ],
+ )
+ assert [row["id"] for row in first.rows] == ["f-1"]
+ checkpoint = AwsIamAccessAnalyzerResumeConfig(**json.loads(json.dumps(asdict(first.final_state))))
+ assert checkpoint.pending_findings == ["f-2"]
+
+ resumed = driver().run(
+ "finding_details",
+ [
+ ScriptedResponse(json={"id": "f-2", "findingDetails": []}),
+ ScriptedResponse(json={"findings": [{"id": "f-3"}]}),
+ ScriptedResponse(json={"id": "f-3", "findingDetails": []}),
+ ],
+ resume_state=checkpoint,
+ )
+
+ assert resumed.raised is None
+ assert [row["id"] for row in resumed.rows] == ["f-2", "f-3"]
+ assert resumed.requests[0].url.split("?")[0].endswith("/findingv2/f-2")
+ assert resumed.requests[1].json() == {"maxResults": 100, "nextToken": "findings-2", "analyzerArn": PARENT_A["arn"]}
+ assert resumed.saved_states[-1].finished
+
+
@pytest.mark.parametrize("endpoint,result_key", [("findings", "findings"), ("archive_rules", "archiveRules")])
def test_deleted_analyzer_is_skipped(endpoint: str, result_key: str) -> None:
result = driver().run(
@@ -346,3 +462,19 @@ def test_table_validation_walks_empty_analyzer_pages() -> None:
assert validate_credentials(CONFIG, "findings") == (True, None)
assert network.requests_log[1].url.endswith("nextToken=next")
assert network.requests_log[-1].json() == {"maxResults": 1, "analyzerArn": PARENT_A["arn"]}
+
+
+def test_recommendation_validation_accepts_findings_without_a_generated_recommendation() -> None:
+ with scripted_network(
+ [
+ ScriptedResponse(json={"analyzers": [EXTERNAL_PARENT], "nextToken": "next"}),
+ ScriptedResponse(json={"analyzers": [UNUSED_PARENT]}),
+ ScriptedResponse(json={"findings": [{"id": "role", "findingType": "UnusedIAMRole"}], "nextToken": "more"}),
+ ScriptedResponse(json={"findings": [{"id": "f-1", "findingType": "UnusedPermission"}]}),
+ ScriptedResponse(status=404, json={"__type": "ResourceNotFoundException"}),
+ ]
+ ) as network:
+ assert validate_credentials(CONFIG, "finding_recommendations") == (True, None)
+ assert network.requests_log[2].json() == {"maxResults": 100, "analyzerArn": UNUSED_PARENT["arn"]}
+ assert network.requests_log[3].json()["nextToken"] == "more"
+ assert network.requests_log[-1].url.split("?")[0].endswith("/recommendation/f-1")