:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement the aws iam access analyzer import source (#110800)
Tom Owers75c0fcba413e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 4b717343bce9..4dfd8d5ac927 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -109,6 +109,7 @@ the row lists both.| aws_cost_anomaly_detection | HTTP | requests | ✅ || aws_cost_explorer | HTTP | requests | ✅ || aws_glue_data_catalog | HTTP | requests | ✅ |+| aws_iam_access_analyzer | HTTP | requests | ✅ || aws_inspector | HTTP | requests | ✅ || aws_organizations | HTTP | requests | ✅ || aws_sagemaker | HTTP | requests | ✅ |@@ -929,7 +930,6 @@ doesn't conflict with concurrent PRs.- aws_cost_and_usage_report- aws_guardduty- aws_health-- aws_iam_access_analyzer- aws_macie- aws_rds_performance_insights- aws_supportdiff --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.pynew file mode 100644index 000000000000..1c668a2a1690--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/aws_iam_access_analyzer.py@@ -0,0 +1,247 @@+import re+import json+import datetime as dt+from collections.abc import Generator+from dataclasses import field+from typing import Any+from urllib.parse import quote, urlencode++import requests+from botocore.auth import SigV4Auth+from botocore.awsrequest import AWSRequest+from botocore.credentials import Credentials++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.aws_iam_access_analyzer.settings import (+ API_VERSION,+ DEFAULT_REGION,+ ENDPOINTS,+ ERROR_MESSAGES,+ PAGE_SIZE,+ PARTITION_KEY,+ TIMESTAMP_COLUMNS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.transport import BoundedRetry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsiamaccessanalyzer import (+ AwsIamAccessAnalyzerSourceConfig,+)++_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")+++@frozen+class AwsIamAccessAnalyzerResumeConfig:+ next_token: str | None = None+ analyzers_next_token: str | None = None+ pending_analyzers: list[dict[str, str]] = field(default_factory=list)+ finished: bool = False+++class AwsIamAccessAnalyzerError(Exception):+ def __init__(self, code: str, message: str) -> None:+ self.code = code+ super().__init__(f"AWS IAM Access Analyzer request failed: {code} - {message}")+++class AwsIamAccessAnalyzerClient:+ def __init__(self, config: AwsIamAccessAnalyzerSourceConfig, api_version: str = API_VERSION) -> None:+ if api_version != API_VERSION:+ raise ValueError(f"Unsupported AWS IAM Access Analyzer API version: {api_version}")+ if not config.aws_access_key_id or not config.aws_secret_access_key:+ raise ValueError("Enter both an AWS access key ID and a secret access key.")+ self.region = (config.region or "").strip() or DEFAULT_REGION+ if not re.fullmatch(r"[a-z]{2}(?:-[a-z]+)+-\d+", self.region):+ raise ValueError("Enter a valid AWS region, such as us-east-1.")+ suffix = "amazonaws.com.cn" if self.region.startswith("cn-") else "amazonaws.com"+ self.url = f"https://access-analyzer.{self.region}.{suffix}"+ self.signer = SigV4Auth(+ Credentials(config.aws_access_key_id, config.aws_secret_access_key, config.aws_session_token or None),+ "access-analyzer",+ self.region,+ )+ self.session = make_tracked_session(+ retry=BoundedRetry(+ total=3,+ backoff_factor=1,+ status_forcelist=(429, 500, 502, 503, 504),+ allowed_methods=frozenset({"GET", "POST"}),+ raise_on_status=False,+ ),+ redact_values=tuple(+ value+ for value in (config.aws_access_key_id, config.aws_secret_access_key, config.aws_session_token)+ if value+ ),+ )++ def close(self) -> None:+ self.session.close()++ def request(+ self,+ endpoint: str,+ *,+ analyzer: dict[str, str] | None = None,+ next_token: str | None = None,+ page_size: int = PAGE_SIZE,+ ) -> dict[str, Any]:+ definition = ENDPOINTS[endpoint]+ payload: dict[str, Any] = {"maxResults": page_size}+ if next_token:+ payload["nextToken"] = next_token+ path = definition.path+ if endpoint != "analyzers":+ if analyzer is None:+ raise ValueError(f"An analyzer is required for {endpoint}.")+ if endpoint == "findings":+ payload["analyzerArn"] = analyzer["arn"]+ else:+ path = path.format(analyzer_name=quote(analyzer["name"], safe=""))+ url = self.url + path+ body = None+ if definition.method == "GET":+ url += "?" + urlencode(payload)+ else:+ body = json.dumps(payload).encode("utf-8")+ request = AWSRequest(method=definition.method, url=url, data=body, headers={"Content-Type": "application/json"})+ self.signer.add_auth(request)+ response = self.session.request(+ definition.method,+ url,+ data=body,+ headers=dict(request.headers),+ timeout=60,+ allow_redirects=False,+ )+ if response.status_code >= 300:+ try:+ error = response.json()+ except ValueError:+ error = {}+ if not isinstance(error, dict):+ error = {}+ raw_code = response.headers.get("x-amzn-ErrorType") or error.get("__type") or error.get("code")+ code = str(raw_code or f"HTTP {response.status_code}").split(":")[0].rsplit("#", 1)[-1]+ # AWS error text can include identifiers and credentials. Keep only the error code.+ raise AwsIamAccessAnalyzerError(code, ERROR_MESSAGES.get(code, "AWS could not complete the request."))+ return response.json()+++def normalize_row(row: dict[str, Any], region: str, analyzer: dict[str, str] | None = None) -> dict[str, Any]:+ result = {_CAMEL_BOUNDARY.sub("_", key).lower(): value for key, value in row.items()}+ for column in TIMESTAMP_COLUMNS:+ value = result.get(column)+ if isinstance(value, str) and value:+ result[column] = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))+ result["region"] = region+ if analyzer is not None:+ result["analyzer_arn"] = analyzer["arn"]+ return result+++def get_rows(+ config: AwsIamAccessAnalyzerSourceConfig,+ endpoint: str,+ manager: ResumableSourceManager[AwsIamAccessAnalyzerResumeConfig],+ api_version: str,+) -> Generator[list[dict[str, Any]]]:+ state = manager.load_state() if manager.can_resume() else None+ state = state or AwsIamAccessAnalyzerResumeConfig()+ if state.finished:+ return+ client = AwsIamAccessAnalyzerClient(config, api_version)+ try:+ while not state.finished:+ analyzer = None+ 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"]]+ parent_token = parent_page.get("nextToken") or None+ state = AwsIamAccessAnalyzerResumeConfig(+ pending_analyzers=parents,+ analyzers_next_token=parent_token,+ finished=not parents and parent_token is None,+ )+ if not parents:+ manager.save_state(state)+ manager.safe_point()+ continue+ analyzer = state.pending_analyzers[0]+ try:+ page = client.request(endpoint, analyzer=analyzer, next_token=state.next_token)+ except AwsIamAccessAnalyzerError as error:+ if analyzer is None or error.code != "ResourceNotFoundException":+ raise+ page = {ENDPOINTS[endpoint].result_key: []}+ rows = [normalize_row(row, client.region, analyzer) for row in page[ENDPOINTS[endpoint].result_key]]+ next_token = page.get("nextToken") or None+ 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,+ )+ manager.save_state(state)+ if rows:+ yield rows+ manager.safe_point()+ finally:+ client.close()+++def validate_credentials(+ config: AwsIamAccessAnalyzerSourceConfig,+ schema_name: str | None = None,+ api_version: str = API_VERSION,+) -> tuple[bool, str | None]:+ if schema_name is not None and schema_name not in ENDPOINTS:+ return False, f"Unknown AWS IAM Access Analyzer table: {schema_name}"+ try:+ client = AwsIamAccessAnalyzerClient(config, api_version)+ 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"):+ 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)+ return True, None+ finally:+ client.close()+ except AwsIamAccessAnalyzerError as error:+ if error.code in {"AccessDenied", "AccessDeniedException"} and schema_name is None:+ return True, None+ return False, ERROR_MESSAGES.get(error.code, "AWS could not validate these credentials. Try again.")+ except ValueError as error:+ return False, str(error)+ except requests.RequestException:+ return False, "Could not connect to AWS IAM Access Analyzer. Check the region and try again."+++def aws_iam_access_analyzer_source(+ config: AwsIamAccessAnalyzerSourceConfig,+ endpoint: str,+ manager: ResumableSourceManager[AwsIamAccessAnalyzerResumeConfig],+ api_version: str,+) -> SourceResponse:+ if endpoint not in ENDPOINTS:+ raise ValueError(f"Unknown AWS IAM Access Analyzer table: {endpoint}")+ 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",+ 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.pynew file mode 100644index 000000000000..ff5b319868f8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/canonical_descriptions.py@@ -0,0 +1,53 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "analyzers": {+ "description": "Access analyzers in the configured AWS region.",+ "docs_url": "https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_AnalyzerSummary.html",+ "columns": {+ "arn": "The Amazon Resource Name (ARN) of the analyzer.",+ "name": "The analyzer name.",+ "type": "The analyzer type and its account or organization scope.",+ "status": "The current analyzer status.",+ "created_at": "The time when AWS created the analyzer.",+ "last_resource_analyzed": "The ARN of the most recently analyzed resource.",+ "last_resource_analyzed_at": "The time of the most recent resource analysis.",+ "configuration": "The configuration for internal or unused access analysis.",+ "status_reason": "The reason for the current analyzer status.",+ "tags": "Tags attached to the analyzer.",+ "region": "The AWS region queried by this source.",+ },+ },+ "findings": {+ "description": "Finding summaries for external, internal, and unused access from each analyzer.",+ "docs_url": "https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_FindingSummaryV2.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.",+ "resource": "The ARN of the resource associated with the finding.",+ "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.",+ },+ },+ "archive_rules": {+ "description": "Rules that automatically archive matching findings for each analyzer.",+ "docs_url": "https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_ArchiveRuleSummary.html",+ "columns": {+ "rule_name": "The rule name within the analyzer.",+ "analyzer_arn": "The ARN of the analyzer that owns this rule.",+ "filter": "The conditions that a finding must meet for automatic archiving.",+ "created_at": "The time when AWS created the rule.",+ "updated_at": "The time when AWS last updated the rule.",+ "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.pynew file mode 100644index 000000000000..505213005b24--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/settings.py@@ -0,0 +1,58 @@+from typing import Literal++from posthog.dataclasses import frozen++API_VERSION = "2019-11-01"+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"}+++@frozen+class Endpoint:+ method: Literal["GET", "POST"]+ path: str+ result_key: str+ primary_keys: tuple[str, ...]+ description: str+++ENDPOINTS: dict[str, Endpoint] = {+ "analyzers": Endpoint(+ method="GET",+ path="/analyzer",+ result_key="analyzers",+ primary_keys=("arn",),+ description="Access analyzers in the configured AWS region.",+ ),+ "findings": Endpoint(+ method="POST",+ path="/findingv2",+ result_key="findings",+ primary_keys=("analyzer_arn", "id"),+ description="External, internal, and unused access findings from each analyzer.",+ ),+ "archive_rules": Endpoint(+ method="GET",+ path="/analyzer/{analyzer_name}/archive-rule",+ result_key="archiveRules",+ primary_keys=("analyzer_arn", "rule_name"),+ description="Rules that automatically archive findings for each analyzer.",+ ),+}++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.",+ "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.",+ "SignatureDoesNotMatch": "AWS rejected the signature. Check the secret access key and region.",+ "ExpiredTokenException": "The AWS session token has expired. Enter new temporary credentials.",+ "ExpiredToken": "The AWS session token has expired. Enter new temporary credentials.",+ "SubscriptionRequiredException": "AWS requires a subscription. Enable IAM Access Analyzer in the selected account and region.",+ "OptInRequired": "AWS requires access to this service. Enable IAM Access Analyzer in the selected account and region.",+ "ValidationException": "AWS rejected the request. Check the selected region and resume the sync with a fresh checkpoint.",+}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.pyindex 16ff55331caa..afb3d9e18208 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@@ -1,8 +1,38 @@from typing import cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_iam_access_analyzer.aws_iam_access_analyzer import (+ AwsIamAccessAnalyzerResumeConfig,+ aws_iam_access_analyzer_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_iam_access_analyzer.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_iam_access_analyzer.settings import (+ API_DOCS_URL,+ API_VERSION,+ DEFAULT_REGION,+ ENDPOINTS,+ ERROR_MESSAGES,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsiamaccessanalyzer import (AwsIamAccessAnalyzerSourceConfig,)@@ -10,18 +40,124 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AwsIamAccessAnalyzerSource(SimpleSource[AwsIamAccessAnalyzerSourceConfig]):+class AwsIamAccessAnalyzerSource(ResumableSource[AwsIamAccessAnalyzerSourceConfig, AwsIamAccessAnalyzerResumeConfig]):+ lists_tables_without_credentials = True+ supported_versions = (API_VERSION,)+ default_version = API_VERSION+ api_docs_url = API_DOCS_URL+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.AWSIAMACCESSANALYZER+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {f"AWS IAM Access Analyzer request failed: {code}": message for code, message in ERROR_MESSAGES.items()}++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: AwsIamAccessAnalyzerSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(+ ENDPOINTS, {}, names, descriptions={name: endpoint.description for name, endpoint in ENDPOINTS.items()}+ )++ def validate_credentials(+ self,+ config: AwsIamAccessAnalyzerSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_credentials(config, schema_name, self.resolve_api_version(api_version))++ def get_endpoint_permissions(+ self,+ config: AwsIamAccessAnalyzerSourceConfig,+ team_id: int,+ endpoints: list[str],+ api_version: str | None = None,+ ) -> dict[str, str | None]:+ return {+ endpoint: validate_credentials(config, endpoint, self.resolve_api_version(api_version))[1]+ for endpoint in endpoints+ }++ def get_resumable_source_manager(+ self, inputs: SourceInputs+ ) -> ResumableSourceManager[AwsIamAccessAnalyzerResumeConfig]:+ return ResumableSourceManager(inputs, AwsIamAccessAnalyzerResumeConfig)++ def source_for_pipeline(+ self,+ config: AwsIamAccessAnalyzerSourceConfig,+ resumable_source_manager: ResumableSourceManager[AwsIamAccessAnalyzerResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return aws_iam_access_analyzer_source(+ config, inputs.schema_name, resumable_source_manager, self.resolve_api_version(inputs.api_version)+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.AWSIAMACCESSANALYZER,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- label="Amazon Web Services (AWS IAM Access Analyzer)",+ label="AWS IAM Access Analyzer",+ caption="""Sync access analyzers, findings, and archive rules from one AWS region.++Grant `access-analyzer:ListAnalyzers`, `access-analyzer:ListFindings`, and `access-analyzer:ListArchiveRules` 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.""",iconPath="/static/services/aws_iam_access_analyzer.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl=API_DOCS_URL,+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["aws", "iam", "access analyzer", "security"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="aws_access_key_id",+ label="AWS access key ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="AKIA...",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="aws_secret_access_key",+ label="AWS secret access key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="aws_session_token",+ label="AWS session token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="Only needed for temporary credentials",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="region",+ label="AWS region",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ caption="Leave this blank to use us-east-1.",+ placeholder=DEFAULT_REGION,+ secret=False,+ ),+ ],+ ),)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.pynew file mode 100644index 000000000000..4d42bd9101e5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/tests/test_aws_iam_access_analyzer.py@@ -0,0 +1,378 @@+import json+import datetime as dt+from collections.abc import Iterable+from dataclasses import asdict+from typing import Any, cast++import pytest+from unittest.mock import patch++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.aws_iam_access_analyzer import (+ aws_iam_access_analyzer as transport,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_iam_access_analyzer.aws_iam_access_analyzer import (+ AwsIamAccessAnalyzerClient,+ AwsIamAccessAnalyzerError,+ AwsIamAccessAnalyzerResumeConfig,+ aws_iam_access_analyzer_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_iam_access_analyzer.settings import (+ API_VERSION,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsiamaccessanalyzer import (+ AwsIamAccessAnalyzerSourceConfig,+)++CONFIG = AwsIamAccessAnalyzerSourceConfig(+ aws_access_key_id="AKIAEXAMPLE",+ aws_secret_access_key="example-secret",+ aws_session_token="example-token",+ region="eu-west-1",+)+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"}+++class FakeManager(ResumableSourceManager[AwsIamAccessAnalyzerResumeConfig]):+ def __init__(self, state: AwsIamAccessAnalyzerResumeConfig | None = None) -> None:+ self.state = state+ self.saved: list[AwsIamAccessAnalyzerResumeConfig] = []+ self.safe_points = 0+ self.cleared: bool = False++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> AwsIamAccessAnalyzerResumeConfig | None:+ return self.state++ def save_state(self, data: AwsIamAccessAnalyzerResumeConfig) -> None:+ self.saved.append(data)++ def safe_point(self) -> None:+ self.safe_points += 1++ def clear_state(self) -> None:+ self.cleared = True+++def response(body: dict[str, Any], status: int = 200, headers: dict[str, str] | None = None) -> requests.Response:+ result = requests.Response()+ result.status_code = status+ result._content = json.dumps(body).encode()+ result.headers.update(headers or {})+ return result+++ "endpoint,method,path,payload",+ [+ ("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),+ ],+)+def test_requests_use_rest_json_and_sign_the_exact_url_and_body(+ endpoint: str, method: str, path: str, payload: dict[str, Any] | None+) -> None:+ with patch.object(transport, "make_tracked_session") as make_session:+ session = make_session.return_value+ session.request.return_value = response({})+ client = AwsIamAccessAnalyzerClient(CONFIG, API_VERSION)+ client.request(endpoint, analyzer=PARENT_A, next_token="a+/=")++ args, kwargs = session.request.call_args+ assert args == (method, "https://access-analyzer.eu-west-1.amazonaws.com" + path)+ assert (json.loads(kwargs["data"]) if kwargs["data"] else None) == payload+ headers = kwargs["headers"]+ assert headers["Content-Type"] == "application/json"+ assert "X-Amz-Target" not in headers+ assert headers["X-Amz-Security-Token"] == "example-token"+ assert "/eu-west-1/access-analyzer/aws4_request" in headers["Authorization"]+ assert "x-amz-security-token" in headers["Authorization"]+ assert headers["X-Amz-Date"]+ assert kwargs["allow_redirects"] is False+ assert make_session.call_args.kwargs["redact_values"] == ("AKIAEXAMPLE", "example-secret", "example-token")+ retry = make_session.call_args.kwargs["retry"]+ assert retry.is_retry(method, 429)+ assert retry.is_retry(method, 503)+ assert not retry.is_retry(method, 403)+++def test_analyzer_pagination_continues_after_empty_page_and_stages_terminal_state() -> None:+ manager = FakeManager()+ with patch.object(transport, "make_tracked_session") as factory:+ session = factory.return_value+ session.request.side_effect = [+ response({"analyzers": [], "nextToken": "next"}),+ response({"analyzers": [{**PARENT_A, "createdAt": "2025-01-01T00:00:00Z"}]}),+ ]+ result = aws_iam_access_analyzer_source(CONFIG, "analyzers", manager, API_VERSION)+ batches = list(cast(Iterable[list[dict[str, Any]]], result.items()))+ assert manager.cleared is False+ assert result.on_complete is not None+ result.on_complete()+ assert len(batches) == 1+ assert batches[0][0]["created_at"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)+ assert batches[0][0]["region"] == "eu-west-1"+ assert session.request.call_args_list[1].args[1].endswith("&nextToken=next")+ assert manager.saved[0].next_token == "next"+ assert manager.saved[-1].finished+ assert manager.safe_points == 2+ session.close.assert_called_once()+ assert manager.cleared+++ "endpoint,result_key,id_key", [("findings", "findings", "id"), ("archive_rules", "archiveRules", "ruleName")]+)+def test_child_pages_resume_with_remaining_analyzers_and_parent_cursor(+ endpoint: str, result_key: str, id_key: str+) -> None:+ manager = FakeManager()+ with patch.object(transport, "make_tracked_session") as factory:+ session = factory.return_value+ session.request.side_effect = [+ response({"analyzers": [PARENT_A], "nextToken": "parents-2"}),+ response({result_key: [{id_key: "same-id"}], "nextToken": "children-2"}),+ ]+ first_run = get_rows(CONFIG, endpoint, manager, API_VERSION)+ first_batch = next(first_run)+ checkpoint = AwsIamAccessAnalyzerResumeConfig(**json.loads(json.dumps(asdict(manager.saved[-1]))))+ first_run.close()+ assert checkpoint.next_token == "children-2"+ resumed = FakeManager(checkpoint)+ session.request.reset_mock()+ session.request.side_effect = [+ response({result_key: []}),+ response({"analyzers": [], "nextToken": "parents-3"}),+ response({"analyzers": [PARENT_B]}),+ response({result_key: [{id_key: "same-id"}]}),+ ]+ remaining = list(get_rows(CONFIG, endpoint, resumed, API_VERSION))++ assert first_batch[0]["analyzer_arn"] == PARENT_A["arn"]+ assert remaining[0][0]["analyzer_arn"] == PARENT_B["arn"]+ first_call = session.request.call_args_list[0]+ if endpoint == "findings":+ assert json.loads(first_call.kwargs["data"]) == {+ "analyzerArn": PARENT_A["arn"],+ "maxResults": 100,+ "nextToken": "children-2",+ }+ else:+ assert first_call.args[1].endswith("/example-a/archive-rule?maxResults=100&nextToken=children-2")+ assert session.request.call_args_list[1].args[1].endswith("nextToken=parents-2")+ assert session.request.call_args_list[2].args[1].endswith("nextToken=parents-3")+ assert resumed.safe_points == 3+ assert resumed.saved[-1].finished++[email protected]("endpoint,result_key", [("findings", "findings"), ("archive_rules", "archiveRules")])+def test_deleted_analyzer_is_skipped(endpoint: str, result_key: str) -> None:+ manager = FakeManager(AwsIamAccessAnalyzerResumeConfig(pending_analyzers=[PARENT_A, PARENT_B]))+ with patch.object(transport, "make_tracked_session") as factory:+ session = factory.return_value+ session.request.side_effect = [+ response({"__type": "ResourceNotFoundException"}, 404),+ response({result_key: [{"id": "remaining"}]}),+ ]+ rows = list(get_rows(CONFIG, endpoint, manager, API_VERSION))++ assert rows[0][0]["analyzer_arn"] == PARENT_B["arn"]+ assert manager.saved[0].pending_analyzers == [PARENT_B]+ assert manager.saved[-1].finished+++def test_child_request_errors_other_than_deleted_analyzers_are_raised() -> None:+ manager = FakeManager(AwsIamAccessAnalyzerResumeConfig(pending_analyzers=[PARENT_A]))+ with patch.object(transport, "make_tracked_session") as factory:+ factory.return_value.request.return_value = response({"__type": "AccessDeniedException"}, 403)+ with pytest.raises(AwsIamAccessAnalyzerError, match="AccessDeniedException"):+ list(get_rows(CONFIG, "findings", manager, API_VERSION))++[email protected]("endpoint", ["analyzers", "findings", "archive_rules"])+def test_terminal_checkpoint_does_not_restart_the_sync(endpoint: str) -> None:+ with patch.object(transport, "make_tracked_session") as factory:+ assert (+ list(get_rows(CONFIG, endpoint, FakeManager(AwsIamAccessAnalyzerResumeConfig(finished=True)), API_VERSION))+ == []+ )+ factory.assert_not_called()++[email protected]("endpoint", ["findings", "archive_rules"])+def test_no_analyzers_finishes_without_child_requests(endpoint: str) -> None:+ manager = FakeManager()+ with patch.object(transport, "make_tracked_session") as factory:+ factory.return_value.request.return_value = response({"analyzers": []})+ assert list(get_rows(CONFIG, endpoint, manager, API_VERSION)) == []+ factory.return_value.request.assert_called_once()+ assert manager.saved[-1].finished+ assert manager.safe_points == 1+++ "code,status,header",+ [+ ("AccessDeniedException", 403, True),+ ("UnrecognizedClientException", 403, False),+ ("InvalidSignatureException", 403, False),+ ("SubscriptionRequiredException", 400, False),+ ("ThrottlingException", 429, True),+ ],+)+def test_errors_extract_aws_codes_without_exposing_response_text(code: str, status: int, header: bool) -> None:+ with patch.object(transport, "make_tracked_session") as factory:+ factory.return_value.request.return_value = response(+ {"__type": f"aws#{code}", "message": "example-secret"},+ status,+ {"x-amzn-ErrorType": f"{code}:extra"} if header else {},+ )+ with pytest.raises(AwsIamAccessAnalyzerError) as caught:+ AwsIamAccessAnalyzerClient(CONFIG).request("analyzers")+ assert caught.value.code == code+ assert "example-secret" not in str(caught.value)++[email protected]("schema_name", [None, "analyzers", "findings", "archive_rules"])+ "code",+ [+ "AccessDeniedException",+ "AccessDenied",+ "UnrecognizedClientException",+ "InvalidSignatureException",+ "ExpiredTokenException",+ "SubscriptionRequiredException",+ ],+)+def test_validation_accepts_only_missing_permissions_at_source_creation(schema_name: str | None, code: str) -> None:+ with patch.object(transport, "make_tracked_session") as factory:+ factory.return_value.request.return_value = response({"__type": code}, 403)+ valid, message = validate_credentials(CONFIG, schema_name)+ assert valid == (schema_name is None and code in {"AccessDenied", "AccessDeniedException"})+ assert (message is None) == valid+ factory.return_value.request.assert_called_once()+ factory.return_value.close.assert_called_once()++[email protected]("schema_name", [None, "findings", "archive_rules"])+def test_validation_checks_child_permissions_only_for_a_selected_table(schema_name: str | None) -> None:+ with patch.object(transport, "make_tracked_session") as factory:+ session = factory.return_value+ session.request.side_effect = [+ response({"analyzers": [PARENT_A]}),+ response({"__type": "AccessDeniedException"}, 403),+ ]+ valid, message = validate_credentials(CONFIG, schema_name)+ assert valid == (schema_name is None)+ assert session.request.call_count == (1 if schema_name is None else 2)+ assert (message is None) == valid+ assert "maxResults=1" in session.request.call_args_list[0].args[1]+++ "region,suffix", [("cn-north-1", "amazonaws.com.cn"), ("us-gov-west-1", "amazonaws.com"), ("", "amazonaws.com")]+)+def test_region_controls_endpoint_and_signing_scope(region: str, suffix: str) -> None:+ config = AwsIamAccessAnalyzerSourceConfig(+ aws_access_key_id="AKIAEXAMPLE", aws_secret_access_key="example-secret", region=region+ )+ with patch.object(transport, "make_tracked_session") as factory:+ factory.return_value.request.return_value = response({"analyzers": []})+ AwsIamAccessAnalyzerClient(config).request("analyzers")+ call = factory.return_value.request.call_args+ expected_region = region or "us-east-1"+ assert call.args[1].startswith(f"https://access-analyzer.{expected_region}.{suffix}/")+ assert f"/{expected_region}/access-analyzer/" in call.kwargs["headers"]["Authorization"]+ assert "X-Amz-Security-Token" not in call.kwargs["headers"]+++ "field,value", [("region", "bad.example/path"), ("aws_access_key_id", ""), ("aws_secret_access_key", "")]+)+def test_invalid_configuration_fails_before_network(field: str, value: str) -> None:+ config = AwsIamAccessAnalyzerSourceConfig(aws_access_key_id="AKIAEXAMPLE", aws_secret_access_key="example-secret")+ setattr(config, field, value)+ with patch.object(transport, "make_tracked_session") as factory:+ valid, message = validate_credentials(config)+ assert not valid+ assert message+ factory.assert_not_called()+++def test_unknown_version_and_table_fail_before_network() -> None:+ with patch.object(transport, "make_tracked_session") as factory:+ assert validate_credentials(CONFIG, api_version="2099-01-01")[0] is False+ assert validate_credentials(CONFIG, schema_name="unknown")[0] is False+ with pytest.raises(ValueError, match="Unknown"):+ aws_iam_access_analyzer_source(CONFIG, "unknown", FakeManager(), API_VERSION)+ with pytest.raises(ValueError, match="required"):+ AwsIamAccessAnalyzerClient(CONFIG).request("findings")+ factory.return_value.request.assert_not_called()+++def test_transport_failure_returns_a_safe_validation_message() -> None:+ with patch.object(transport, "make_tracked_session") as factory:+ factory.return_value.request.side_effect = requests.ConnectionError("example-secret")+ valid, message = validate_credentials(CONFIG)+ assert not valid+ assert message is not None and "example-secret" not in message+ factory.return_value.close.assert_called_once()+++ "endpoint,result_key,id_key", [("findings", "findings", "id"), ("archive_rules", "archiveRules", "ruleName")]+)+def test_resume_between_analyzers_does_not_repeat_the_completed_analyzer(+ endpoint: str, result_key: str, id_key: str+) -> None:+ manager = FakeManager()+ with patch.object(transport, "make_tracked_session") as factory:+ session = factory.return_value+ session.request.side_effect = [+ response({"analyzers": [PARENT_A, PARENT_B]}),+ response({result_key: [{id_key: "same-id"}]}),+ ]+ first_run = get_rows(CONFIG, endpoint, manager, API_VERSION)+ next(first_run)+ checkpoint = manager.saved[-1]+ first_run.close()+ resumed = FakeManager(checkpoint)+ session.request.reset_mock()+ session.request.side_effect = [response({result_key: [{id_key: "same-id"}]})]+ rows = list(get_rows(CONFIG, endpoint, resumed, API_VERSION))+ session.request.assert_called_once()+ assert rows[0][0]["analyzer_arn"] == PARENT_B["arn"]+ assert resumed.saved[-1].finished++[email protected]("status,body", [(500, b"<html>error</html>"), (502, b"[]"), (302, b"")])+def test_non_json_and_redirect_errors_keep_the_http_status(status: int, body: bytes) -> None:+ error_response = response({}, status)+ error_response._content = body+ with patch.object(transport, "make_tracked_session") as factory:+ factory.return_value.request.return_value = error_response+ with pytest.raises(AwsIamAccessAnalyzerError) as caught:+ AwsIamAccessAnalyzerClient(CONFIG).request("analyzers")+ assert caught.value.code == f"HTTP {status}"+++def test_table_validation_walks_empty_analyzer_pages() -> None:+ with patch.object(transport, "make_tracked_session") as factory:+ session = factory.return_value+ session.request.side_effect = [+ response({"analyzers": [], "nextToken": "next"}),+ response({"analyzers": [PARENT_A]}),+ response({"findings": []}),+ ]+ assert validate_credentials(CONFIG, "findings") == (True, None)+ assert session.request.call_args_list[1].args[1].endswith("nextToken=next")+ assert json.loads(session.request.call_args.kwargs["data"]) == {"maxResults": 1, "analyzerArn": PARENT_A["arn"]}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/tests/test_aws_iam_access_analyzer_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/tests/test_aws_iam_access_analyzer_source.pynew file mode 100644index 000000000000..fe78caeff6b3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_iam_access_analyzer/tests/test_aws_iam_access_analyzer_source.py@@ -0,0 +1,103 @@+import json+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest.mock import patch++import structlog++from products.warehouse_sources.backend.temporal.data_imports.sources.aws_iam_access_analyzer import (+ aws_iam_access_analyzer as transport,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_iam_access_analyzer.source import (+ AwsIamAccessAnalyzerSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_iam_access_analyzer.tests.test_aws_iam_access_analyzer import (+ CONFIG,+ PARENT_A,+ FakeManager,+ response,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs++[email protected]("incremental", [False, True])+def test_pipeline_does_not_filter_findings_by_a_stored_watermark(incremental: bool) -> None:+ inputs = SourceInputs(+ schema_name="findings",+ schema_id="schema",+ source_id="source",+ team_id=1,+ should_use_incremental_field=incremental,+ db_incremental_field_last_value="2025-01-01T00:00:00Z",+ db_incremental_field_earliest_value=None,+ incremental_field="updated_at",+ incremental_field_type=None,+ job_id="job",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+ with patch.object(transport, "make_tracked_session") as factory:+ factory.return_value.request.side_effect = [+ response({"analyzers": [PARENT_A]}),+ response({"findings": [{"id": "example-finding"}]}),+ ]+ result = AwsIamAccessAnalyzerSource().source_for_pipeline(CONFIG, FakeManager(), inputs)+ rows = list(cast(Iterable[Any], result.items()))+ assert rows[0][0]["analyzer_arn"] == PARENT_A["arn"]+ assert result.primary_keys == ["analyzer_arn", "id"]+ assert json.loads(factory.return_value.request.call_args.kwargs["data"]) == {+ "maxResults": 100,+ "analyzerArn": PARENT_A["arn"],+ }+++ "names,expected",+ [(None, ["analyzers", "findings", "archive_rules"]), (["findings"], ["findings"]), (["missing"], [])],+)+def test_schema_selection_does_not_require_credentials(names: list[str] | None, expected: list[str]) -> None:+ with patch.object(transport, "make_tracked_session") as factory:+ schemas = AwsIamAccessAnalyzerSource().get_schemas(CONFIG, 1, names=names)+ assert [schema.name for schema in schemas] == expected+ assert all(not schema.supports_incremental and not schema.supports_append for schema in schemas)+ factory.assert_not_called()+++def test_permission_errors_are_scoped_to_each_selected_table() -> None:+ with patch.object(transport, "make_tracked_session") as factory:+ factory.return_value.request.side_effect = [+ response({"analyzers": [PARENT_A]}),+ response({"analyzers": [PARENT_A]}),+ response({"__type": "AccessDeniedException"}, 403),+ ]+ permissions = AwsIamAccessAnalyzerSource().get_endpoint_permissions(CONFIG, 1, ["analyzers", "findings"])+ assert permissions["analyzers"] is None+ assert "access-analyzer:ListFindings" in (permissions["findings"] or "")+++ "code,terminal",+ [+ ("AccessDeniedException", True),+ ("UnrecognizedClientException", True),+ ("InvalidSignatureException", True),+ ("SubscriptionRequiredException", True),+ ("ValidationException", True),+ ("ThrottlingException", False),+ ("InternalServerException", False),+ ],+)+def test_api_errors_match_the_pipeline_retry_policy(code: str, terminal: bool) -> None:+ with patch.object(transport, "make_tracked_session") as factory:+ factory.return_value.request.return_value = response({"__type": code}, 403 if terminal else 500)+ with pytest.raises(transport.AwsIamAccessAnalyzerError) as caught:+ transport.AwsIamAccessAnalyzerClient(CONFIG).request("analyzers")+ matches = [+ message+ for pattern, message in AwsIamAccessAnalyzerSource().get_non_retryable_errors().items()+ if pattern in str(caught.value)+ ]+ assert bool(matches) == terminal+ assert all(matches)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsiamaccessanalyzer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsiamaccessanalyzer.pyindex 921932a94939..28eb88e1538b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsiamaccessanalyzer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsiamaccessanalyzer.py@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass AwsIamAccessAnalyzerSourceConfig(config.Config):- pass+ aws_access_key_id: str+ aws_secret_access_key: str+ aws_session_token: str | None = None+ region: str | None = None