Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(iam): account posture — GetAccountSummary, password policy, aliases (#861)
Shai Lahmish2b5b14b5e7aa
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex caa8bf70..12777975 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **SQS — out-of-range numeric attributes rejected with `InvalidAttributeValue`** — `CreateQueue` and `SetQueueAttributes` accepted any value and stored it verbatim, so `VisibilityTimeout=99999` (and every other numeric attribute) was silently kept. Now `VisibilityTimeout` (0..43200), `MaximumMessageSize` (1024..262144), `MessageRetentionPeriod` (60..1209600), `DelaySeconds` (0..900), `ReceiveMessageWaitTimeSeconds` (0..20), and `KmsDataKeyReusePeriodSeconds` (60..86400) are validated against the AWS ranges and rejected with `InvalidAttributeValue` (400) when outside the documented bounds or non-numeric. Reported by @dcabib.- **EventBridge — `anything-but` honors nested `prefix` / `suffix` / `wildcard` content filters** — `{"anything-but": {"prefix": "TEST-"}}` (and `suffix` / `wildcard` variants) was silently ignored at dispatch and every event matched regardless of the field value, because the handler only recognized literal and list-of-literal forms. The nested-matcher form per AWS docs is now negated correctly: an event whose field matches the nested filter is excluded. Reported by @aldirrix.- **ElastiCache — Redis container respawned after restart** — with `PERSIST_STATE=1`, restored cluster metadata reported `CacheClusterStatus=available` but the persisted Docker container id no longer existed, so the endpoint was unreachable even though `DescribeCacheClusters` looked healthy. Restored clusters and replication groups are now marked pending respawn at `restore_state` time and lazily spawned (under a lock to prevent concurrent first-requests from double-spawning) on the first dispatcher call — endpoint metadata is rewritten to the freshly-spawned container before any caller can read it. Failures are logged once and cleared from the pending set (no retry storm). Reported by @ItsSmiffy.+- **IAM — `GetAccountSummary`, `GetAccountPasswordPolicy`, `UpdateAccountPasswordPolicy`, `DeleteAccountPasswordPolicy`, `ListAccountAliases`, `CreateAccountAlias`, `DeleteAccountAlias`** — account-level hygiene reads. `GetAccountSummary` returns computed counts (`Users`, `Groups`, `Roles`, `Policies`, `MFADevices`, `MFADevicesInUse`, `AccountMFAEnabled`) plus static quotas. `GetAccountPasswordPolicy` returns `NoSuchEntity` (404) before any policy is set, matching real AWS. Account aliases stored per-account (replace-on-create semantics).---diff --git a/README.md b/README.mdindex c84d270b..6a112dfa 100644--- a/README.md+++ b/README.md@@ -356,7 +356,7 @@ subnet = ec2.create_subnet(| **DynamoDB** | CreateTable, UpdateTable, DeleteTable, DescribeTable, ListTables, PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem, TransactWriteItems, TransactGetItems, DescribeTimeToLive, UpdateTimeToLive, DescribeContinuousBackups, UpdateContinuousBackups, DescribeEndpoints, TagResource, UntagResource, ListTagsOfResource, EnableKinesisStreamingDestination, DisableKinesisStreamingDestination, DescribeKinesisStreamingDestination, UpdateKinesisStreamingDestination | TTL enforced via thread-safe background reaper (60s cadence); DynamoDB Streams — `StreamSpecification` emits INSERT/MODIFY/REMOVE records on all write operations, respects `StreamViewType`; Kinesis streaming destinations (`aws_dynamodb_kinesis_streaming_destination`) fan item mutations out into any Kinesis stream by ARN while the destination is ACTIVE || **DynamoDB Streams** | ListStreams, DescribeStream, GetShardIterator, GetRecords | Reads records emitted by the main DynamoDB service via `boto3.client("dynamodbstreams")` — single synthetic shard per stream; `TRIM_HORIZON`/`LATEST`/`AT_SEQUENCE_NUMBER`/`AFTER_SEQUENCE_NUMBER` iterator types; `NEW_AND_OLD_IMAGES`, `NEW_IMAGE`, `OLD_IMAGE`, `KEYS_ONLY` view types; opaque base64 iterator tokens || **Lambda** | CreateFunction, DeleteFunction, GetFunction, GetFunctionConfiguration, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration, AddPermission, RemovePermission, GetPolicy, ListVersionsByFunction, PublishVersion, CreateAlias, GetAlias, UpdateAlias, DeleteAlias, ListAliases, TagResource, UntagResource, ListTags, CreateEventSourceMapping, DeleteEventSourceMapping, GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping, CreateFunctionUrlConfig, GetFunctionUrlConfig, UpdateFunctionUrlConfig, DeleteFunctionUrlConfig, ListFunctionUrlConfigs, PutFunctionConcurrency, GetFunctionConcurrency, DeleteFunctionConcurrency, PutFunctionEventInvokeConfig, GetFunctionEventInvokeConfig, DeleteFunctionEventInvokeConfig, PublishLayerVersion, GetLayerVersion, GetLayerVersionByArn, ListLayerVersions, DeleteLayerVersion, ListLayers, AddLayerVersionPermission, RemoveLayerVersionPermission, GetLayerVersionPolicy, CheckpointDurableExecution, GetDurableExecution, GetDurableExecutionState, GetDurableExecutionHistory, ListDurableExecutionsByFunction, StopDurableExecution, SendDurableExecutionCallbackSuccess, SendDurableExecutionCallbackFailure, SendDurableExecutionCallbackHeartbeat | Python and Node.js runtimes execute with warm worker pool; `provided.al2023`/`provided.al2` runtimes execute via Docker RIE (Go, Rust, C++ support); `Publish=True` creates immutable numbered versions; Code via `ZipFile`, `S3Bucket`/`S3Key` (with optional `S3ObjectVersion`), or `ImageUri` (Docker image); `PackageType: Image` pulls and invokes user-provided Docker images via Lambda RIE; SQS, Kinesis, and DynamoDB Streams event source mappings; Function URL CRUD; Lambda Layers CRUD; Aliases; Concurrency; EventInvokeConfig; **Durable Functions** — `CreateFunction` accepts `DurableConfig`; checkpoint/state/history/list/stop ops at the preview API (`2025-12-01`); external `SendCallback{Success,Failure,Heartbeat}` resume the SDK across invocations; resume scheduler fires WAIT expiries, callback timeouts, and step-retry backoffs; verified against the official `aws-durable-execution-sdk-python` and `aws-durable-execution-sdk-java`; **X-Ray active tracing** — `TracingConfig.Mode=Active` injects `_X_AMZN_TRACE_ID` (`Root=1-<hex>-<hex>;Parent=<hex>;Sampled=1`) into the runtime per invocation so the AWS X-Ray SDK runs without `Missing AWS Lambda trace data`; supported on the warm Python / Node executor, provided runtimes, and the local subprocess fallback (docker RIE upstream does not implement X-Ray and is logged but unsupported) |-| **IAM** | CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles, DeleteRole, CreatePolicy, GetPolicy, DeletePolicy, AttachRolePolicy, DetachRolePolicy, PutRolePolicy, GetRolePolicy, DeleteRolePolicy, ListRolePolicies, ListAttachedRolePolicies, CreateAccessKey, ListAccessKeys, DeleteAccessKey, UpdateAccessKey, GetAccessKeyLastUsed, CreateInstanceProfile, GetInstanceProfile, DeleteInstanceProfile, AddRoleToInstanceProfile, RemoveRoleFromInstanceProfile, ListInstanceProfiles, CreateGroup, GetGroup, AddUserToGroup, RemoveUserFromGroup, CreateServiceLinkedRole, DeleteServiceLinkedRole, GetServiceLinkedRoleDeletionStatus, CreateOpenIDConnectProvider, ListOpenIDConnectProviders, CreateSAMLProvider, GetSAMLProvider, ListSAMLProviders, UpdateSAMLProvider, DeleteSAMLProvider, CreateLoginProfile, GetLoginProfile, UpdateLoginProfile, DeleteLoginProfile, CreateVirtualMFADevice, EnableMFADevice, DeactivateMFADevice, ResyncMFADevice, ListMFADevices, ListVirtualMFADevices, DeleteVirtualMFADevice, GetAccountAuthorizationDetails, GenerateServiceLastAccessedDetails, GetServiceLastAccessedDetails, TagRole, UntagRole, TagUser, UntagUser, TagPolicy, UntagPolicy | |+| **IAM** | CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles, DeleteRole, CreatePolicy, GetPolicy, DeletePolicy, AttachRolePolicy, DetachRolePolicy, PutRolePolicy, GetRolePolicy, DeleteRolePolicy, ListRolePolicies, ListAttachedRolePolicies, CreateAccessKey, ListAccessKeys, DeleteAccessKey, UpdateAccessKey, GetAccessKeyLastUsed, CreateInstanceProfile, GetInstanceProfile, DeleteInstanceProfile, AddRoleToInstanceProfile, RemoveRoleFromInstanceProfile, ListInstanceProfiles, CreateGroup, GetGroup, AddUserToGroup, RemoveUserFromGroup, CreateServiceLinkedRole, DeleteServiceLinkedRole, GetServiceLinkedRoleDeletionStatus, CreateOpenIDConnectProvider, ListOpenIDConnectProviders, CreateSAMLProvider, GetSAMLProvider, ListSAMLProviders, UpdateSAMLProvider, DeleteSAMLProvider, CreateLoginProfile, GetLoginProfile, UpdateLoginProfile, DeleteLoginProfile, CreateVirtualMFADevice, EnableMFADevice, DeactivateMFADevice, ResyncMFADevice, ListMFADevices, ListVirtualMFADevices, DeleteVirtualMFADevice, GetAccountAuthorizationDetails, GenerateServiceLastAccessedDetails, GetServiceLastAccessedDetails, TagRole, UntagRole, TagUser, UntagUser, TagPolicy, UntagPolicy , GetAccountSummary, GetAccountPasswordPolicy, UpdateAccountPasswordPolicy, DeleteAccountPasswordPolicy, ListAccountAliases, CreateAccountAlias, DeleteAccountAlias | || **STS** | GetCallerIdentity, AssumeRole, GetSessionToken, AssumeRoleWithWebIdentity | || **IMDS** (EC2 Instance Metadata) | `PUT /latest/api/token`, `GET /latest/meta-data/instance-id`, `GET /latest/meta-data/iam/security-credentials/`, `GET /latest/meta-data/iam/security-credentials/<role>`, `GET /latest/meta-data/iam/info`, `GET /latest/meta-data/placement/{region,availability-zone,...}`, `GET /latest/dynamic/instance-identity/document` | IMDSv1 + IMDSv2; default credential chain falls through to a `ministack-instance-role` document with `ASIA*` session creds. Point SDKs at ministack via `AWS_EC2_METADATA_SERVICE_ENDPOINT=http://localhost:4566` (or `ec2_metadata_service_endpoint` in `~/.aws/config`); set `MINISTACK_IMDS_V2_REQUIRED=1` to require the token PUT || **ECS Task Metadata V4** | `GET /v4/<token>`, `GET /v4/<token>/task`, `GET /v4/<token>/stats`, `GET /v4/<token>/task/stats` | Per-container token injected as `ECS_CONTAINER_METADATA_URI_V4` on every container started by `RunTask`. `/task` returns sibling containers in the same task. Containers reach the gateway via `host.docker.internal` (mapped through `extra_hosts: host-gateway`, so it works on user-defined Docker networks); `networkMode: host` containers use loopback. Volatile by design (stripped on persistence, cleared by `/_ministack/reset`) |diff --git a/ministack/services/iam.py b/ministack/services/iam.pyindex d377e796..0d7613fe 100644--- a/ministack/services/iam.py+++ b/ministack/services/iam.py@@ -61,6 +61,8 @@ _sla_jobs = AccountScopedDict()_saml_providers = AccountScopedDict()_mfa_devices = AccountScopedDict()_login_profiles = AccountScopedDict()+_account_password_policy = AccountScopedDict()+_account_aliases = AccountScopedDict()# -- AWS-managed policies ---------------------------------------------------@@ -291,6 +293,8 @@ def get_state():"saml_providers": copy.deepcopy(_saml_providers),"mfa_devices": copy.deepcopy(_mfa_devices),"login_profiles": copy.deepcopy(_login_profiles),+ "account_password_policy": copy.deepcopy(_account_password_policy),+ "account_aliases": copy.deepcopy(_account_aliases),}@@ -310,6 +314,8 @@ def restore_state(data):_saml_providers.update(data.get("saml_providers", {}))_mfa_devices.update(data.get("mfa_devices", {}))_login_profiles.update(data.get("login_profiles", {}))+ _account_password_policy.update(data.get("account_password_policy", {}))+ _account_aliases.update(data.get("account_aliases", {}))try:@@ -2108,6 +2114,134 @@ def _delete_saml_provider(p):return _xml(200, "DeleteSAMLProviderResponse", "", ns="iam")+# -------------------- Account summary / password policy / aliases --------------------+++def _get_account_summary(p):+ num_users = len(_users)+ num_groups = len(_groups)+ num_roles = len(_roles)+ num_policies = len(_policies)+ num_mfa = len(_mfa_devices)+ num_mfa_in_use = sum(1 for d in _mfa_devices.values() if d.get("User") is not None)+ acct_mfa_enabled = 1 if num_mfa_in_use > 0 else 0++ summary = {+ "Users": num_users,+ "UsersQuota": 5000,+ "Groups": num_groups,+ "GroupsQuota": 300,+ "GroupsPerUserQuota": 10,+ "Roles": num_roles,+ "RolesQuota": 1000,+ "Policies": num_policies,+ "PoliciesQuota": 1500,+ "PolicySizeQuota": 6144,+ "PolicyVersionsInUse": num_policies,+ "PolicyVersionsInUseQuota": 10000,+ "MFADevices": num_mfa,+ "MFADevicesInUse": num_mfa_in_use,+ "AccountMFAEnabled": acct_mfa_enabled,+ "AccountAccessKeysPresent": 0,+ "AccountSigningCertificatesPresent": 0,+ "AccessKeysPerUserQuota": 2,+ "AssumeRolePolicySizeQuota": 2048,+ "GroupPolicySizeQuota": 5120,+ "UserPolicySizeQuota": 2048,+ "AttachedPoliciesPerGroupQuota": 10,+ "AttachedPoliciesPerRoleQuota": 10,+ "AttachedPoliciesPerUserQuota": 10,+ "VersionsPerPolicyQuota": 5,+ "ServerCertificates": 0,+ "ServerCertificatesQuota": 20,+ "SigningCertificatesPerUserQuota": 2,+ }+ entries = "".join(+ f"<entry><key>{k}</key><value>{v}</value></entry>"+ for k, v in summary.items()+ )+ return _xml(200, "GetAccountSummaryResponse",+ f"<GetAccountSummaryResult>"+ f"<SummaryMap>{entries}</SummaryMap>"+ f"</GetAccountSummaryResult>",+ ns="iam")+++def _get_account_password_policy(p):+ pol = _account_password_policy.get("policy")+ if not pol:+ return _error(404, "NoSuchEntity",+ "The account password policy does not exist.", ns="iam")+ fields = (+ f"<MinimumPasswordLength>{pol.get('MinimumPasswordLength', 8)}</MinimumPasswordLength>"+ f"<RequireSymbols>{'true' if pol.get('RequireSymbols') else 'false'}</RequireSymbols>"+ f"<RequireNumbers>{'true' if pol.get('RequireNumbers') else 'false'}</RequireNumbers>"+ f"<RequireUppercaseCharacters>{'true' if pol.get('RequireUppercaseCharacters') else 'false'}</RequireUppercaseCharacters>"+ f"<RequireLowercaseCharacters>{'true' if pol.get('RequireLowercaseCharacters') else 'false'}</RequireLowercaseCharacters>"+ f"<AllowUsersToChangePassword>{'true' if pol.get('AllowUsersToChangePassword') else 'false'}</AllowUsersToChangePassword>"+ f"<ExpirePasswords>{'true' if pol.get('MaxPasswordAge') else 'false'}</ExpirePasswords>"+ f"<HardExpiry>{'true' if pol.get('HardExpiry') else 'false'}</HardExpiry>"+ )+ if pol.get("MaxPasswordAge"):+ fields += f"<MaxPasswordAge>{pol['MaxPasswordAge']}</MaxPasswordAge>"+ if pol.get("PasswordReusePrevention"):+ fields += f"<PasswordReusePrevention>{pol['PasswordReusePrevention']}</PasswordReusePrevention>"+ return _xml(200, "GetAccountPasswordPolicyResponse",+ f"<GetAccountPasswordPolicyResult>"+ f"<PasswordPolicy>{fields}</PasswordPolicy>"+ f"</GetAccountPasswordPolicyResult>",+ ns="iam")+++def _update_account_password_policy(p):+ pol = _account_password_policy.get("policy") or {}+ for field in ("MinimumPasswordLength", "MaxPasswordAge", "PasswordReusePrevention"):+ val = _p(p, field, "")+ if val:+ pol[field] = int(val)+ for field in ("RequireSymbols", "RequireNumbers", "RequireUppercaseCharacters",+ "RequireLowercaseCharacters", "AllowUsersToChangePassword", "HardExpiry"):+ val = _p(p, field, "")+ if val:+ pol[field] = val.lower() == "true"+ _account_password_policy["policy"] = pol+ return _xml(200, "UpdateAccountPasswordPolicyResponse", "", ns="iam")+++def _delete_account_password_policy(p):+ if "policy" not in _account_password_policy:+ return _error(404, "NoSuchEntity",+ "The account password policy does not exist.", ns="iam")+ del _account_password_policy["policy"]+ return _xml(200, "DeleteAccountPasswordPolicyResponse", "", ns="iam")+++def _list_account_aliases(p):+ aliases = _account_aliases.get("aliases") or []+ members = "".join(f"<member>{a}</member>" for a in aliases)+ return _xml(200, "ListAccountAliasesResponse",+ f"<ListAccountAliasesResult>"+ f"<AccountAliases>{members}</AccountAliases>"+ f"<IsTruncated>false</IsTruncated>"+ f"</ListAccountAliasesResult>",+ ns="iam")+++def _create_account_alias(p):+ alias = _p(p, "AccountAlias")+ _account_aliases["aliases"] = [alias]+ return _xml(200, "CreateAccountAliasResponse", "", ns="iam")+++def _delete_account_alias(p):+ alias = _p(p, "AccountAlias")+ aliases = _account_aliases.get("aliases") or []+ if alias in aliases:+ aliases.remove(alias)+ _account_aliases["aliases"] = aliases+ return _xml(200, "DeleteAccountAliasResponse", "", ns="iam")++# -------------------- Tags: policies --------------------def _tag_policy(p):@@ -2439,6 +2573,13 @@ _IAM_HANDLERS = {"GetLoginProfile": _get_login_profile,"UpdateLoginProfile": _update_login_profile,"DeleteLoginProfile": _delete_login_profile,+ "GetAccountSummary": _get_account_summary,+ "GetAccountPasswordPolicy": _get_account_password_policy,+ "UpdateAccountPasswordPolicy": _update_account_password_policy,+ "DeleteAccountPasswordPolicy": _delete_account_password_policy,+ "ListAccountAliases": _list_account_aliases,+ "CreateAccountAlias": _create_account_alias,+ "DeleteAccountAlias": _delete_account_alias,"TagPolicy": _tag_policy,"UntagPolicy": _untag_policy,"ListPolicyTags": _list_policy_tags,@@ -2459,6 +2600,8 @@ def reset():_saml_providers.clear()_mfa_devices.clear()_login_profiles.clear()+ _account_password_policy.clear()+ _account_aliases.clear()# Re-seed AWS-managed policies. They're not customer state, so a# reset call should restore the canonical set rather than leave the# store empty. Per-account attachment counters are session statediff --git a/tests/conftest.py b/tests/conftest.pyindex 336b66a1..af4b9abf 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -96,6 +96,9 @@ _SERIAL_TESTS = {"tests/test_appsync.py::test_appsync_lambda_authorizer_rejection_returns_unauthorized","tests/test_appsync.py::test_appsync_lambda_missing_authorizer_returns_unauthorized","tests/test_appsync.py::test_appsync_lambda_failing_authorizer_returns_unauthorized",+ # Account-global mutations (password policy, alias); must run serially.+ "tests/test_iam.py::test_iam_password_policy_absent_then_set",+ "tests/test_iam.py::test_iam_account_alias_crud",}diff --git a/tests/test_iam.py b/tests/test_iam.pyindex 551d7a70..85884dac 100644--- a/tests/test_iam.py+++ b/tests/test_iam.py@@ -1016,3 +1016,39 @@ def test_iam_delete_login_profile(iam):except Exception:passiam.delete_user(UserName=name)+++# ── Account posture (summary / password policy / aliases) ─────────────+++def test_iam_password_policy_absent_then_set(iam):+ # First, delete any existing policy to ensure clean state (serial test)+ try:+ iam.delete_account_password_policy()+ except Exception:+ pass+ with pytest.raises(iam.exceptions.NoSuchEntityException):+ iam.get_account_password_policy()+ iam.update_account_password_policy(MinimumPasswordLength=14)+ resp = iam.get_account_password_policy()+ assert resp["PasswordPolicy"]["MinimumPasswordLength"] == 14+ iam.delete_account_password_policy()+++def test_iam_account_summary_counts(iam):+ resp = iam.get_account_summary()+ sm = resp["SummaryMap"]+ assert "Users" in sm+ assert "MFADevices" in sm+ assert "AccountMFAEnabled" in sm+ assert isinstance(sm["Users"], int)+++def test_iam_account_alias_crud(iam):+ alias = "my-test-alias-acct"+ iam.create_account_alias(AccountAlias=alias)+ aliases = iam.list_account_aliases()["AccountAliases"]+ assert alias in aliases+ iam.delete_account_alias(AccountAlias=alias)+ aliases_after = iam.list_account_aliases()["AccountAliases"]+ assert alias not in aliases_after