Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(org): CreateAccount and CreatePolicy (#1810)

Nahuel Nuceraee67979ca9ed
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a7d6fc95..c7f17688 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to MiniStack will be documented here.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
Versioning follows [Semantic Versioning](https://semver.org/).
+## [Unreleased]
+
+### Added
+
+- **Organizations — member accounts, service control policies and attachments** — `CreateAccount`, `DescribeCreateAccountStatus`, `MoveAccount`, `CloseAccount`, `CreatePolicy`, `DescribePolicy`, `UpdatePolicy`, `DeletePolicy`, `ListPolicies`, `AttachPolicy`, `DetachPolicy`, `ListPoliciesForTarget`, `ListTargetsForPolicy`, `EnablePolicyType` and `DisablePolicyType`, so `aws_organizations_account`, `aws_organizations_policy` and `aws_organizations_policy_attachment` apply. `CreateAccount` answers with a `CreateAccountStatus` whose id the provider reads back through `DescribeCreateAccountStatus`, as on AWS. A root carries `SERVICE_CONTROL_POLICY` enabled and the AWS-managed `p-FullAWSAccess`, attaching a policy whose type the root has disabled is `PolicyTypeNotEnabledException`, and deleting an attached policy is `PolicyInUseException`. Requested by @rv0lt.
+
## [1.5.15] — 2026-09-22
### Added
diff --git a/README.md b/README.md
index 8ea7276a..adf05a64 100644
--- a/README.md
+++ b/README.md
@@ -613,7 +613,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i
| **EventBridge Scheduler** | CreateSchedule, GetSchedule, UpdateSchedule, DeleteSchedule, ListSchedules, CreateScheduleGroup, GetScheduleGroup, DeleteScheduleGroup, ListScheduleGroups, TagResource, UntagResource, ListTagsForResource | 12 actions; schedules **fire their targets** — a background sweep invokes each enabled schedule's target (Lambda, SQS, SNS, Step Functions) when due, honoring `State`, `StartDate`/`EndDate`, and `ActionAfterCompletion: DELETE`; schedule groups with cascading deletes; `rate()`, `cron()`, `at()` expressions; group/prefix/state filters on list; default group auto-created; CFN `AWS::Scheduler::Schedule` and `AWS::Scheduler::ScheduleGroup` supported |
| **EKS** | CreateCluster, DescribeCluster, ListClusters, DeleteCluster, CreateNodegroup, DescribeNodegroup, ListNodegroups, DeleteNodegroup, CreateAddon, DescribeAddon, ListAddons, UpdateAddon, DeleteAddon, AssociateEncryptionConfig, CreateAccessEntry, DescribeAccessEntry, ListAccessEntries, UpdateAccessEntry, DeleteAccessEntry, AssociateAccessPolicy, DisassociateAccessPolicy, ListAssociatedAccessPolicies, AssociateIdentityProviderConfig, DescribeIdentityProviderConfig, DisassociateIdentityProviderConfig, ListIdentityProviderConfigs, CreatePodIdentityAssociation, DescribePodIdentityAssociation, ListPodIdentityAssociations, UpdatePodIdentityAssociation, DeletePodIdentityAssociation, TagResource, UntagResource, ListTagsForResource | `CreateCluster` spawns a real **k3s** container (75 MB) with a full Kubernetes API server; `kubectl`, Helm, and any K8s tooling work out of the box; cascading delete removes nodegroups and k3s container; addon CRUD (e.g. `vpc-cni`, `coredns`, `kube-proxy`, `aws-ebs-csi-driver`) at `/clusters/{name}/addons` flips status to `ACTIVE` on create / update; `AssociateEncryptionConfig` at `/clusters/{name}/encryption-config/associate` records KMS encryption config (rejects re-association, AWS-shape `update` envelope); **Access Entries** (modern post-1.29 IAM bindings — replaces aws-auth ConfigMap) at `/clusters/{name}/access-entries[/{principalArn}[/access-policies[/{policyArn}]]]` for Crossplane / Terraform `aws_eks_access_entry` + `aws_eks_access_policy_association`; OIDC discovery + JWKS served at the cluster's `identity.oidc.issuer` URL so Terraform's `aws_iam_openid_connect_provider` (IRSA) works against ministack; **OIDC Identity Provider Config** (`AssociateIdentityProviderConfig` / `DescribeIdentityProviderConfig` / `DisassociateIdentityProviderConfig` / `ListIdentityProviderConfigs`) at `/clusters/{name}/identity-provider-configs[/{verb}]` — one OIDC IdP per cluster, issuer + clientId + claims forwarded to the k3s API server via `--kube-apiserver-arg=oidc-*` flags, tags reachable via `ListTagsForResource`; CFN `AWS::EKS::Cluster` and `AWS::EKS::Nodegroup` supported |
| **OpenSearch Service** | CreateDomain, DescribeDomain, DescribeDomains, DeleteDomain, ListDomainNames, UpdateDomainConfig, DescribeDomainConfig, DescribeDomainChangeProgress, ListVersions, GetCompatibleVersions, AddTags, ListTags, RemoveTags | Management plane on `/2021-01-01/*` (`boto3.client("opensearch")`, SigV4 scope `es`). Default data plane is a stub endpoint (`<domain>.ministack.local:9200`) — set `OPENSEARCH_DATAPLANE=1` to spawn one real `opensearchproject/opensearch` container per `CreateDomain` (same pattern as ElastiCache/RDS); `DescribeDomain.Endpoint` then points at that container and `_cluster/health`/`/_search` work end-to-end. Add `OPENSEARCH_DASHBOARDS=1` (with dataplane on) to also spawn a per-domain `opensearch-dashboards` sidecar; `DescribeDomain.DashboardEndpoint` is populated. ARNs follow `arn:aws:es:<region>:<account>:domain/<name>`; Terraform `aws_opensearch_domain` resource compatible. |
-| **Organizations** | DescribeOrganization, ListRoots, ListAccounts, ListAccountsForParent, DescribeAccount, CreateOrganizationalUnit, DescribeOrganizationalUnit, DeleteOrganizationalUnit, ListOrganizationalUnitsForParent, ListParents, TagResource, UntagResource, ListTagsForResource | Single-master-account org auto-initialised on first call; nested OUs with `Path` field (additive 2026-03 AWS change); the `aws_organizations_organizational_unit` Read calls `ListParents` (single parent, `ROOT`/`ORGANIZATIONAL_UNIT`, to populate `parent_id`) **and** `ListTagsForResource` on every refresh, so both — plus `TagResource`/`UntagResource` — round-trip and a multi-OU hierarchy applies cleanly + idempotently; `FeatureSet=ALL` |
+| **Organizations** | DescribeOrganization, ListRoots, ListAccounts, ListAccountsForParent, DescribeAccount, CreateAccount, DescribeCreateAccountStatus, MoveAccount, CloseAccount, CreateOrganizationalUnit, DescribeOrganizationalUnit, DeleteOrganizationalUnit, ListOrganizationalUnitsForParent, ListParents, CreatePolicy, DescribePolicy, UpdatePolicy, DeletePolicy, ListPolicies, AttachPolicy, DetachPolicy, ListPoliciesForTarget, ListTargetsForPolicy, EnablePolicyType, DisablePolicyType, TagResource, UntagResource, ListTagsForResource | Single-master-account org auto-initialised on first call; `aws_organizations_account`, `aws_organizations_policy` and `aws_organizations_policy_attachment` apply — `CreateAccount` answers with a `CreateAccountStatus` read back through `DescribeCreateAccountStatus`, the root carries `SERVICE_CONTROL_POLICY` enabled plus the AWS-managed `p-FullAWSAccess`, attaching a policy whose type the root has disabled is `PolicyTypeNotEnabledException` and deleting an attached one is `PolicyInUseException`; nested OUs with `Path` field (additive 2026-03 AWS change); the `aws_organizations_organizational_unit` Read calls `ListParents` (single parent, `ROOT`/`ORGANIZATIONAL_UNIT`, to populate `parent_id`) **and** `ListTagsForResource` on every refresh, so both — plus `TagResource`/`UntagResource` — round-trip and a multi-OU hierarchy applies cleanly + idempotently; `FeatureSet=ALL` |
| **Account** | GetAccountInformation, GetContactInformation, ListRegions, GetRegionOptStatus | rest-json `/getAccountInformation`, etc.; returns `AccountState=ACTIVE` (additive 2026-04 AWS change); 31-region opt-in matrix |
| **WAF (Classic + Regional)** | List* (17 ops), Get*, GetChangeToken, GetChangeTokenStatus, GetPermissionPolicy, Create*/Update*/Delete* (stubbed) | Minimal v1 stub — empty lists for all `List*`, valid ChangeToken on Create/Update/Delete; for full features use **wafv2** (also supported) |
| **Signer** | StartSigningJob, DescribeSigningJob, ListSigningJobs, PutSigningProfile, GetSigningProfile | **Signing is synchronous and synthetic**: `StartSigningJob` validates the source object against the local S3 store and writes a JSON signature marker (source reference + SHA-256 of the source bytes — not real cryptography) to `destination.s3.bucketName` at key `prefix + jobId` **before returning**, so the job is already `Succeeded` and a caller whose contract is the signed object at `prefix + jobId` never polls `DescribeSigningJob` (`.zip` is appended for a `.zip` source on `AWSLambda-SHA384-ECDSA`, as measured on AWS). A missing source object or destination bucket is `ResourceNotFoundException` at Start with **no job recorded** (there is no async pipeline, so nothing ever lists as `Failed`); an unknown `profileName` is `ResourceNotFoundException` like on AWS, so create profiles with `PutSigningProfile` first. `clientRequestToken` replays the first response. `source.s3.version` is required by the service model, but an absent value (what `head_object` reports on an unversioned bucket) reads the current object and records the version id S3 holds for it, which is `"null"` only on a bucket without versioning; a literal `"null"` reads the stored `"null"` version when one exists, falling back to the current object. The job carries the profile's `signingMaterial`, `overrides`, `signingParameters` and a `signatureExpiresAt` from its validity period (default 135 months). `ListSigningJobs` filters on `status`, `isRevoked`, `platformId`, `requestedBy` and `jobInvoker`, and pages: `maxResults` (1..25) limits the page and a `nextToken` carries the sort position of the last job, so a paginator reaches every job; without `maxResults` the whole list comes back in one page |
diff --git a/ministack/services/organizations.py b/ministack/services/organizations.py
index 599419cf..607e6cc9 100644
--- a/ministack/services/organizations.py
+++ b/ministack/services/organizations.py
@@ -36,6 +36,11 @@ _accounts = AccountScopedDict() # account_id -> Account dict
_ous = AccountScopedDict() # ou_id -> OU dict (with ParentId)
_roots = AccountScopedDict() # root_id -> Root dict (single root)
_tags = AccountScopedDict() # resource_id (ou-/account/r-/policy) -> {tag_key: tag_value}
+_policies = AccountScopedDict() # policy_id -> Policy dict (summary fields + Content)
+_attachments = AccountScopedDict() # policy_id -> [target_id, ...]
+_create_statuses = AccountScopedDict() # car-id -> CreateAccountStatus dict
+
+FULL_ACCESS_POLICY_ID = "p-FullAWSAccess"
def reset():
@@ -44,6 +49,9 @@ def reset():
_ous.clear()
_roots.clear()
_tags.clear()
+ _policies.clear()
+ _attachments.clear()
+ _create_statuses.clear()
def get_state():
@@ -53,6 +61,9 @@ def get_state():
"ous": copy.deepcopy(_ous),
"roots": copy.deepcopy(_roots),
"tags": copy.deepcopy(_tags),
+ "policies": copy.deepcopy(_policies),
+ "attachments": copy.deepcopy(_attachments),
+ "create_statuses": copy.deepcopy(_create_statuses),
}
@@ -65,7 +76,9 @@ def _restore_state(data):
return
for store, key in (
(_orgs, "orgs"), (_accounts, "accounts"),
- (_ous, "ous"), (_roots, "roots"), (_tags, "tags")
+ (_ous, "ous"), (_roots, "roots"), (_tags, "tags"),
+ (_policies, "policies"), (_attachments, "attachments"),
+ (_create_statuses, "create_statuses"),
):
# update() copies every account's entries; iterating an
# AccountScopedDict yields only the caller's, and the loader runs at
@@ -104,8 +117,22 @@ def _ensure_org():
"Id": root_id,
"Arn": f"arn:aws:organizations::{master}:root/{org_id}/{root_id}",
"Name": "Root",
- "PolicyTypes": [],
+ # An ALL-features org has SCPs enabled on its root.
+ "PolicyTypes": [{"Type": "SERVICE_CONTROL_POLICY", "Status": "ENABLED"}],
+ }
+ _policies[FULL_ACCESS_POLICY_ID] = {
+ "Id": FULL_ACCESS_POLICY_ID,
+ "Arn": f"arn:aws:organizations::aws:policy/{org_id}/service_control_policy/"
+ f"{FULL_ACCESS_POLICY_ID}",
+ "Name": "FullAWSAccess",
+ "Description": "Allows access to every operation",
+ "Type": "SERVICE_CONTROL_POLICY",
+ "AwsManaged": True,
+ "_Content": json.dumps(
+ {"Version": "2012-10-17",
+ "Statement": [{"Effect": "Allow", "Action": "*", "Resource": "*"}]}),
}
+ _attachments[FULL_ACCESS_POLICY_ID] = [root_id, master]
# Master account record
_accounts[master] = {
"Id": master,
@@ -244,11 +271,11 @@ def _tag_list(resource_id):
def _resource_exists(rid):
- # Taggable org resources tracked today: OUs, accounts, and the root.
return (
_ous.get(rid) is not None
or _accounts.get(rid) is not None
or _roots.get(rid) is not None
+ or _policies.get(rid) is not None
)
@@ -304,6 +331,374 @@ def _list_tags_for_resource(payload):
return _json(200, {"Tags": _tag_list(rid)})
+_POLICY_TYPES = (
+ "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",
+)
+
+
+def _policy_summary(p):
+ return {k: v for k, v in p.items() if not k.startswith("_")}
+
+
+def _policy_document(p):
+ return {"PolicySummary": _policy_summary(p), "Content": p["_Content"]}
+
+
+def _require_policy(policy_id):
+ if not policy_id:
+ return None, error_response_json("InvalidInputException", "PolicyId is required", 400)
+ p = _policies.get(policy_id)
+ if p is None:
+ return None, error_response_json(
+ "PolicyNotFoundException",
+ f"We can't find a policy with the PolicyId {policy_id}", 400)
+ return p, None
+
+
+def _target(target_id):
+ """The record and TargetType for a root, OU or account id."""
+ if _roots.get(target_id):
+ return _roots[target_id], "ROOT"
+ if _ous.get(target_id):
+ return _ous[target_id], "ORGANIZATIONAL_UNIT"
+ if _accounts.get(target_id):
+ return _accounts[target_id], "ACCOUNT"
+ return None, None
+
+
+def _policy_type_enabled(policy_type):
+ for root in _roots.values():
+ for entry in root.get("PolicyTypes") or []:
+ if entry.get("Type") == policy_type and entry.get("Status") == "ENABLED":
+ return True
+ return False
+
+
+def _create_account(payload):
+ _ensure_org()
+ email = payload.get("Email")
+ name = payload.get("AccountName")
+ if not email or not name:
+ return error_response_json("InvalidInputException",
+ "Email and AccountName are required", 400)
+ org_id = _orgs["self"]["Id"]
+ master = get_account_id()
+ digits = new_uuid().replace("-", "")
+ account_id = "".join(c for c in digits if c.isdigit()).ljust(12, "0")[:12]
+ request_id = "car-" + new_uuid().replace("-", "")[:8]
+ now = int(time.time())
+ root_id = next(iter(_roots))
+ _accounts[account_id] = {
+ "Id": account_id,
+ "Arn": f"arn:aws:organizations::{master}:account/{org_id}/{account_id}",
+ "Email": email,
+ "Name": name,
+ "Status": "ACTIVE",
+ "JoinedMethod": "CREATED",
+ "JoinedTimestamp": now,
+ "Path": "/",
+ "_ParentId": root_id,
+ }
+ attached = list(_attachments.get(FULL_ACCESS_POLICY_ID) or [])
+ _attachments[FULL_ACCESS_POLICY_ID] = attached + [account_id]
+ inline_tags = payload.get("Tags") or []
+ if inline_tags:
+ _tags[account_id] = {t["Key"]: t.get("Value", "") for t in inline_tags if "Key" in t}
+ status = {
+ "Id": request_id,
+ "AccountName": name,
+ "State": "SUCCEEDED",
+ "RequestedTimestamp": now,
+ "CompletedTimestamp": now,
+ "AccountId": account_id,
+ }
+ _create_statuses[request_id] = status
+ return _json(200, {"CreateAccountStatus": dict(status)})
+
+
+def _describe_create_account_status(payload):
+ _ensure_org()
+ request_id = payload.get("CreateAccountRequestId")
+ if not request_id:
+ return error_response_json("InvalidInputException",
+ "CreateAccountRequestId is required", 400)
+ status = _create_statuses.get(request_id)
+ if status is None:
+ return error_response_json(
+ "CreateAccountStatusNotFoundException",
+ f"We can't find an create account request with the Id {request_id}", 400)
+ return _json(200, {"CreateAccountStatus": dict(status)})
+
+
+def _move_account(payload):
+ _ensure_org()
+ account_id = payload.get("AccountId")
+ source = payload.get("SourceParentId")
+ destination = payload.get("DestinationParentId")
+ if not account_id or not source or not destination:
+ return error_response_json(
+ "InvalidInputException",
+ "AccountId, SourceParentId and DestinationParentId are required", 400)
+ account = _accounts.get(account_id)
+ if account is None:
+ return error_response_json("AccountNotFoundException",
+ f"We can't find an account with the AccountId {account_id}", 400)
+ if _target(source)[0] is None:
+ return error_response_json("SourceParentNotFoundException",
+ f"We can't find a parent with the ParentId {source}", 400)
+ if _target(destination)[0] is None:
+ return error_response_json("DestinationParentNotFoundException",
+ f"We can't find a parent with the ParentId {destination}", 400)
+ updated = dict(account)
+ updated["_ParentId"] = destination
+ _accounts[account_id] = updated
+ return _json(200, {})
+
+
+def _close_account(payload):
+ _ensure_org()
+ account_id = payload.get("AccountId")
+ if not account_id:
+ return error_response_json("InvalidInputException", "AccountId is required", 400)
+ account = _accounts.get(account_id)
+ if account is None:
+ return error_response_json("AccountNotFoundException",
+ f"We can't find an account with the AccountId {account_id}", 400)
+ if account.get("Status") == "SUSPENDED":
+ return error_response_json("AccountAlreadyClosedException",
+ f"The account {account_id} is already closed", 400)
+ updated = dict(account)
+ updated["Status"] = "SUSPENDED"
+ _accounts[account_id] = updated
+ return _json(200, {})
+
+
+def _create_policy(payload):
+ _ensure_org()
+ content = payload.get("Content")
+ description = payload.get("Description")
+ name = payload.get("Name")
+ policy_type = payload.get("Type")
+ if not content or description is None or not name or not policy_type:
+ return error_response_json(
+ "InvalidInputException", "Content, Description, Name and Type are required", 400)
+ if policy_type not in _POLICY_TYPES:
+ return error_response_json("InvalidInputException",
+ f"Type {policy_type} is not a supported policy type", 400)
+ try:
+ json.loads(content)
+ except (TypeError, json.JSONDecodeError):
+ return error_response_json("MalformedPolicyDocumentException",
+ "The provided policy document is not valid JSON", 400)
+ if any(p["Name"] == name and p["Type"] == policy_type for p in _policies.values()):
+ return error_response_json("DuplicatePolicyException",
+ f"A policy with the name {name} already exists", 400)
+ org_id = _orgs["self"]["Id"]
+ policy_id = "p-" + new_uuid().replace("-", "")[:8]
+ rec = {
+ "Id": policy_id,
+ "Arn": f"arn:aws:organizations::{get_account_id()}:policy/{org_id}/"
+ f"{policy_type.lower()}/{policy_id}",
+ "Name": name,
+ "Description": description,
+ "Type": policy_type,
+ "AwsManaged": False,
+ "_Content": content,
+ }
+ _policies[policy_id] = rec
+ inline_tags = payload.get("Tags") or []
+ if inline_tags:
+ _tags[policy_id] = {t["Key"]: t.get("Value", "") for t in inline_tags if "Key" in t}
+ return _json(200, {"Policy": _policy_document(rec)})
+
+
+def _describe_policy(payload):
+ _ensure_org()
+ policy, err = _require_policy(payload.get("PolicyId"))
+ if err:
+ return err
+ return _json(200, {"Policy": _policy_document(policy)})
+
+
+def _update_policy(payload):
+ _ensure_org()
+ policy, err = _require_policy(payload.get("PolicyId"))
+ if err:
+ return err
+ if policy.get("AwsManaged"):
+ return error_response_json("AccessDeniedException",
+ "You can't modify an Amazon Web Services managed policy", 400)
+ name = payload.get("Name")
+ if name and any(p["Name"] == name and p["Id"] != policy["Id"]
+ and p["Type"] == policy["Type"] for p in _policies.values()):
+ return error_response_json("DuplicatePolicyException",
+ f"A policy with the name {name} already exists", 400)
+ content = payload.get("Content")
+ if content is not None:
+ try:
+ json.loads(content)
+ except (TypeError, json.JSONDecodeError):
+ return error_response_json("MalformedPolicyDocumentException",
+ "The provided policy document is not valid JSON", 400)
+ updated = dict(policy)
+ if name:
+ updated["Name"] = name
+ if payload.get("Description") is not None:
+ updated["Description"] = payload["Description"]
+ if content is not None:
+ updated["_Content"] = content
+ _policies[policy["Id"]] = updated
+ return _json(200, {"Policy": _policy_document(updated)})
+
+
+def _delete_policy(payload):
+ _ensure_org()
+ policy, err = _require_policy(payload.get("PolicyId"))
+ if err:
+ return err
+ if _attachments.get(policy["Id"]):
+ return error_response_json(
+ "PolicyInUseException",
+ f"The policy {policy['Id']} is attached to one or more targets", 400)
+ del _policies[policy["Id"]]
+ _tags.pop(policy["Id"], None)
+ _attachments.pop(policy["Id"], None)
+ return _json(200, {})
+
+
+def _list_policies(payload):
+ _ensure_org()
+ policy_filter = payload.get("Filter")
+ if not policy_filter:
+ return error_response_json("InvalidInputException", "Filter is required", 400)
+ out = [_policy_summary(p) for p in _policies.values() if p["Type"] == policy_filter]
+ return _json(200, {"Policies": out})
+
+
+def _attach_policy(payload):
+ _ensure_org()
+ policy, err = _require_policy(payload.get("PolicyId"))
+ if err:
+ return err
+ target_id = payload.get("TargetId")
+ if not target_id:
+ return error_response_json("InvalidInputException", "TargetId is required", 400)
+ if _target(target_id)[0] is None:
+ return error_response_json("TargetNotFoundException",
+ f"We can't find a root, OU or account with the TargetId {target_id}",
+ 400)
+ if not _policy_type_enabled(policy["Type"]):
+ return error_response_json(
+ "PolicyTypeNotEnabledException",
+ f"The policy type {policy['Type']} is not enabled in the current root", 400)
+ attached = list(_attachments.get(policy["Id"]) or [])
+ if target_id in attached:
+ return error_response_json(
+ "DuplicatePolicyAttachmentException",
+ f"The policy {policy['Id']} is already attached to {target_id}", 400)
+ _attachments[policy["Id"]] = attached + [target_id]
+ return _json(200, {})
+
+
+def _detach_policy(payload):
+ _ensure_org()
+ policy, err = _require_policy(payload.get("PolicyId"))
+ if err:
+ return err
+ target_id = payload.get("TargetId")
+ attached = list(_attachments.get(policy["Id"]) or [])
+ if target_id not in attached:
+ return error_response_json(
+ "PolicyNotAttachedException",
+ f"The policy {policy['Id']} is not attached to {target_id}", 400)
+ attached.remove(target_id)
+ _attachments[policy["Id"]] = attached
+ return _json(200, {})
+
+
+def _list_policies_for_target(payload):
+ _ensure_org()
+ target_id = payload.get("TargetId")
+ policy_filter = payload.get("Filter")
+ if not target_id or not policy_filter:
+ return error_response_json("InvalidInputException",
+ "TargetId and Filter are required", 400)
+ if _target(target_id)[0] is None:
+ return error_response_json("TargetNotFoundException",
+ f"We can't find a root, OU or account with the TargetId {target_id}",
+ 400)
+ out = [_policy_summary(p) for pid, p in _policies.items()
+ if p["Type"] == policy_filter and target_id in (_attachments.get(pid) or [])]
+ return _json(200, {"Policies": out})
+
+
+def _list_targets_for_policy(payload):
+ _ensure_org()
+ policy, err = _require_policy(payload.get("PolicyId"))
+ if err:
+ return err
+ targets = []
+ for target_id in _attachments.get(policy["Id"]) or []:
+ record, target_type = _target(target_id)
+ if record is None:
+ continue
+ targets.append({
+ "TargetId": target_id,
+ "Arn": record.get("Arn", ""),
+ "Name": record.get("Name", ""),
+ "Type": target_type,
+ })
+ return _json(200, {"Targets": targets})
+
+
+def _set_policy_type(payload, enable):
+ _ensure_org()
+ root_id = payload.get("RootId")
+ policy_type = payload.get("PolicyType")
+ if not root_id or not policy_type:
+ return error_response_json("InvalidInputException",
+ "RootId and PolicyType are required", 400)
+ root = _roots.get(root_id)
+ if root is None:
+ return error_response_json("RootNotFoundException",
+ f"We can't find a root with the RootId {root_id}", 400)
+ if policy_type not in _POLICY_TYPES:
+ return error_response_json("InvalidInputException",
+ f"Type {policy_type} is not a supported policy type", 400)
+ entries = [dict(e) for e in root.get("PolicyTypes") or []]
+ present = next((e for e in entries if e.get("Type") == policy_type), None)
+ if enable:
+ if present and present.get("Status") == "ENABLED":
+ return error_response_json(
+ "PolicyTypeAlreadyEnabledException",
+ f"The policy type {policy_type} is already enabled", 400)
+ if present:
+ present["Status"] = "ENABLED"
+ else:
+ entries.append({"Type": policy_type, "Status": "ENABLED"})
+ else:
+ if not present or present.get("Status") != "ENABLED":
+ return error_response_json(
+ "PolicyTypeNotEnabledException",
+ f"The policy type {policy_type} is not enabled", 400)
+ entries = [e for e in entries if e.get("Type") != policy_type]
+ updated = dict(root)
+ updated["PolicyTypes"] = entries
+ _roots[root_id] = updated
+ return _json(200, {"Root": dict(updated)})
+
+
+def _enable_policy_type(payload):
+ return _set_policy_type(payload, True)
+
+
+def _disable_policy_type(payload):
+ return _set_policy_type(payload, False)
+
+
_DISPATCH = {
"DescribeOrganization": _describe_organization,
"ListRoots": _list_roots,
@@ -318,6 +713,21 @@ _DISPATCH = {
"TagResource": _tag_resource,
"UntagResource": _untag_resource,
"ListTagsForResource": _list_tags_for_resource,
+ "CreateAccount": _create_account,
+ "DescribeCreateAccountStatus": _describe_create_account_status,
+ "MoveAccount": _move_account,
+ "CloseAccount": _close_account,
+ "CreatePolicy": _create_policy,
+ "DescribePolicy": _describe_policy,
+ "UpdatePolicy": _update_policy,
+ "DeletePolicy": _delete_policy,
+ "ListPolicies": _list_policies,
+ "AttachPolicy": _attach_policy,
+ "DetachPolicy": _detach_policy,
+ "ListPoliciesForTarget": _list_policies_for_target,
+ "ListTargetsForPolicy": _list_targets_for_policy,
+ "EnablePolicyType": _enable_policy_type,
+ "DisablePolicyType": _disable_policy_type,
}
diff --git a/tests/test_organizations.py b/tests/test_organizations.py
index 5350fb11..4d03f05d 100644
--- a/tests/test_organizations.py
+++ b/tests/test_organizations.py
@@ -215,3 +215,158 @@ def test_organizations_list_responses_omit_empty_next_token(orgs):
root_id = orgs.list_roots()["Roots"][0]["Id"]
assert "NextToken" not in orgs.list_organizational_units_for_parent(ParentId=root_id)
assert "NextToken" not in orgs.list_accounts_for_parent(ParentId=root_id)
+
+
+# ---------------------------------------------------------------------------
+# Accounts, SCPs and attachments: the surface Terraform's
+# aws_organizations_account / _policy / _policy_attachment drive.
+# ---------------------------------------------------------------------------
+
+_SCP = "SERVICE_CONTROL_POLICY"
+_DOC = '{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Action":"*","Resource":"*"}]}'
+
+
+def _policy(client, name, content=_DOC, **kw):
+ return client.create_policy(Name=name, Description="d", Type=_SCP,
+ Content=content, **kw)["Policy"]
+
+
+def test_organizations_root_has_scps_enabled_and_full_access_attached():
+ """An ALL-features org has SCPs on its root and the AWS-managed
+ FullAWSAccess policy, so a plan that reads them never sees an empty list."""
+ o = _client_for("110000000001")
+ root = o.list_roots()["Roots"][0]
+ assert {"Type": _SCP, "Status": "ENABLED"} in root["PolicyTypes"]
+ managed = [p for p in o.list_policies(Filter=_SCP)["Policies"]
+ if p["Id"] == "p-FullAWSAccess"]
+ assert managed and managed[0]["AwsManaged"] is True
+ assert root["Id"] in [t["TargetId"]
+ for t in o.list_targets_for_policy(PolicyId="p-FullAWSAccess")["Targets"]]
+
+
+def test_organizations_create_account_is_readable_through_its_request_id():
+ """CreateAccount answers only with a status, so the id arrives through
+ DescribeCreateAccountStatus, which is how the provider learns it."""
+ o = _client_for("110000000002")
+ status = o.create_account(Email="[email protected]", AccountName="dev")["CreateAccountStatus"]
+ assert status["Id"].startswith("car-")
+ assert status["State"] == "SUCCEEDED"
+ account_id = status["AccountId"]
+ assert len(account_id) == 12 and account_id.isdigit()
+
+ again = o.describe_create_account_status(
+ CreateAccountRequestId=status["Id"])["CreateAccountStatus"]
+ assert again["AccountId"] == account_id
+ account = o.describe_account(AccountId=account_id)["Account"]
+ assert account["Name"] == "dev"
+ assert account["Email"] == "[email protected]"
+ assert account["JoinedMethod"] == "CREATED"
+ with pytest.raises(ClientError) as exc:
+ o.describe_create_account_status(CreateAccountRequestId="car-deadbeef")
+ assert exc.value.response["Error"]["Code"] == "CreateAccountStatusNotFoundException"
+
+
+def test_organizations_account_moves_between_parents_and_closes():
+ o = _client_for("110000000003")
+ root = o.list_roots()["Roots"][0]["Id"]
+ ou = o.create_organizational_unit(ParentId=root, Name="Workloads")["OrganizationalUnit"]
+ account_id = o.create_account(
+ Email="[email protected]", AccountName="m")["CreateAccountStatus"]["AccountId"]
+
+ o.move_account(AccountId=account_id, SourceParentId=root, DestinationParentId=ou["Id"])
+ assert o.list_parents(ChildId=account_id)["Parents"][0]["Id"] == ou["Id"]
+ assert account_id in [a["Id"] for a in o.list_accounts_for_parent(ParentId=ou["Id"])["Accounts"]]
+
+ o.close_account(AccountId=account_id)
+ assert o.describe_account(AccountId=account_id)["Account"]["Status"] == "SUSPENDED"
+ with pytest.raises(ClientError) as exc:
+ o.close_account(AccountId=account_id)
+ assert exc.value.response["Error"]["Code"] == "AccountAlreadyClosedException"
+
+
+def test_organizations_policy_crud_round_trips_its_document():
+ o = _client_for("110000000004")
+ created = _policy(o, "deny-all")
+ policy_id = created["PolicySummary"]["Id"]
+ assert policy_id.startswith("p-")
+ assert created["PolicySummary"]["AwsManaged"] is False
+ assert created["Content"] == _DOC
+
+ o.update_policy(PolicyId=policy_id, Description="updated")
+ described = o.describe_policy(PolicyId=policy_id)["Policy"]
+ assert described["PolicySummary"]["Description"] == "updated"
+ assert described["Content"] == _DOC
+
+ o.delete_policy(PolicyId=policy_id)
+ with pytest.raises(ClientError) as exc:
+ o.describe_policy(PolicyId=policy_id)
+ assert exc.value.response["Error"]["Code"] == "PolicyNotFoundException"
+
+
+def test_organizations_policy_attaches_and_detaches_from_a_target():
+ o = _client_for("110000000005")
+ root = o.list_roots()["Roots"][0]["Id"]
+ ou = o.create_organizational_unit(ParentId=root, Name="Restricted")["OrganizationalUnit"]
+ policy_id = _policy(o, "deny-root")["PolicySummary"]["Id"]
+
+ o.attach_policy(PolicyId=policy_id, TargetId=ou["Id"])
+ assert policy_id in [p["Id"] for p in o.list_policies_for_target(
+ TargetId=ou["Id"], Filter=_SCP)["Policies"]]
+ target = [t for t in o.list_targets_for_policy(PolicyId=policy_id)["Targets"]
+ if t["TargetId"] == ou["Id"]][0]
+ assert target["Type"] == "ORGANIZATIONAL_UNIT"
+ assert target["Name"] == "Restricted"
+
+ with pytest.raises(ClientError) as exc:
+ o.attach_policy(PolicyId=policy_id, TargetId=ou["Id"])
+ assert exc.value.response["Error"]["Code"] == "DuplicatePolicyAttachmentException"
+ with pytest.raises(ClientError) as exc:
+ o.delete_policy(PolicyId=policy_id)
+ assert exc.value.response["Error"]["Code"] == "PolicyInUseException"
+
+ o.detach_policy(PolicyId=policy_id, TargetId=ou["Id"])
+ assert o.list_policies_for_target(TargetId=ou["Id"], Filter=_SCP)["Policies"] == []
+ with pytest.raises(ClientError) as exc:
+ o.detach_policy(PolicyId=policy_id, TargetId=ou["Id"])
+ assert exc.value.response["Error"]["Code"] == "PolicyNotAttachedException"
+ o.delete_policy(PolicyId=policy_id)
+
+
+def test_organizations_create_policy_validates_its_input():
+ o = _client_for("110000000006")
+ with pytest.raises(ClientError) as exc:
+ o.create_policy(Name="bad", Description="d", Type=_SCP, Content="not json")
+ assert exc.value.response["Error"]["Code"] == "MalformedPolicyDocumentException"
+ _policy(o, "dupe")
+ with pytest.raises(ClientError) as exc:
+ _policy(o, "dupe")
+ assert exc.value.response["Error"]["Code"] == "DuplicatePolicyException"
+ with pytest.raises(ClientError) as exc:
+ o.update_policy(PolicyId="p-FullAWSAccess", Description="mine")
+ assert exc.value.response["Error"]["Code"] == "AccessDeniedException"
+
+
+def test_organizations_attach_requires_the_policy_type_enabled_on_the_root():
+ o = _client_for("110000000007")
+ root = o.list_roots()["Roots"][0]["Id"]
+ policy_id = _policy(o, "scp")["PolicySummary"]["Id"]
+ o.disable_policy_type(RootId=root, PolicyType=_SCP)
+ with pytest.raises(ClientError) as exc:
+ o.attach_policy(PolicyId=policy_id, TargetId=root)
+ assert exc.value.response["Error"]["Code"] == "PolicyTypeNotEnabledException"
+
+ updated = o.enable_policy_type(RootId=root, PolicyType=_SCP)["Root"]
+ assert {"Type": _SCP, "Status": "ENABLED"} in updated["PolicyTypes"]
+ o.attach_policy(PolicyId=policy_id, TargetId=root)
+ with pytest.raises(ClientError) as exc:
+ o.enable_policy_type(RootId=root, PolicyType=_SCP)
+ assert exc.value.response["Error"]["Code"] == "PolicyTypeAlreadyEnabledException"
+
+
+def test_organizations_policies_are_account_scoped():
+ a, b = _client_for("110000000008"), _client_for("110000000009")
+ policy_id = _policy(a, "tenant-a")["PolicySummary"]["Id"]
+ assert policy_id not in [p["Id"] for p in b.list_policies(Filter=_SCP)["Policies"]]
+ with pytest.raises(ClientError) as exc:
+ b.describe_policy(PolicyId=policy_id)
+ assert exc.value.response["Error"]["Code"] == "PolicyNotFoundException"