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 Organizations import source (#84479)

Tom Owers59c2a236c5e5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/aws_organizations.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/aws_organizations.py
new file mode 100644
index 000000000000..7f4482598f2b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/aws_organizations.py
@@ -0,0 +1,685 @@
+import re
+import json
+import datetime as dt
+import dataclasses
+from collections.abc import Callable, Iterator
+from typing import Any, Optional
+
+import requests
+from botocore.auth import SigV4Auth
+from botocore.awsrequest import AWSRequest
+from botocore.credentials import Credentials
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_organizations.settings import (
+ AWS_ORGANIZATIONS_ENDPOINTS,
+ CONTENT_TYPE,
+ CREDENTIAL_ERROR_CODES,
+ MAX_RESULTS,
+ MAX_RETRY_ATTEMPTS,
+ ORGANIZATIONS_API_VERSION,
+ ORGANIZATIONS_ENDPOINT_URL,
+ POLICY_FILTERS,
+ REQUEST_TIMEOUT_SECONDS,
+ RETRY_INITIAL_WAIT_SECONDS,
+ RETRY_MAX_WAIT_SECONDS,
+ RETRYABLE_ERROR_CODES,
+ SIGNING_NAME,
+ SIGNING_REGION,
+ TARGET_PREFIXES,
+ AwsOrganizationsEndpointConfig,
+)
+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
+
+# Organizations is a POST-only JSON RPC and the tracked session's default policy only retries
+# idempotent verbs, so POST is opted in explicitly for the transport-level statuses.
+TRANSPORT_RETRY = BoundedRetry(
+ total=3,
+ backoff_factor=1,
+ status_forcelist=(429, 500, 502, 503, 504),
+ allowed_methods=frozenset(["POST"]),
+ raise_on_status=False,
+)
+
+_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
+
+_IAM_ACTION_PATTERN = re.compile(r"organizations:[A-Za-z0-9]+")
+
+
+class AwsOrganizationsError(Exception):
+ def __init__(self, code: str, message: str) -> None:
+ super().__init__(f"AWS Organizations request failed: {code} - {message}")
+ self.code = code
+ self.message = message
+
+
+class AwsOrganizationsRetryableError(AwsOrganizationsError):
+ pass
+
+
[email protected](frozen=True)
+class AwsOrganizationsResumeConfig:
+ """Where a previous attempt stopped: the page token, and which sub-walk it belonged to.
+
+ `work_key` is the `ListPolicies` filter for the policies table and `None` everywhere else.
+ """
+
+ next_token: Optional[str] = None
+ work_key: Optional[str] = None
+
+
[email protected](frozen=True)
+class Page:
+ items: list[dict[str, Any]]
+ next_token: Optional[str]
+
+
+def target_prefix(api_version: Optional[str]) -> str:
+ version = api_version or ORGANIZATIONS_API_VERSION
+ prefix = TARGET_PREFIXES.get(version)
+ if prefix is None:
+ raise ValueError(f"Unsupported AWS Organizations API version: {version!r}")
+ return prefix
+
+
+def result_key(endpoint_config: AwsOrganizationsEndpointConfig) -> str:
+ if endpoint_config.result_key is None:
+ raise ValueError(f"{endpoint_config.name} is not a paginated list endpoint")
+ return endpoint_config.result_key
+
+
+def _snake(name: str) -> str:
+ """`MasterAccountId` -> `master_account_id`, `FeatureSet` -> `feature_set`."""
+ return _CAMEL_BOUNDARY.sub("_", name).lower()
+
+
+def _parse_timestamp(value: Any) -> Any:
+ """Organizations serializes timestamps as epoch seconds; leave anything else untouched."""
+ if isinstance(value, int | float) and not isinstance(value, bool):
+ return dt.datetime.fromtimestamp(value, tz=dt.UTC)
+ if isinstance(value, str) and value:
+ try:
+ parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return value
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=dt.UTC)
+ return value
+
+
+def _flatten(prefix: str, obj: dict[str, Any]) -> dict[str, Any]:
+ flattened: dict[str, Any] = {}
+ for key, value in obj.items():
+ column = f"{prefix}_{_snake(key)}" if prefix else _snake(key)
+ if isinstance(value, dict):
+ flattened.update(_flatten(column, value))
+ else:
+ flattened[column] = value
+ return flattened
+
+
+def normalize_row(endpoint_config: AwsOrganizationsEndpointConfig, obj: dict[str, Any]) -> dict[str, Any]:
+ """Flatten nested structures into snake_case columns and parse epoch timestamps."""
+ kept = {key: value for key, value in obj.items() if key not in endpoint_config.drop_keys}
+ row = _flatten("", kept)
+ for column in endpoint_config.timestamp_columns:
+ if column in row:
+ row[column] = _parse_timestamp(row[column])
+ return row
+
+
+def _error_code(response: requests.Response, body: dict[str, Any]) -> str:
+ header = response.headers.get("x-amzn-ErrorType") or ""
+ if header:
+ return header.split(":")[0].split("#")[-1]
+ # AWS returns `{"__type": "com.amazonaws.organizations#AccessDeniedException"}`; some
+ # fronting errors use a bare `code` instead.
+ raw = body.get("__type") or body.get("code") or f"HTTP {response.status_code}"
+ return str(raw).rsplit("#", 1)[-1]
+
+
+def _error_message(response: requests.Response, body: dict[str, Any]) -> str:
+ for key in ("message", "Message", "errorMessage", "Reason"):
+ value = body.get(key)
+ if value:
+ return str(value)[:500]
+ return response.text[:500]
+
+
+def error_for_response(response: requests.Response) -> AwsOrganizationsError:
+ try:
+ body = response.json()
+ except ValueError:
+ body = {}
+ if not isinstance(body, dict):
+ body = {}
+ code = _error_code(response, body)
+ message = _error_message(response, body)
+ if code in RETRYABLE_ERROR_CODES or response.status_code >= 500:
+ return AwsOrganizationsRetryableError(code, message)
+ return AwsOrganizationsError(code, message)
+
+
+class AwsOrganizationsClient:
+ """SigV4-signed JSON client for the AWS Organizations API.
+
+ Every operation is a POST to the single global endpoint, discriminated by `X-Amz-Target`,
+ so there is no REST surface the declarative framework could drive. Signing rides botocore
+ (already a repo dependency) but the request goes out over the tracked session so it stays
+ in our HTTP logs and metrics.
+ """
+
+ def __init__(
+ self,
+ access_key_id: str,
+ secret_access_key: str,
+ session_token: Optional[str] = None,
+ api_version: Optional[str] = None,
+ ) -> None:
+ self.target_prefix = target_prefix(api_version)
+ self._credentials = Credentials(access_key_id, secret_access_key, session_token or None)
+ self._signer = SigV4Auth(self._credentials, SIGNING_NAME, SIGNING_REGION)
+ self._session = make_tracked_session(
+ retry=TRANSPORT_RETRY,
+ redact_values=tuple(value for value in (secret_access_key, session_token) if value),
+ )
+
+ def _signed_headers(self, operation: str, body: bytes) -> dict[str, str]:
+ request = AWSRequest(
+ method="POST",
+ url=ORGANIZATIONS_ENDPOINT_URL,
+ data=body,
+ headers={
+ "Content-Type": CONTENT_TYPE,
+ "X-Amz-Target": f"{self.target_prefix}.{operation}",
+ },
+ )
+ self._signer.add_auth(request)
+ return dict(request.headers)
+
+ def send(self, operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ body = json.dumps(payload).encode("utf-8")
+ response = self._session.post(
+ ORGANIZATIONS_ENDPOINT_URL,
+ data=body,
+ headers=self._signed_headers(operation, body),
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ if response.status_code >= 400:
+ raise error_for_response(response)
+ parsed = response.json()
+ return parsed if isinstance(parsed, dict) else {}
+
+ # Throttling arrives as HTTP 400 with the code in the body, which the tracked transport's
+ # status-code retries can't see, so there is no compounding here.
+ @retry(
+ retry=retry_if_exception_type((AwsOrganizationsRetryableError, requests.ConnectionError, requests.Timeout)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=RETRY_INITIAL_WAIT_SECONDS, max=RETRY_MAX_WAIT_SECONDS),
+ reraise=True,
+ )
+ def request(self, operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ return self.send(operation, payload)
+
+
+def _is_invalid_token(error: AwsOrganizationsError) -> bool:
+ return "INVALID_PAGINATION_TOKEN" in error.message.upper() or error.code == "InvalidPaginationTokenException"
+
+
+def is_policy_type_unavailable(error: AwsOrganizationsError) -> bool:
+ """True when a policy type simply isn't offered here, rather than being denied to us."""
+ if error.code == "UnsupportedAPIEndpointException":
+ return True
+ # Partitions that don't offer a policy type reject its enum value outright instead of
+ # returning an empty list.
+ return error.code == "InvalidInputException" and "INVALID_ENUM" in error.message.upper()
+
+
+def iter_pages(
+ client: AwsOrganizationsClient,
+ operation: str,
+ payload: dict[str, Any],
+ items_key: str,
+ logger: FilteringBoundLogger,
+ start_token: Optional[str] = None,
+) -> Iterator[Page]:
+ next_token = start_token
+ resumed = start_token is not None
+
+ while True:
+ request_payload = dict(payload)
+ if next_token:
+ request_payload["NextToken"] = next_token
+
+ try:
+ body = client.request(operation, request_payload)
+ except AwsOrganizationsError as error:
+ # A token saved by a previous attempt can expire; restart the walk instead of
+ # failing the job. Merge on the primary key absorbs the re-read rows.
+ if resumed and _is_invalid_token(error):
+ logger.debug(f"Saved page token no longer valid; restarting. operation={operation}")
+ next_token = None
+ resumed = False
+ continue
+ raise
+ resumed = False
+
+ items = [item for item in body.get(items_key) or [] if isinstance(item, dict)]
+ next_token = body.get("NextToken") or None
+ yield Page(items=items, next_token=next_token)
+ # AWS documents that these operations can return an empty page while more results are
+ # still available, so only a null token ends the walk.
+ if not next_token:
+ return
+
+
+def iter_items(
+ client: AwsOrganizationsClient,
+ operation: str,
+ payload: dict[str, Any],
+ items_key: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[dict[str, Any]]:
+ for page in iter_pages(client, operation, payload, items_key, logger):
+ yield from page.items
+
+
+def _checkpointed_rows(
+ pages: Iterator[Page],
+ rows_for_items: Callable[[list[dict[str, Any]]], list[dict[str, Any]]],
+ resumable_source_manager: ResumableSourceManager[AwsOrganizationsResumeConfig],
+ work_key: Optional[str] = None,
+) -> Iterator[list[dict[str, Any]]]:
+ for page in pages:
+ rows = rows_for_items(page.items)
+ if rows:
+ yield rows
+ # Saved after yielding: a crash re-yields the last page, which merges away on the
+ # primary key, rather than skipping it.
+ resumable_source_manager.save_state(AwsOrganizationsResumeConfig(next_token=page.next_token, work_key=work_key))
+
+
+def _single_object_rows(
+ client: AwsOrganizationsClient, endpoint_config: AwsOrganizationsEndpointConfig
+) -> Iterator[list[dict[str, Any]]]:
+ body = client.request(endpoint_config.operation, {})
+ obj = body.get(endpoint_config.object_key or "") or {}
+ if isinstance(obj, dict) and obj:
+ yield [normalize_row(endpoint_config, obj)]
+
+
+def _list_rows(
+ client: AwsOrganizationsClient,
+ endpoint_config: AwsOrganizationsEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[AwsOrganizationsResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_token = resume.next_token if resume is not None else None
+ if start_token:
+ logger.debug(f"Resuming from a saved page token. endpoint={endpoint_config.name}")
+
+ payload: dict[str, Any] = {}
+ if endpoint_config.page_size is not None:
+ payload["MaxResults"] = endpoint_config.page_size
+
+ pages = iter_pages(
+ client,
+ endpoint_config.operation,
+ payload,
+ result_key(endpoint_config),
+ logger,
+ start_token=start_token,
+ )
+ yield from _checkpointed_rows(
+ pages,
+ lambda items: [normalize_row(endpoint_config, item) for item in items],
+ resumable_source_manager,
+ )
+
+
+def _policy_rows(
+ client: AwsOrganizationsClient,
+ endpoint_config: AwsOrganizationsEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[AwsOrganizationsResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """One walk per policy type, since `Filter` is required and takes a single type."""
+ filters = list(POLICY_FILTERS)
+ start_token: Optional[str] = None
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ resumed_filter = resume.work_key if resume is not None else None
+ if resumed_filter is not None and resumed_filter in filters:
+ index = filters.index(resumed_filter)
+ if resume is not None and resume.next_token:
+ filters = filters[index:]
+ start_token = resume.next_token
+ else:
+ # The saved walk finished, so pick up at the next policy type.
+ filters = filters[index + 1 :]
+ logger.debug(f"Resuming policies from a saved policy type. policy_type={resumed_filter}")
+
+ for policy_filter in filters:
+ pages = iter_pages(
+ client,
+ endpoint_config.operation,
+ {"Filter": policy_filter, "MaxResults": endpoint_config.page_size},
+ result_key(endpoint_config),
+ logger,
+ start_token=start_token,
+ )
+ try:
+ yield from _checkpointed_rows(
+ pages,
+ lambda items: [normalize_row(endpoint_config, item) for item in items],
+ resumable_source_manager,
+ work_key=policy_filter,
+ )
+ except AwsOrganizationsError as error:
+ if is_policy_type_unavailable(error):
+ logger.debug(f"Skipping unavailable policy type. policy_type={policy_filter}")
+ start_token = None
+ continue
+ raise
+ start_token = None
+
+
+# Named fields instead of a 2/3-tuple return: semgrep's tuple-return-prefer-dataclass
+# devex rule flags tuple[$T, $T] and tuple[$A, $B, $C, ...] return annotations because
+# same-typed or 3+ positional elements are easy to swap or misread at the call site.
[email protected](frozen=True)
+class OrganizationalUnitEntry:
+ """An OU paired with the parent it was found under."""
+
+ item: dict[str, Any]
+ parent_id: str
+ parent_type: str
+
+
[email protected](frozen=True)
+class TaggableResource:
+ """A resource that can carry tags, identified by id and resource type."""
+
+ resource_id: str
+ resource_type: str
+
+
+def _iter_organizational_units(
+ client: AwsOrganizationsClient, logger: FilteringBoundLogger
+) -> Iterator[OrganizationalUnitEntry]:
+ """Every OU in the organization, paired with the parent it was found under.
+
+ Organizations only lists OUs one parent at a time, so the hierarchy is walked breadth-first
+ from the roots.
+ """
+ pending: list[tuple[str, str]] = []
+ for root in iter_items(client, "ListRoots", {"MaxResults": MAX_RESULTS}, "Roots", logger):
+ root_id = root.get("Id")
+ if isinstance(root_id, str) and root_id:
+ pending.append((root_id, "ROOT"))
+
+ seen: set[str] = set()
+ while pending:
+ parent_id, parent_type = pending.pop(0)
+ for item in iter_items(
+ client,
+ "ListOrganizationalUnitsForParent",
+ {"ParentId": parent_id, "MaxResults": MAX_RESULTS},
+ "OrganizationalUnits",
+ logger,
+ ):
+ yield OrganizationalUnitEntry(item=item, parent_id=parent_id, parent_type=parent_type)
+ unit_id = item.get("Id")
+ # `seen` guards against an id coming back twice, which would otherwise walk the
+ # same subtree forever.
+ if isinstance(unit_id, str) and unit_id and unit_id not in seen:
+ seen.add(unit_id)
+ pending.append((unit_id, "ORGANIZATIONAL_UNIT"))
+
+
+def _organizational_unit_rows(
+ client: AwsOrganizationsClient,
+ endpoint_config: AwsOrganizationsEndpointConfig,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ rows: list[dict[str, Any]] = []
+ for entry in _iter_organizational_units(client, logger):
+ row = normalize_row(endpoint_config, entry.item)
+ row["parent_id"] = entry.parent_id
+ row["parent_type"] = entry.parent_type
+ rows.append(row)
+ if len(rows) >= MAX_RESULTS:
+ yield rows
+ rows = []
+ if rows:
+ yield rows
+
+
+def _iter_taggable_resources(
+ client: AwsOrganizationsClient, logger: FilteringBoundLogger
+) -> Iterator[TaggableResource]:
+ """Every resource in the organization that can carry tags."""
+
+ def candidates() -> Iterator[tuple[Any, str]]:
+ for account in iter_items(client, "ListAccounts", {"MaxResults": MAX_RESULTS}, "Accounts", logger):
+ yield account.get("Id"), "ACCOUNT"
+
+ for root in iter_items(client, "ListRoots", {"MaxResults": MAX_RESULTS}, "Roots", logger):
+ yield root.get("Id"), "ROOT"
+
+ for entry in _iter_organizational_units(client, logger):
+ yield entry.item.get("Id"), "ORGANIZATIONAL_UNIT"
+
+ for policy_filter in POLICY_FILTERS:
+ try:
+ for policy in iter_items(
+ client, "ListPolicies", {"Filter": policy_filter, "MaxResults": MAX_RESULTS}, "Policies", logger
+ ):
+ yield policy.get("Id"), "POLICY"
+ except AwsOrganizationsError as error:
+ if is_policy_type_unavailable(error):
+ logger.debug(f"Skipping unavailable policy type. policy_type={policy_filter}")
+ continue
+ raise
+
+ seen: set[str] = set()
+ for resource_id, resource_type in candidates():
+ if isinstance(resource_id, str) and resource_id and resource_id not in seen:
+ seen.add(resource_id)
+ yield TaggableResource(resource_id=resource_id, resource_type=resource_type)
+
+
+def _resource_tag_rows(
+ client: AwsOrganizationsClient,
+ endpoint_config: AwsOrganizationsEndpointConfig,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ for resource in _iter_taggable_resources(client, logger):
+ resource_id, resource_type = resource.resource_id, resource.resource_type
+ rows: list[dict[str, Any]] = []
+ try:
+ for tag in iter_items(
+ client, endpoint_config.operation, {"ResourceId": resource_id}, result_key(endpoint_config), logger
+ ):
+ row = normalize_row(endpoint_config, tag)
+ row["resource_id"] = resource_id
+ row["resource_type"] = resource_type
+ rows.append(row)
+ except AwsOrganizationsError as error:
+ if error.code == "TargetNotFoundException":
+ logger.debug(f"Skipping resource deleted mid-sync. resource_id={resource_id}")
+ continue
+ raise
+ if rows:
+ yield rows
+
+
+def get_rows(
+ aws_access_key_id: str,
+ aws_secret_access_key: str,
+ aws_session_token: Optional[str],
+ endpoint: str,
+ api_version: Optional[str],
+ resumable_source_manager: ResumableSourceManager[AwsOrganizationsResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ endpoint_config = AWS_ORGANIZATIONS_ENDPOINTS[endpoint]
+ client = AwsOrganizationsClient(
+ aws_access_key_id, aws_secret_access_key, aws_session_token, api_version=api_version
+ )
+
+ if endpoint_config.object_key is not None:
+ yield from _single_object_rows(client, endpoint_config)
+ return
+
+ if endpoint == "organizational_units":
+ # The parents are discovered as the walk runs and AWS documents no ordering, so a
+ # partial walk can't be skipped past safely. These restart instead of resuming.
+ yield from _organizational_unit_rows(client, endpoint_config, logger)
+ return
+
+ if endpoint == "resource_tags":
+ yield from _resource_tag_rows(client, endpoint_config, logger)
+ return
+
+ if endpoint == "policies":
+ yield from _policy_rows(client, endpoint_config, resumable_source_manager, logger)
+ else:
+ yield from _list_rows(client, endpoint_config, resumable_source_manager, logger)
+
+ resumable_source_manager.clear_state()
+
+
+def _permission_reason(error: AwsOrganizationsError) -> Optional[str]:
+ if error.code == "AccessDeniedException":
+ match = _IAM_ACTION_PATTERN.search(error.message)
+ missing = f"Missing IAM permission {match.group(0)}." if match else "These credentials can't read this table."
+ return f"{missing} Organizations list operations only work from the management account or a delegated administrator."
+ if error.code == "AWSOrganizationsNotInUseException":
+ return "This AWS account isn't a member of an organization."
+ if error.code in CREDENTIAL_ERROR_CODES:
+ return "AWS rejected the access key. Please check the access key ID and secret access key."
+ return None
+
+
+def endpoint_permission_reason(client: AwsOrganizationsClient, endpoint: str) -> Optional[str]:
+ """Probe the calls a sync of this endpoint issues. `None` when reachable.
+
+ Only a real denial counts as unreachable: throttles, 5xx and network errors leave the
+ endpoint reported as reachable, so a blip can't hide tables from the schema picker.
+ """
+ endpoint_config = AWS_ORGANIZATIONS_ENDPOINTS.get(endpoint)
+ if endpoint_config is None:
+ return None
+
+ try:
+ if endpoint_config.object_key is not None:
+ client.request(endpoint_config.operation, {})
+ elif endpoint == "organizational_units":
+ roots = client.request("ListRoots", {"MaxResults": 1})
+ for root in roots.get("Roots") or []:
+ root_id = root.get("Id") if isinstance(root, dict) else None
+ if isinstance(root_id, str):
+ client.request("ListOrganizationalUnitsForParent", {"ParentId": root_id, "MaxResults": 1})
+ break
+ elif endpoint == "policies":
+ client.request("ListPolicies", {"Filter": POLICY_FILTERS[0], "MaxResults": 1})
+ elif endpoint == "resource_tags":
+ accounts = client.request("ListAccounts", {"MaxResults": 1})
+ for account in accounts.get("Accounts") or []:
+ account_id = account.get("Id") if isinstance(account, dict) else None
+ if isinstance(account_id, str):
+ client.request("ListTagsForResource", {"ResourceId": account_id})
+ break
+ else:
+ client.request(endpoint_config.operation, {"MaxResults": 1})
+ except AwsOrganizationsError as error:
+ return _permission_reason(error)
+ except Exception:
+ return None
+ return None
+
+
+def probe_endpoint_permissions(
+ aws_access_key_id: str,
+ aws_secret_access_key: str,
+ aws_session_token: Optional[str],
+ endpoints: list[str],
+ api_version: Optional[str] = None,
+) -> dict[str, str | None]:
+ client = AwsOrganizationsClient(
+ aws_access_key_id, aws_secret_access_key, aws_session_token, api_version=api_version
+ )
+ return {endpoint: endpoint_permission_reason(client, endpoint) for endpoint in endpoints}
+
+
+def validate_credentials(
+ aws_access_key_id: str,
+ aws_secret_access_key: str,
+ aws_session_token: Optional[str],
+ schema_name: Optional[str] = None,
+ api_version: Optional[str] = None,
+) -> tuple[bool, Optional[str]]:
+ if not aws_access_key_id or not aws_secret_access_key:
+ return False, "AWS access key ID and secret access key are required"
+
+ client = AwsOrganizationsClient(
+ aws_access_key_id, aws_secret_access_key, aws_session_token, api_version=api_version
+ )
+
+ if schema_name is not None and schema_name in AWS_ORGANIZATIONS_ENDPOINTS:
+ reason = endpoint_permission_reason(client, schema_name)
+ return reason is None, reason
+
+ try:
+ # DescribeOrganization is the one operation any account in the organization can call, so
+ # it proves the key is genuine without requiring management-account access.
+ client.request("DescribeOrganization", {})
+ except AwsOrganizationsError as error:
+ if error.code == "AccessDeniedException":
+ # A denied DescribeOrganization still proves the key is genuine; per-table access is
+ # reported in the schema picker instead of blocking source creation.
+ return True, None
+ if error.code == "AWSOrganizationsNotInUseException":
+ return (
+ False,
+ "This AWS account isn't a member of an organization. Connect a key from an account in an AWS organization.",
+ )
+ return False, str(error)
+ except Exception:
+ return False, "Could not reach the AWS Organizations API. Please try again."
+
+ return True, None
+
+
+def aws_organizations_source(
+ aws_access_key_id: str,
+ aws_secret_access_key: str,
+ aws_session_token: Optional[str],
+ endpoint: str,
+ api_version: Optional[str],
+ resumable_source_manager: ResumableSourceManager[AwsOrganizationsResumeConfig],
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ endpoint_config = AWS_ORGANIZATIONS_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ aws_access_key_id=aws_access_key_id,
+ aws_secret_access_key=aws_secret_access_key,
+ aws_session_token=aws_session_token,
+ endpoint=endpoint,
+ api_version=api_version,
+ resumable_source_manager=resumable_source_manager,
+ logger=logger,
+ ),
+ primary_keys=endpoint_config.primary_key,
+ # AWS documents no ordering for these list APIs, and none of them takes a time filter,
+ # so every table is a full refresh with nothing for a watermark to track.
+ sort_mode="desc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/canonical_descriptions.py
new file mode 100644
index 000000000000..c7b362fde307
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/canonical_descriptions.py
@@ -0,0 +1,76 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "accounts": {
+ "description": "Every AWS account in the organization. The dimension table that maps a 12-digit account ID to a human-readable account name.",
+ "docs_url": "https://docs.aws.amazon.com/organizations/latest/APIReference/API_Account.html",
+ "columns": {
+ "id": "The unique identifier (ID) of the account, a 12-digit number.",
+ "arn": "The Amazon Resource Name (ARN) of the account.",
+ "email": "The email address associated with the AWS account, used as the root user sign-in name.",
+ "name": "The friendly name of the account.",
+ "state": "The state of the account in the organization: ACTIVE, SUSPENDED, or PENDING_CLOSURE.",
+ "joined_method": "How the account joined the organization: INVITED for an invited account, CREATED for one created by the organization.",
+ "joined_timestamp": "The date the account became part of the organization.",
+ "paths": "The paths of the account in the organization hierarchy, from the root down to the account.",
+ },
+ },
+ "organization": {
+ "description": "The organization itself, including its management account and which functionality is enabled. One row.",
+ "docs_url": "https://docs.aws.amazon.com/organizations/latest/APIReference/API_Organization.html",
+ "columns": {
+ "id": "The unique identifier (ID) of the organization, starting with 'o-'.",
+ "arn": "The Amazon Resource Name (ARN) of the organization.",
+ "feature_set": "The functionality available to the organization: ALL for all features, or CONSOLIDATED_BILLING for consolidated billing only.",
+ "master_account_arn": "The Amazon Resource Name (ARN) of the management account of the organization.",
+ "master_account_email": "The email address of the management account of the organization.",
+ "master_account_id": "The unique identifier (ID) of the management account of the organization.",
+ },
+ },
+ "organizational_units": {
+ "description": "Organizational units (OUs) in the account hierarchy, each with the root or OU it sits under.",
+ "docs_url": "https://docs.aws.amazon.com/organizations/latest/APIReference/API_OrganizationalUnit.html",
+ "columns": {
+ "id": "The unique identifier (ID) of the organizational unit, starting with 'ou-'.",
+ "arn": "The Amazon Resource Name (ARN) of the organizational unit.",
+ "name": "The friendly name of the organizational unit.",
+ "path": "The path of the organizational unit in the organization hierarchy.",
+ "parent_id": "The ID of the root or organizational unit this unit is a child of.",
+ "parent_type": "Whether the parent is a ROOT or an ORGANIZATIONAL_UNIT.",
+ },
+ },
+ "policies": {
+ "description": "Policies in the organization, across every policy type it supports. Policy contents are not included.",
+ "docs_url": "https://docs.aws.amazon.com/organizations/latest/APIReference/API_PolicySummary.html",
+ "columns": {
+ "id": "The unique identifier (ID) of the policy, starting with 'p-'.",
+ "arn": "The Amazon Resource Name (ARN) of the policy.",
+ "name": "The friendly name of the policy.",
+ "description": "The description of the policy.",
+ "type": "The type of policy, for example SERVICE_CONTROL_POLICY or TAG_POLICY.",
+ "aws_managed": "True when the policy is managed by AWS, which means it can be attached to entities but not edited.",
+ },
+ },
+ "resource_tags": {
+ "description": "Tags attached to accounts, roots, organizational units, and policies. One row per tag.",
+ "docs_url": "https://docs.aws.amazon.com/organizations/latest/APIReference/API_ListTagsForResource.html",
+ "columns": {
+ "resource_id": "The ID of the tagged resource: an account ID, root ID, organizational unit ID, or policy ID.",
+ "resource_type": "The kind of resource the tag is attached to: ACCOUNT, ROOT, ORGANIZATIONAL_UNIT, or POLICY.",
+ "key": "The key of the tag.",
+ "value": "The value of the tag.",
+ },
+ },
+ "roots": {
+ "description": "Roots of the organization, with the policy types currently enabled on each.",
+ "docs_url": "https://docs.aws.amazon.com/organizations/latest/APIReference/API_Root.html",
+ "columns": {
+ "id": "The unique identifier (ID) of the root, starting with 'r-'.",
+ "arn": "The Amazon Resource Name (ARN) of the root.",
+ "name": "The friendly name of the root.",
+ "policy_types": "The policy types currently enabled for the root, each with its type and status.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/settings.py
new file mode 100644
index 000000000000..4f96c9b60935
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/settings.py
@@ -0,0 +1,167 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+# AWS Organizations is a global service: the docs state there is "a single global endpoint for
+# all of the AWS Regions in each partition", so both the host and the SigV4 signing region are
+# fixed rather than user-configurable.
+ORGANIZATIONS_ENDPOINT_URL = "https://organizations.us-east-1.amazonaws.com/"
+SIGNING_REGION = "us-east-1"
+SIGNING_NAME = "organizations"
+
+CONTENT_TYPE = "application/x-amz-json-1.1"
+
+# Service model version. It is carried in the `X-Amz-Target` header of every request
+# (`AWSOrganizationsV20161128.<Operation>`), so this is a real pin rather than a label.
+ORGANIZATIONS_API_VERSION = "2016-11-28"
+TARGET_PREFIXES: dict[str, str] = {ORGANIZATIONS_API_VERSION: "AWSOrganizationsV20161128"}
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+# Every paginated Organizations operation caps `MaxResults` at 20.
+MAX_RESULTS = 20
+
+MAX_RETRY_ATTEMPTS = 6
+RETRY_INITIAL_WAIT_SECONDS = 1.0
+RETRY_MAX_WAIT_SECONDS = 60.0
+
+# Organizations returns throttling and internal errors as HTTP 400 with the code in the body, so
+# the transport's status-code retries never see them. They are retried in-source instead.
+RETRYABLE_ERROR_CODES = frozenset(
+ {
+ "ConcurrentModificationException",
+ "ServiceException",
+ "TooManyRequestsException",
+ }
+)
+
+# Codes that mean the key itself is bad, as opposed to a valid key missing an IAM permission.
+CREDENTIAL_ERROR_CODES = (
+ "UnrecognizedClientException",
+ "InvalidClientTokenId",
+ "SignatureDoesNotMatch",
+ "InvalidSignatureException",
+ "ExpiredTokenException",
+ "ExpiredToken",
+ "IncompleteSignature",
+ "MissingAuthenticationToken",
+)
+
+# `Filter` is required on ListPolicies and takes one policy type per call, so the policies table
+# is one walk per type. Kept in the docs' `Valid Values` order.
+POLICY_FILTERS = (
+ "SERVICE_CONTROL_POLICY",
+ "RESOURCE_CONTROL_POLICY",
+ "TAG_POLICY",
+ "BACKUP_POLICY",
+ "AISERVICES_OPT_OUT_POLICY",
+ "CHATBOT_POLICY",
+ "DECLARATIVE_POLICY_EC2",
+ "SECURITYHUB_POLICY",
+ "INSPECTOR_POLICY",
+ "UPGRADE_ROLLOUT_POLICY",
+ "BEDROCK_POLICY",
+ "S3_POLICY",
+ "NETWORK_SECURITY_DIRECTOR_POLICY",
+)
+
+
+@dataclass(frozen=True)
+class AwsOrganizationsEndpointConfig:
+ name: str
+ # Operation that produces this table's rows. Fan-out tables name their child operation here;
+ # the parents they iterate are listed by the transport.
+ operation: str
+ primary_key: list[str] | None
+ # Response key holding the list of items. `None` for single-object operations.
+ result_key: str | None = None
+ # Top-level response member wrapping a single-object operation's row.
+ object_key: str | None = None
+ # `MaxResults` per request. `None` for operations that don't accept it
+ # (DescribeOrganization, ListTagsForResource).
+ page_size: int | None = None
+ # Flattened columns holding epoch-seconds timestamps, parsed into datetimes.
+ timestamp_columns: tuple[str, ...] = ()
+ # Response members deliberately not stored, with the reason on each entry below.
+ drop_keys: frozenset[str] = field(default_factory=frozenset)
+ # IAM actions a sync of this table calls, for the permission messages.
+ iam_actions: tuple[str, ...] = ()
+
+
+AWS_ORGANIZATIONS_ENDPOINTS: dict[str, AwsOrganizationsEndpointConfig] = {
+ "accounts": AwsOrganizationsEndpointConfig(
+ name="accounts",
+ operation="ListAccounts",
+ primary_key=["id"],
+ result_key="Accounts",
+ page_size=MAX_RESULTS,
+ timestamp_columns=("joined_timestamp",),
+ # AWS retires the `Status` response member on September 9, 2026 and recommends `State`,
+ # which carries the same value.
+ drop_keys=frozenset({"Status"}),
+ iam_actions=("organizations:ListAccounts",),
+ ),
+ "organization": AwsOrganizationsEndpointConfig(
+ name="organization",
+ operation="DescribeOrganization",
+ primary_key=["id"],
+ object_key="Organization",
+ # `AvailablePolicyTypes` is deprecated and only ever reports service control policies.
+ # `roots.policy_types` is the supported way to read which policy types are enabled.
+ drop_keys=frozenset({"AvailablePolicyTypes"}),
+ iam_actions=("organizations:DescribeOrganization",),
+ ),
+ "organizational_units": AwsOrganizationsEndpointConfig(
+ name="organizational_units",
+ operation="ListOrganizationalUnitsForParent",
+ primary_key=["id"],
+ result_key="OrganizationalUnits",
+ page_size=MAX_RESULTS,
+ iam_actions=("organizations:ListRoots", "organizations:ListOrganizationalUnitsForParent"),
+ ),
+ "policies": AwsOrganizationsEndpointConfig(
+ name="policies",
+ operation="ListPolicies",
+ primary_key=["id"],
+ result_key="Policies",
+ page_size=MAX_RESULTS,
+ iam_actions=("organizations:ListPolicies",),
+ ),
+ "resource_tags": AwsOrganizationsEndpointConfig(
+ name="resource_tags",
+ operation="ListTagsForResource",
+ primary_key=["resource_id", "key"],
+ result_key="Tags",
+ iam_actions=(
+ "organizations:ListAccounts",
+ "organizations:ListRoots",
+ "organizations:ListOrganizationalUnitsForParent",
+ "organizations:ListPolicies",
+ "organizations:ListTagsForResource",
+ ),
+ ),
+ "roots": AwsOrganizationsEndpointConfig(
+ name="roots",
+ operation="ListRoots",
+ primary_key=["id"],
+ result_key="Roots",
+ page_size=MAX_RESULTS,
+ iam_actions=("organizations:ListRoots",),
+ ),
+}
+
+ENDPOINTS = tuple(AWS_ORGANIZATIONS_ENDPOINTS.keys())
+
+# Organizations exposes no server-side time filter on any of these operations, so every table
+# is a full refresh. The volumes are small: accounts, OUs and policies are all bounded by
+# per-organization quotas.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
+
+ENDPOINT_DESCRIPTIONS: dict[str, str] = {
+ "accounts": "Every AWS account in the organization, with its name, email, state, and the time it joined.",
+ "organization": "The organization itself: its ID, feature set, and management account. One row per sync.",
+ "organizational_units": "Organizational units in the account hierarchy, each with the parent it sits under.",
+ "policies": "Policies in the organization, one row per policy, across every policy type the organization supports.",
+ "resource_tags": "Tags attached to accounts, roots, organizational units, and policies. One row per tag.",
+ "roots": "Roots of the organization, with the policy types enabled on each.",
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/source.py
index 2cd7246e1e47..34fb9f593ba4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/source.py
@@ -1,32 +1,184 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_organizations.aws_organizations import (
+ AwsOrganizationsResumeConfig,
+ aws_organizations_source,
+ probe_endpoint_permissions,
+ validate_credentials as validate_aws_organizations_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_organizations.settings import (
+ ENDPOINT_DESCRIPTIONS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ ORGANIZATIONS_API_VERSION,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsorganizations import (
AwsOrganizationsSourceConfig,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+_MANAGEMENT_ACCOUNT_HINT = (
+ "Organizations list operations only work from the management account or a delegated administrator."
+)
+
@SourceRegistry.register
-class AwsOrganizationsSource(SimpleSource[AwsOrganizationsSourceConfig]):
+class AwsOrganizationsSource(ResumableSource[AwsOrganizationsSourceConfig, AwsOrganizationsResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog, safe for public docs
+ supported_versions = (ORGANIZATIONS_API_VERSION,)
+ default_version = ORGANIZATIONS_API_VERSION
+ api_docs_url = "https://docs.aws.amazon.com/organizations/latest/APIReference/API_Operations.html"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AWSORGANIZATIONS
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "AWS Organizations request failed: UnrecognizedClientException": "AWS rejected the access key. Please check the access key ID and secret access key, and that the key is still active.",
+ "AWS Organizations request failed: InvalidClientTokenId": "AWS rejected the access key. Please check the access key ID and secret access key, and that the key is still active.",
+ "AWS Organizations request failed: SignatureDoesNotMatch": "AWS rejected the request signature. Please re-enter the secret access key.",
+ "AWS Organizations request failed: InvalidSignatureException": "AWS rejected the request signature. If you are using temporary credentials, the session token has expired.",
+ "AWS Organizations request failed: ExpiredTokenException": "The AWS session token has expired. Please reconnect with fresh credentials.",
+ "AWS Organizations request failed: AccessDeniedException": f"These AWS credentials are missing AWS Organizations read permissions. Grant organizations:DescribeOrganization, organizations:ListAccounts, organizations:ListRoots, organizations:ListOrganizationalUnitsForParent, organizations:ListPolicies and organizations:ListTagsForResource to the IAM user or role. {_MANAGEMENT_ACCOUNT_HINT}",
+ "AWS Organizations request failed: AWSOrganizationsNotInUseException": "This AWS account isn't a member of an organization. Connect a key from an account in an AWS organization.",
+ "AWS access key ID and secret access key are required": "Enter both an AWS access key ID and a secret access key.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.aws_organizations.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AwsOrganizationsSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, descriptions=ENDPOINT_DESCRIPTIONS)
+
+ def validate_credentials(
+ self,
+ config: AwsOrganizationsSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_aws_organizations_credentials(
+ config.aws_access_key_id,
+ config.aws_secret_access_key,
+ config.aws_session_token,
+ schema_name=schema_name,
+ api_version=self.resolve_api_version(api_version),
+ )
+
+ def get_endpoint_permissions(
+ self,
+ config: AwsOrganizationsSourceConfig,
+ team_id: int,
+ endpoints: list[str],
+ api_version: str | None = None,
+ ) -> dict[str, str | None]:
+ return probe_endpoint_permissions(
+ config.aws_access_key_id,
+ config.aws_secret_access_key,
+ config.aws_session_token,
+ endpoints,
+ api_version=self.resolve_api_version(api_version),
+ )
+
+ def get_resumable_source_manager(
+ self, inputs: SourceInputs
+ ) -> ResumableSourceManager[AwsOrganizationsResumeConfig]:
+ return ResumableSourceManager[AwsOrganizationsResumeConfig](inputs, AwsOrganizationsResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AwsOrganizationsSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AwsOrganizationsResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return aws_organizations_source(
+ aws_access_key_id=config.aws_access_key_id,
+ aws_secret_access_key=config.aws_secret_access_key,
+ aws_session_token=config.aws_session_token,
+ endpoint=inputs.schema_name,
+ api_version=self.resolve_api_version(inputs.api_version),
+ resumable_source_manager=resumable_source_manager,
+ logger=inputs.logger,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.AWS_ORGANIZATIONS,
- category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
- label="Amazon Web Services (AWS Organizations)",
+ category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
+ label="AWS Organizations",
+ caption="""Sync your AWS organization structure into the PostHog Data warehouse, so cost and usage data can be read by account name, organizational unit, and tag.
+
+Create an IAM user or role with the `organizations:DescribeOrganization`, `organizations:ListAccounts`, `organizations:ListRoots`, `organizations:ListOrganizationalUnitsForParent`, `organizations:ListPolicies` and `organizations:ListTagsForResource` permissions, then paste its access key ID and secret access key. Add a session token too if you are using temporary credentials.
+
+Use a key from the management account or from a member account that is a delegated administrator. Keys from other member accounts can only read the organization table.
+
+AWS Organizations is a global service, so there is nothing to pick a region for. This source syncs the accounts, organizational units, and policies in the standard AWS partition.""",
iconPath="/static/services/aws_organizations.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/aws-organizations",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["aws", "organizations", "accounts", "organizational units"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="aws_access_key_id",
+ label="AWS access key ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="AKIA...",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="aws_secret_access_key",
+ label="AWS secret access key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="aws_session_token",
+ label="AWS session token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="Only needed for temporary credentials",
+ caption="Only for temporary credentials. Session tokens expire after a few hours, so scheduled syncs will fail once the token expires. Use a permanent access key (starts with AKIA) for recurring imports.",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/tests/test_aws_organizations.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/tests/test_aws_organizations.py
new file mode 100644
index 000000000000..1cace85ca580
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/tests/test_aws_organizations.py
@@ -0,0 +1,590 @@
+import json
+import datetime as dt
+from collections.abc import Callable
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+import requests
+import structlog
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_organizations import aws_organizations
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_organizations.aws_organizations import (
+ AwsOrganizationsClient,
+ AwsOrganizationsError,
+ AwsOrganizationsResumeConfig,
+ AwsOrganizationsRetryableError,
+ error_for_response,
+ get_rows,
+ normalize_row,
+ probe_endpoint_permissions,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_organizations.settings import (
+ AWS_ORGANIZATIONS_ENDPOINTS,
+ MAX_RESULTS,
+ ORGANIZATIONS_ENDPOINT_URL,
+ POLICY_FILTERS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+LOGGER = structlog.get_logger()
+
+ACCOUNTS = AWS_ORGANIZATIONS_ENDPOINTS["accounts"]
+ORGANIZATION = AWS_ORGANIZATIONS_ENDPOINTS["organization"]
+ORGANIZATIONAL_UNITS = AWS_ORGANIZATIONS_ENDPOINTS["organizational_units"]
+POLICIES = AWS_ORGANIZATIONS_ENDPOINTS["policies"]
+RESOURCE_TAGS = AWS_ORGANIZATIONS_ENDPOINTS["resource_tags"]
+ROOTS = AWS_ORGANIZATIONS_ENDPOINTS["roots"]
+
+JAN_2025 = 1735689600.0 # 2025-01-01T00:00:00Z
+
+Responder = Callable[[str, dict[str, Any]], dict[str, Any]]
+
+
+class FakeResumeManager(ResumableSourceManager[AwsOrganizationsResumeConfig]):
+ def __init__(self, state: Optional[AwsOrganizationsResumeConfig] = None) -> None:
+ self.state = state
+ self.saved: list[AwsOrganizationsResumeConfig] = []
+ self.cleared = False
+
+ def can_resume(self) -> bool:
+ return self.state is not None
+
+ def load_state(self) -> Optional[AwsOrganizationsResumeConfig]:
+ return self.state
+
+ def save_state(self, data: AwsOrganizationsResumeConfig) -> None:
+ self.saved.append(data)
+
+ def clear_state(self) -> None:
+ self.cleared = True
+
+
+def make_response(
+ status_code: int, payload: Optional[dict[str, Any]] = None, headers: Optional[dict[str, str]] = None
+) -> requests.Response:
+ response = requests.Response()
+ response.status_code = status_code
+ response.headers.update(headers or {})
+ response._content = json.dumps(payload if payload is not None else {}).encode()
+ return response
+
+
+def page(key: str, items: list[dict[str, Any]], next_token: Optional[str] = None) -> dict[str, Any]:
+ body: dict[str, Any] = {key: items}
+ if next_token is not None:
+ body["NextToken"] = next_token
+ return body
+
+
+def install_api(responder: Responder) -> list[tuple[str, dict[str, Any]]]:
+ calls: list[tuple[str, dict[str, Any]]] = []
+
+ def request(self: AwsOrganizationsClient, operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ calls.append((operation, dict(payload)))
+ return responder(operation, dict(payload))
+
+ patcher = mock.patch.object(AwsOrganizationsClient, "request", request)
+ patcher.start()
+ return calls
+
+
[email protected](autouse=True)
+def stop_patches():
+ yield
+ mock.patch.stopall()
+
+
+def run_endpoint(
+ endpoint: str, responder: Responder, manager: Optional[FakeResumeManager] = None
+) -> tuple[list[list[dict[str, Any]]], list[tuple[str, dict[str, Any]]], FakeResumeManager]:
+ calls = install_api(responder)
+ resume_manager = manager if manager is not None else FakeResumeManager()
+ batches = list(
+ get_rows(
+ aws_access_key_id="AKIAEXAMPLE",
+ aws_secret_access_key="secret",
+ aws_session_token=None,
+ endpoint=endpoint,
+ api_version=None,
+ resumable_source_manager=resume_manager,
+ logger=LOGGER,
+ )
+ )
+ return batches, calls, resume_manager
+
+
+def flatten(batches: list[list[dict[str, Any]]]) -> list[dict[str, Any]]:
+ return [row for batch in batches for row in batch]
+
+
+class TestNormalizeRow:
+ def test_account_row_parses_the_epoch_timestamp_and_drops_the_retiring_status_member(self) -> None:
+ row = normalize_row(
+ ACCOUNTS,
+ {
+ "Id": "111111111111",
+ "Arn": "arn:aws:organizations::111111111111:account/o-example/111111111111",
+ "Email": "[email protected]",
+ "Name": "Production Account",
+ "JoinedMethod": "INVITED",
+ "JoinedTimestamp": JAN_2025,
+ "State": "ACTIVE",
+ "Status": "ACTIVE",
+ "Paths": ["o-example/r-exam/111111111111/"],
+ },
+ )
+
+ assert row == {
+ "id": "111111111111",
+ "arn": "arn:aws:organizations::111111111111:account/o-example/111111111111",
+ "email": "[email protected]",
+ "name": "Production Account",
+ "joined_method": "INVITED",
+ "joined_timestamp": dt.datetime(2025, 1, 1, tzinfo=dt.UTC),
+ "state": "ACTIVE",
+ "paths": ["o-example/r-exam/111111111111/"],
+ }
+
+ def test_organization_row_drops_the_deprecated_available_policy_types_member(self) -> None:
+ row = normalize_row(
+ ORGANIZATION,
+ {
+ "Id": "o-example",
+ "Arn": "arn:aws:organizations::111111111111:organization/o-example",
+ "FeatureSet": "ALL",
+ "MasterAccountArn": "arn:aws:organizations::111111111111:account/o-example/111111111111",
+ "MasterAccountEmail": "[email protected]",
+ "MasterAccountId": "111111111111",
+ "AvailablePolicyTypes": [{"Type": "SERVICE_CONTROL_POLICY", "Status": "ENABLED"}],
+ },
+ )
+
+ assert row == {
+ "id": "o-example",
+ "arn": "arn:aws:organizations::111111111111:organization/o-example",
+ "feature_set": "ALL",
+ "master_account_arn": "arn:aws:organizations::111111111111:account/o-example/111111111111",
+ "master_account_email": "[email protected]",
+ "master_account_id": "111111111111",
+ }
+
+ def test_root_row_keeps_the_policy_type_list_whole(self) -> None:
+ row = normalize_row(
+ ROOTS,
+ {
+ "Id": "r-exam",
+ "Name": "Root",
+ "PolicyTypes": [{"Type": "TAG_POLICY", "Status": "ENABLED"}],
+ },
+ )
+
+ assert row == {
+ "id": "r-exam",
+ "name": "Root",
+ "policy_types": [{"Type": "TAG_POLICY", "Status": "ENABLED"}],
+ }
+
+
+class TestSignedRequest:
+ def test_request_is_signed_for_the_global_endpoint_and_names_the_operation(self) -> None:
+ sent: list[dict[str, Any]] = []
+
+ class FakeSession:
+ def post(
+ self,
+ url: str,
+ data: Optional[bytes] = None,
+ headers: Optional[dict[str, str]] = None,
+ timeout: Optional[int] = None,
+ ) -> requests.Response:
+ sent.append({"url": url, "data": data, "headers": headers or {}})
+ return make_response(200, {"Organization": {"Id": "o-example"}})
+
+ with mock.patch.object(aws_organizations, "make_tracked_session", return_value=FakeSession()):
+ client = AwsOrganizationsClient("AKIAEXAMPLE", "secret", None)
+ body = client.send("DescribeOrganization", {})
+
+ assert body == {"Organization": {"Id": "o-example"}}
+ assert sent[0]["url"] == ORGANIZATIONS_ENDPOINT_URL
+ assert sent[0]["headers"]["X-Amz-Target"] == "AWSOrganizationsV20161128.DescribeOrganization"
+ assert sent[0]["headers"]["Content-Type"] == "application/x-amz-json-1.1"
+ # Organizations is global: a signature scoped anywhere but us-east-1/organizations is
+ # rejected as SignatureDoesNotMatch, which reads to the user as a bad key.
+ assert "/us-east-1/organizations/aws4_request" in sent[0]["headers"]["Authorization"]
+
+ @pytest.mark.parametrize(
+ "status_code,code,retryable",
+ [
+ (400, "AccessDeniedException", False),
+ (400, "AWSOrganizationsNotInUseException", False),
+ (400, "UnrecognizedClientException", False),
+ (400, "TooManyRequestsException", True),
+ (400, "ConcurrentModificationException", True),
+ (500, "ServiceException", True),
+ ],
+ )
+ def test_error_responses_carry_the_code_and_only_transient_ones_are_retryable(
+ self, status_code: int, code: str, retryable: bool
+ ) -> None:
+ response = make_response(
+ status_code, {"__type": f"com.amazonaws.organizations#{code}", "message": "denied for organizations:Foo"}
+ )
+
+ error = error_for_response(response)
+
+ assert error.code == code
+ assert isinstance(error, AwsOrganizationsRetryableError) is retryable
+ assert str(error) == f"AWS Organizations request failed: {code} - denied for organizations:Foo"
+
+ def test_error_type_header_wins_over_the_body(self) -> None:
+ response = make_response(
+ 400,
+ {"message": "nope"},
+ headers={"x-amzn-ErrorType": "AccessDeniedException:http://internal.amazon.com/coral/"},
+ )
+
+ assert error_for_response(response).code == "AccessDeniedException"
+
+
+class TestPagination:
+ def test_walk_continues_past_an_empty_page_and_stops_only_on_a_null_token(self) -> None:
+ pages = [
+ page("Accounts", [{"Id": "111111111111"}], next_token="one"),
+ # Documented behavior: a list operation can return an empty page while more
+ # results are still available.
+ page("Accounts", [], next_token="two"),
+ page("Accounts", [{"Id": "222222222222"}]),
+ ]
+
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ token = payload.get("NextToken")
+ index = {None: 0, "one": 1, "two": 2}[token]
+ return pages[index]
+
+ batches, calls, _ = run_endpoint("accounts", responder)
+
+ assert [row["id"] for row in flatten(batches)] == ["111111111111", "222222222222"]
+ assert [call[1].get("NextToken") for call in calls] == [None, "one", "two"]
+
+ @pytest.mark.parametrize(
+ "endpoint,operation,expects_max_results",
+ [
+ ("accounts", "ListAccounts", True),
+ ("roots", "ListRoots", True),
+ ("resource_tags", "ListTagsForResource", False),
+ ],
+ )
+ def test_max_results_is_sent_only_where_the_operation_accepts_it(
+ self, endpoint: str, operation: str, expects_max_results: bool
+ ) -> None:
+ def responder(called_operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ if called_operation == "ListAccounts":
+ return page("Accounts", [{"Id": "111111111111"}])
+ if called_operation == "ListRoots":
+ return page("Roots", [{"Id": "r-exam"}])
+ if called_operation == "ListOrganizationalUnitsForParent":
+ return page("OrganizationalUnits", [])
+ if called_operation == "ListPolicies":
+ return page("Policies", [])
+ return page("Tags", [{"Key": "team", "Value": "growth"}])
+
+ _, calls, _ = run_endpoint(endpoint, responder)
+
+ payloads = [payload for called_operation, payload in calls if called_operation == operation]
+ assert payloads
+ for payload in payloads:
+ assert ("MaxResults" in payload) is expects_max_results
+ if expects_max_results:
+ assert payload["MaxResults"] == MAX_RESULTS
+
+ def test_single_object_endpoint_issues_one_call_and_one_row(self) -> None:
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ return {"Organization": {"Id": "o-example", "FeatureSet": "ALL"}}
+
+ batches, calls, _ = run_endpoint("organization", responder)
+
+ assert calls == [("DescribeOrganization", {})]
+ assert flatten(batches) == [{"id": "o-example", "feature_set": "ALL"}]
+
+
+class TestPolicies:
+ def test_one_walk_per_policy_type(self) -> None:
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ return page("Policies", [{"Id": f"p-{payload['Filter'].lower()}", "Type": payload["Filter"]}])
+
+ batches, calls, _ = run_endpoint("policies", responder)
+
+ assert [payload["Filter"] for _, payload in calls] == list(POLICY_FILTERS)
+ assert len(flatten(batches)) == len(POLICY_FILTERS)
+
+ @pytest.mark.parametrize(
+ "code,message",
+ [
+ ("UnsupportedAPIEndpointException", "This action isn't available in the current AWS Region."),
+ ("InvalidInputException", "INVALID_ENUM_POLICY_TYPE: You specified an invalid policy type string."),
+ ],
+ )
+ def test_a_policy_type_this_organization_does_not_offer_is_skipped(self, code: str, message: str) -> None:
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ if payload["Filter"] == "SERVICE_CONTROL_POLICY":
+ raise AwsOrganizationsError(code, message)
+ return page("Policies", [{"Id": "p-example", "Type": payload["Filter"]}])
+
+ batches, _, _ = run_endpoint("policies", responder)
+
+ assert len(flatten(batches)) == len(POLICY_FILTERS) - 1
+
+ def test_a_denied_policy_type_fails_the_sync(self) -> None:
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ raise AwsOrganizationsError("AccessDeniedException", "not authorized for organizations:ListPolicies")
+
+ with pytest.raises(AwsOrganizationsError, match="AccessDeniedException"):
+ run_endpoint("policies", responder)
+
+
+class TestOrganizationalUnits:
+ def test_nested_units_are_discovered_and_stamped_with_their_parent(self) -> None:
+ children = {
+ "r-exam": [{"Id": "ou-exam-aaaaaaaa", "Name": "Engineering"}],
+ "ou-exam-aaaaaaaa": [{"Id": "ou-exam-bbbbbbbb", "Name": "Platform"}],
+ "ou-exam-bbbbbbbb": [],
+ }
+
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ if operation == "ListRoots":
+ return page("Roots", [{"Id": "r-exam"}])
+ return page("OrganizationalUnits", children[payload["ParentId"]])
+
+ batches, _, _ = run_endpoint("organizational_units", responder)
+
+ assert [(row["id"], row["parent_id"], row["parent_type"]) for row in flatten(batches)] == [
+ ("ou-exam-aaaaaaaa", "r-exam", "ROOT"),
+ ("ou-exam-bbbbbbbb", "ou-exam-aaaaaaaa", "ORGANIZATIONAL_UNIT"),
+ ]
+
+ def test_a_unit_returned_twice_does_not_walk_the_same_subtree_forever(self) -> None:
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ if operation == "ListRoots":
+ return page("Roots", [{"Id": "r-exam"}])
+ if payload["ParentId"] == "r-exam":
+ return page("OrganizationalUnits", [{"Id": "ou-exam-aaaaaaaa"}, {"Id": "ou-exam-aaaaaaaa"}])
+ return page("OrganizationalUnits", [])
+
+ batches, calls, _ = run_endpoint("organizational_units", responder)
+
+ assert len(flatten(batches)) == 2
+ assert [payload["ParentId"] for operation, payload in calls if operation.startswith("ListOrg")] == [
+ "r-exam",
+ "ou-exam-aaaaaaaa",
+ ]
+
+
+class TestResourceTags:
+ def _responder(self, missing: Optional[str] = None) -> Responder:
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ if operation == "ListAccounts":
+ return page("Accounts", [{"Id": "111111111111"}])
+ if operation == "ListRoots":
+ return page("Roots", [{"Id": "r-exam"}])
+ if operation == "ListOrganizationalUnitsForParent":
+ if payload["ParentId"] == "r-exam":
+ return page("OrganizationalUnits", [{"Id": "ou-exam-aaaaaaaa"}])
+ return page("OrganizationalUnits", [])
+ if operation == "ListPolicies":
+ if payload["Filter"] == "SERVICE_CONTROL_POLICY":
+ return page("Policies", [{"Id": "p-example"}])
+ return page("Policies", [])
+ if payload["ResourceId"] == missing:
+ raise AwsOrganizationsError("TargetNotFoundException", "We can't find that target.")
+ return page("Tags", [{"Key": "team", "Value": payload["ResourceId"]}])
+
+ return responder
+
+ def test_tags_are_collected_from_every_taggable_resource_type(self) -> None:
+ batches, _, _ = run_endpoint("resource_tags", self._responder())
+
+ assert [(row["resource_id"], row["resource_type"], row["key"], row["value"]) for row in flatten(batches)] == [
+ ("111111111111", "ACCOUNT", "team", "111111111111"),
+ ("r-exam", "ROOT", "team", "r-exam"),
+ ("ou-exam-aaaaaaaa", "ORGANIZATIONAL_UNIT", "team", "ou-exam-aaaaaaaa"),
+ ("p-example", "POLICY", "team", "p-example"),
+ ]
+
+ def test_a_resource_deleted_mid_sync_is_skipped(self) -> None:
+ batches, _, _ = run_endpoint("resource_tags", self._responder(missing="r-exam"))
+
+ assert [row["resource_id"] for row in flatten(batches)] == [
+ "111111111111",
+ "ou-exam-aaaaaaaa",
+ "p-example",
+ ]
+
+ def test_primary_key_is_unique_per_resource_and_tag_key(self) -> None:
+ rows = flatten(run_endpoint("resource_tags", self._responder())[0])
+ keys = [tuple(row[column] for column in RESOURCE_TAGS.primary_key or []) for row in rows]
+
+ assert len(set(keys)) == len(keys)
+
+
+class TestResume:
+ def test_a_saved_token_starts_the_walk_where_the_last_attempt_stopped(self) -> None:
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ assert payload["NextToken"] == "page-two"
+ return page("Accounts", [{"Id": "222222222222"}])
+
+ manager = FakeResumeManager(AwsOrganizationsResumeConfig(next_token="page-two"))
+ batches, calls, _ = run_endpoint("accounts", responder, manager=manager)
+
+ assert len(calls) == 1
+ assert [row["id"] for row in flatten(batches)] == ["222222222222"]
+
+ def test_state_is_saved_after_every_page_and_cleared_once_the_walk_completes(self) -> None:
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ if payload.get("NextToken") is None:
+ return page("Accounts", [{"Id": "111111111111"}], next_token="page-two")
+ return page("Accounts", [{"Id": "222222222222"}])
+
+ _, _, manager = run_endpoint("accounts", responder)
+
+ assert [state.next_token for state in manager.saved] == ["page-two", None]
+ assert manager.cleared is True
+
+ def test_an_expired_saved_token_restarts_the_walk_instead_of_failing(self) -> None:
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ if payload.get("NextToken") == "stale":
+ raise AwsOrganizationsError(
+ "InvalidInputException", "INVALID_PAGINATION_TOKEN: Get the value for the NextToken parameter"
+ )
+ return page("Accounts", [{"Id": "111111111111"}])
+
+ manager = FakeResumeManager(AwsOrganizationsResumeConfig(next_token="stale"))
+ batches, calls, _ = run_endpoint("accounts", responder, manager=manager)
+
+ assert [payload.get("NextToken") for _, payload in calls] == ["stale", None]
+ assert [row["id"] for row in flatten(batches)] == ["111111111111"]
+
+ def test_policies_resume_picks_up_at_the_policy_type_after_the_completed_one(self) -> None:
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ return page("Policies", [{"Id": f"p-{payload['Filter'].lower()}"}])
+
+ manager = FakeResumeManager(AwsOrganizationsResumeConfig(work_key=POLICY_FILTERS[0]))
+ _, calls, _ = run_endpoint("policies", responder, manager=manager)
+
+ assert [payload["Filter"] for _, payload in calls] == list(POLICY_FILTERS[1:])
+
+ def test_policies_resume_continues_a_half_walked_policy_type(self) -> None:
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ return page("Policies", [{"Id": "p-example"}])
+
+ manager = FakeResumeManager(AwsOrganizationsResumeConfig(next_token="page-two", work_key=POLICY_FILTERS[1]))
+ _, calls, _ = run_endpoint("policies", responder, manager=manager)
+
+ assert calls[0] == (
+ "ListPolicies",
+ {"Filter": POLICY_FILTERS[1], "MaxResults": MAX_RESULTS, "NextToken": "page-two"},
+ )
+ assert [payload["Filter"] for _, payload in calls] == list(POLICY_FILTERS[1:])
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "code,expected_valid",
+ [
+ # A denied DescribeOrganization still proves the key is genuine.
+ ("AccessDeniedException", True),
+ ("AWSOrganizationsNotInUseException", False),
+ ("UnrecognizedClientException", False),
+ ("SignatureDoesNotMatch", False),
+ ],
+ )
+ def test_only_a_bad_key_or_a_missing_organization_blocks_source_creation(
+ self, code: str, expected_valid: bool
+ ) -> None:
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ raise AwsOrganizationsError(code, "message")
+
+ install_api(responder)
+ valid, reason = validate_credentials("AKIAEXAMPLE", "secret", None)
+
+ assert valid is expected_valid
+ assert (reason is None) is expected_valid
+
+ def test_a_reachable_organization_validates(self) -> None:
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ assert operation == "DescribeOrganization"
+ return {"Organization": {"Id": "o-example"}}
+
+ install_api(responder)
+
+ assert validate_credentials("AKIAEXAMPLE", "secret", None) == (True, None)
+
+ @pytest.mark.parametrize(
+ "access_key_id,secret_access_key",
+ [("", "secret"), ("AKIAEXAMPLE", ""), ("", "")],
+ )
+ def test_missing_credentials_are_rejected_without_a_request(
+ self, access_key_id: str, secret_access_key: str
+ ) -> None:
+ calls = install_api(lambda operation, payload: {})
+
+ valid, reason = validate_credentials(access_key_id, secret_access_key, None)
+
+ assert valid is False
+ assert reason == "AWS access key ID and secret access key are required"
+ assert calls == []
+
+ def test_a_schema_name_probes_that_table_rather_than_the_organization(self) -> None:
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ if operation == "ListAccounts":
+ raise AwsOrganizationsError(
+ "AccessDeniedException", "not authorized to perform organizations:ListAccounts"
+ )
+ return page("Accounts", [])
+
+ install_api(responder)
+ valid, reason = validate_credentials("AKIAEXAMPLE", "secret", None, schema_name="accounts")
+
+ assert valid is False
+ assert reason is not None
+ assert "organizations:ListAccounts" in reason
+
+
+class TestProbeEndpointPermissions:
+ def test_a_denied_table_names_the_missing_action_and_the_rest_stay_reachable(self) -> None:
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ if operation == "ListPolicies":
+ raise AwsOrganizationsError(
+ "AccessDeniedException", "not authorized to perform organizations:ListPolicies"
+ )
+ if operation == "ListAccounts":
+ return page("Accounts", [{"Id": "111111111111"}])
+ if operation == "ListRoots":
+ return page("Roots", [{"Id": "r-exam"}])
+ if operation == "ListTagsForResource":
+ return page("Tags", [])
+ if operation == "ListOrganizationalUnitsForParent":
+ return page("OrganizationalUnits", [])
+ return {"Organization": {"Id": "o-example"}}
+
+ install_api(responder)
+ reasons = probe_endpoint_permissions(
+ "AKIAEXAMPLE", "secret", None, ["accounts", "organization", "organizational_units", "policies"]
+ )
+
+ assert reasons["accounts"] is None
+ assert reasons["organization"] is None
+ assert reasons["organizational_units"] is None
+ assert reasons["policies"] is not None
+ assert "organizations:ListPolicies" in reasons["policies"]
+
+ @pytest.mark.parametrize("error", [AwsOrganizationsRetryableError("TooManyRequestsException", "slow down")])
+ def test_a_transient_failure_is_not_reported_as_a_permission_problem(self, error: Exception) -> None:
+ def responder(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ raise error
+
+ install_api(responder)
+
+ assert probe_endpoint_permissions("AKIAEXAMPLE", "secret", None, ["accounts"]) == {"accounts": None}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/tests/test_aws_organizations_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/tests/test_aws_organizations_source.py
new file mode 100644
index 000000000000..0bdfe5a430bc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_organizations/tests/test_aws_organizations_source.py
@@ -0,0 +1,182 @@
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+from unittest import mock
+
+import structlog
+
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_organizations import (
+ aws_organizations as transport_module,
+ source as source_module,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_organizations.aws_organizations import (
+ AwsOrganizationsResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_organizations.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_organizations.settings import (
+ AWS_ORGANIZATIONS_ENDPOINTS,
+ ENDPOINT_DESCRIPTIONS,
+ ENDPOINTS,
+ ORGANIZATIONS_API_VERSION,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_organizations.source import (
+ AwsOrganizationsSource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsorganizations import (
+ AwsOrganizationsSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def make_inputs(schema_name: str) -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-id",
+ source_id="source-id",
+ team_id=1,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="job-id",
+ logger=structlog.get_logger(),
+ reset_pipeline=False,
+ )
+
+
+class TestAwsOrganizationsSource:
+ def setup_method(self) -> None:
+ self.source = AwsOrganizationsSource()
+ self.config = AwsOrganizationsSourceConfig(
+ aws_access_key_id="AKIAEXAMPLE",
+ aws_secret_access_key="secret",
+ aws_session_token=None,
+ )
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.AWSORGANIZATIONS
+
+ def test_source_is_released_and_labelled_alpha(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING
+ assert config.label == "AWS Organizations"
+ assert config.iconPath == "/static/services/aws_organizations.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/aws-organizations"
+
+ def test_the_api_version_pins_the_service_model_the_requests_carry(self) -> None:
+ assert self.source.supported_versions == (ORGANIZATIONS_API_VERSION,)
+ assert self.source.default_version == ORGANIZATIONS_API_VERSION
+ assert transport_module.target_prefix(self.source.default_version) == "AWSOrganizationsV20161128"
+ assert self.source.api_docs_url.startswith("https://")
+
+ @pytest.mark.parametrize(
+ "field_name,required,secret",
+ [
+ ("aws_access_key_id", True, False),
+ ("aws_secret_access_key", True, True),
+ ("aws_session_token", False, True),
+ ],
+ )
+ def test_credential_fields(self, field_name: str, required: bool, secret: bool) -> None:
+ fields = {field.name: field for field in self.source.get_source_config.fields}
+
+ field = fields[field_name]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.required is required
+ assert field.secret is secret
+
+ def test_no_region_field_is_asked_for(self) -> None:
+ # Organizations has one global endpoint, so a region would only mislead: a signature
+ # scoped to anything but us-east-1 fails as though the key were wrong.
+ assert [field.name for field in self.source.get_source_config.fields] == [
+ "aws_access_key_id",
+ "aws_secret_access_key",
+ "aws_session_token",
+ ]
+
+ def test_schemas_cover_every_endpoint_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=1)
+
+ assert [schema.name for schema in schemas] == list(ENDPOINTS)
+ assert all(schema.supports_incremental is False for schema in schemas)
+ assert all(schema.description == ENDPOINT_DESCRIPTIONS[schema.name] for schema in schemas)
+
+ def test_schemas_can_be_filtered_to_the_requested_tables(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=1, names=["accounts"])
+
+ assert [schema.name for schema in schemas] == ["accounts"]
+
+ def test_table_catalog_is_listable_without_credentials_for_the_public_docs(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_canonical_descriptions_are_keyed_by_the_schema_names(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+
+ assert descriptions is CANONICAL_DESCRIPTIONS
+ assert set(descriptions.keys()) == set(ENDPOINTS)
+ for endpoint in ENDPOINTS:
+ assert descriptions[endpoint].get("columns")
+
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_source_for_pipeline_names_the_table_and_uses_the_endpoint_primary_key(self, endpoint: str) -> None:
+ inputs = make_inputs(endpoint)
+
+ response = self.source.source_for_pipeline(
+ self.config, self.source.get_resumable_source_manager(inputs), inputs
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == AWS_ORGANIZATIONS_ENDPOINTS[endpoint].primary_key
+
+ def test_source_for_pipeline_passes_the_credentials_and_resolved_version_to_the_transport(self) -> None:
+ inputs = make_inputs("accounts")
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ with mock.patch.object(transport_module, "get_rows", return_value=iter([])) as get_rows:
+ response = self.source.source_for_pipeline(self.config, manager, inputs)
+ cast(Iterable[Any], response.items())
+
+ assert get_rows.call_args.kwargs["aws_access_key_id"] == "AKIAEXAMPLE"
+ assert get_rows.call_args.kwargs["aws_secret_access_key"] == "secret"
+ assert get_rows.call_args.kwargs["endpoint"] == "accounts"
+ assert get_rows.call_args.kwargs["api_version"] == ORGANIZATIONS_API_VERSION
+
+ def test_resumable_manager_is_bound_to_the_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(make_inputs("accounts"))
+
+ assert manager._data_class is AwsOrganizationsResumeConfig
+
+ def test_validate_credentials_delegates_to_the_transport(self) -> None:
+ with mock.patch.object(
+ source_module, "validate_aws_organizations_credentials", return_value=(True, None)
+ ) as validate:
+ assert self.source.validate_credentials(self.config, team_id=1) == (True, None)
+
+ assert validate.call_args.args == ("AKIAEXAMPLE", "secret", None)
+ assert validate.call_args.kwargs == {"schema_name": None, "api_version": ORGANIZATIONS_API_VERSION}
+
+ def test_endpoint_permissions_are_probed_per_table(self) -> None:
+ with mock.patch.object(source_module, "probe_endpoint_permissions", return_value={"accounts": None}) as probe:
+ assert self.source.get_endpoint_permissions(self.config, team_id=1, endpoints=["accounts"]) == {
+ "accounts": None
+ }
+
+ assert probe.call_args.args == ("AKIAEXAMPLE", "secret", None, ["accounts"])
+ assert probe.call_args.kwargs == {"api_version": ORGANIZATIONS_API_VERSION}
+
+ def test_credential_and_permission_failures_are_not_retried(self) -> None:
+ errors = self.source.get_non_retryable_errors()
+
+ assert "AWS Organizations request failed: AccessDeniedException" in errors
+ assert "AWS Organizations request failed: UnrecognizedClientException" in errors
+ assert all(message for message in errors.values())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsorganizations.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsorganizations.py
index 8b51efaa9633..5a13bf2af5ba 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsorganizations.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsorganizations.py
@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class AwsOrganizationsSourceConfig(config.Config):
- pass
+ aws_access_key_id: str
+ aws_secret_access_key: str
+ aws_session_token: str | None = None