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
fix(iam): implement instance-profile tagging actions (#926)
Julin Chandrarajah8aee3a692d94
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 50d4f89e..eadc049b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **S3 — preserve WebSiteRedirectLocation ** — x-amz-website-redirect-location is now preserved### Fixed+- **IAM — instance-profile tagging actions implemented** — `TagInstanceProfile`, `UntagInstanceProfile`, and `ListInstanceProfileTags` previously failed with `InvalidAction: Unknown IAM action`. They are now handled, tags are stored on the instance-profile object (including tags supplied at `CreateInstanceProfile` time), and they read back from `GetInstanceProfile` / `ListInstanceProfiles` (via the `Tags` member) and `ListInstanceProfileTags`. This read-back lets Terraform's `aws_iam_instance_profile` settle to "No changes" on re-apply instead of detecting tag drift.- **EventBridge — input transformer reserved variables** — substitute `<aws.events.event.json>`, `<aws.events.event>`, `<aws.events.rule-name>`, `<aws.events.rule-arn>`, and `<aws.events.event.ingestion-time>` so CDK-style templates that embed the source event deliver valid JSON.- **CloudFormation — `GetTemplateSummary` now returns `Capabilities` and `CapabilitiesReason`** — the handler already accepted `TemplateBody` and returned `Parameters` / `ResourceTypes` correctly, but omitted the `Capabilities` and `CapabilitiesReason` fields. These are now computed from the template: `CAPABILITY_NAMED_IAM` for IAM resources with explicit name properties (`RoleName`, `UserName`, etc.), `CAPABILITY_IAM` for unnamed IAM resources, and `CAPABILITY_AUTO_EXPAND` for templates with a `Transform`. `CapabilitiesReason` uses the format confirmed against the AWS API: `"The following resource(s) require capabilities: [<type>]"`. Contributed by @maximoosemine.- **Lambda - CreateEventSourceMapping persists FilterCriteria** — CreateEventSourceMapping was silently dropping the FilterCriteria parameter, so any filter specified at creation time was never applied.diff --git a/README.md b/README.mdindex ade45ded..27dff0d7 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, GenerateCredentialReport, GetCredentialReport, GetAccountSummary, GetAccountPasswordPolicy, UpdateAccountPasswordPolicy, DeleteAccountPasswordPolicy, ListAccountAliases, CreateAccountAlias, DeleteAccountAlias | |+| **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, TagInstanceProfile, UntagInstanceProfile, ListInstanceProfileTags, 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, GenerateCredentialReport, GetCredentialReport, 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 b88da81f..294fde6f 100644--- a/ministack/services/iam.py+++ b/ministack/services/iam.py@@ -16,6 +16,7 @@ IAM actions:CreateInstanceProfile, DeleteInstanceProfile, GetInstanceProfile,AddRoleToInstanceProfile, RemoveRoleFromInstanceProfile,ListInstanceProfiles, ListInstanceProfilesForRole,+ TagInstanceProfile, UntagInstanceProfile, ListInstanceProfileTags,UpdateAssumeRolePolicy,CreateGroup, GetGroup, DeleteGroup, ListGroups,AddUserToGroup, RemoveUserFromGroup, ListGroupsForUser,@@ -1062,6 +1063,7 @@ def _create_instance_profile(p):"Path": path,"CreateDate": _now(),"Roles": [],+ "Tags": _extract_tags(p),}return _xml(200, "CreateInstanceProfileResponse",f"<CreateInstanceProfileResult>"@@ -1158,6 +1160,49 @@ def _list_instance_profiles_for_role(p):ns="iam")+# -------------------- Tags: instance profiles --------------------++def _tag_instance_profile(p):+ ip_name = _p(p, "InstanceProfileName")+ ip = _instance_profiles.get(ip_name)+ if not ip:+ return _error(404, "NoSuchEntity",+ f"Instance profile {ip_name} not found.", ns="iam")+ new_tags = _extract_tags(p)+ existing = {t["Key"]: t for t in ip.get("Tags", [])}+ for t in new_tags:+ existing[t["Key"]] = t+ ip["Tags"] = list(existing.values())+ return _xml(200, "TagInstanceProfileResponse", "", ns="iam")+++def _untag_instance_profile(p):+ ip_name = _p(p, "InstanceProfileName")+ ip = _instance_profiles.get(ip_name)+ if not ip:+ return _error(404, "NoSuchEntity",+ f"Instance profile {ip_name} not found.", ns="iam")+ keys_to_remove = _extract_tag_keys(p)+ ip["Tags"] = [t for t in ip.get("Tags", []) if t["Key"] not in keys_to_remove]+ return _xml(200, "UntagInstanceProfileResponse", "", ns="iam")+++def _list_instance_profile_tags(p):+ ip_name = _p(p, "InstanceProfileName")+ ip = _instance_profiles.get(ip_name)+ if not ip:+ return _error(404, "NoSuchEntity",+ f"Instance profile {ip_name} not found.", ns="iam")+ members = "".join(+ f"<member><Key>{t['Key']}</Key><Value>{t['Value']}</Value></member>"+ for t in ip.get("Tags", [])+ )+ return _xml(200, "ListInstanceProfileTagsResponse",+ f"<ListInstanceProfileTagsResult><Tags>{members}</Tags>"+ "<IsTruncated>false</IsTruncated></ListInstanceProfileTagsResult>",+ ns="iam")++# -------------------- Tags: roles --------------------def _tag_role(p):@@ -2543,12 +2588,22 @@ def _instance_profile_xml(name):for rname in ip["Roles"]:if rname in _roles:roles_xml += f"<member>{_role_xml(rname)}</member>"+ # Tags are emitted when present so GetInstanceProfile / ListInstanceProfiles+ # read them back. _user_xml / _role_xml follow the same pattern.+ tags_xml = ""+ if ip.get("Tags"):+ tag_members = "".join(+ f"<member><Key>{t['Key']}</Key><Value>{t['Value']}</Value></member>"+ for t in ip["Tags"]+ )+ tags_xml = f"<Tags>{tag_members}</Tags>"return (f"<InstanceProfileName>{ip['InstanceProfileName']}</InstanceProfileName>"f"<InstanceProfileId>{ip['InstanceProfileId']}</InstanceProfileId>"f"<Arn>{ip['Arn']}</Arn>"f"<Path>{ip['Path']}</Path>"f"<CreateDate>{ip['CreateDate']}</CreateDate>"- f"<Roles>{roles_xml}</Roles>")+ f"<Roles>{roles_xml}</Roles>"+ f"{tags_xml}")def _xml(status, root_tag, inner, ns="iam"):@@ -2620,6 +2675,9 @@ _IAM_HANDLERS = {"RemoveRoleFromInstanceProfile": _remove_role_from_instance_profile,"ListInstanceProfiles": _list_instance_profiles,"ListInstanceProfilesForRole": _list_instance_profiles_for_role,+ "TagInstanceProfile": _tag_instance_profile,+ "UntagInstanceProfile": _untag_instance_profile,+ "ListInstanceProfileTags": _list_instance_profile_tags,"UpdateAssumeRolePolicy": _update_assume_role_policy,"TagRole": _tag_role,"UntagRole": _untag_role,diff --git a/tests/test_iam.py b/tests/test_iam.pyindex ecdb6ad7..90c0f87d 100644--- a/tests/test_iam.py+++ b/tests/test_iam.py@@ -484,6 +484,50 @@ def test_iam_instance_profile_crud(iam):iam.remove_role_from_instance_profile(InstanceProfileName="qa-iam-ip", RoleName="qa-iam-ip-role")iam.delete_instance_profile(InstanceProfileName="qa-iam-ip")++def test_iam_instance_profile_tags(iam):+ """TagInstanceProfile, ListInstanceProfileTags, UntagInstanceProfile round-trip."""+ iam.create_instance_profile(InstanceProfileName="qa-iam-ip-tags")+ iam.tag_instance_profile(+ InstanceProfileName="qa-iam-ip-tags",+ Tags=[{"Key": "k", "Value": "v"}],+ )+ tags = iam.list_instance_profile_tags(InstanceProfileName="qa-iam-ip-tags")["Tags"]+ assert any(t["Key"] == "k" and t["Value"] == "v" for t in tags)+ iam.untag_instance_profile(InstanceProfileName="qa-iam-ip-tags", TagKeys=["k"])+ tags2 = iam.list_instance_profile_tags(InstanceProfileName="qa-iam-ip-tags")["Tags"]+ assert not any(t["Key"] == "k" for t in tags2)+ iam.delete_instance_profile(InstanceProfileName="qa-iam-ip-tags")+++def test_iam_instance_profile_tags_serialized_in_get(iam):+ """Tags set via TagInstanceProfile (and at create time) must read back from+ GetInstanceProfile / ListInstanceProfiles so Terraform's+ aws_iam_instance_profile does not detect tag drift on re-apply. Same bug+ class as #441 (user tags) / #445 (policy tags)."""+ import uuid as _u+ name = f"qa-iam-ip-ser-{_u.uuid4().hex[:8]}"+ # Tags supplied at create time must round-trip.+ iam.create_instance_profile(+ InstanceProfileName=name,+ Tags=[{"Key": "Team", "Value": "platform"}],+ )+ got = iam.get_instance_profile(InstanceProfileName=name)["InstanceProfile"]+ got_tags = {t["Key"]: t["Value"] for t in got.get("Tags") or []}+ assert got_tags.get("Team") == "platform", f"GetInstanceProfile dropped Tags: {got}"+ # TagInstanceProfile after-the-fact must also round-trip via GetInstanceProfile.+ iam.tag_instance_profile(InstanceProfileName=name, Tags=[{"Key": "Env", "Value": "dev"}])+ got2 = iam.get_instance_profile(InstanceProfileName=name)["InstanceProfile"]+ got2_tags = {t["Key"]: t["Value"] for t in got2.get("Tags") or []}+ assert got2_tags == {"Team": "platform", "Env": "dev"}+ # ListInstanceProfiles (separate code path) must surface them too.+ listed = iam.list_instance_profiles()["InstanceProfiles"]+ match = next(p for p in listed if p["InstanceProfileName"] == name)+ listed_tags = {t["Key"]: t["Value"] for t in match.get("Tags") or []}+ assert listed_tags == {"Team": "platform", "Env": "dev"}+ iam.delete_instance_profile(InstanceProfileName=name)++def test_iam_attach_detach_user_policy(iam):"""AttachUserPolicy / DetachUserPolicy / ListAttachedUserPolicies."""iam.create_user(UserName="qa-iam-attach-user")