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): add UpdateAccessKey and GetAccessKeyLastUsed operations (#714)
lahmish43161c3b82ff
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 79cc05e9..3226e1ab 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,14 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [Unreleased]++### Added+- **IAM `UpdateAccessKey`** — enables toggling an access key between `Active` and `Inactive`, matching the two statuses the real AWS API accepts. Optional `UserName` is validated when provided.+- **IAM `GetAccessKeyLastUsed`** — returns the AWS "never used" shape (`Region`/`ServiceName` = `N/A`, no `LastUsedDate`) since MiniStack does not track per-key usage history.++---+## [1.3.49] — 2026-05-25### Addeddiff --git a/README.md b/README.mdindex 60362670..e2c87379 100644--- a/README.md+++ b/README.md@@ -349,7 +349,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 | 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 |-| **IAM** | CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles, DeleteRole, CreatePolicy, GetPolicy, DeletePolicy, AttachRolePolicy, DetachRolePolicy, PutRolePolicy, GetRolePolicy, DeleteRolePolicy, ListRolePolicies, ListAttachedRolePolicies, CreateAccessKey, ListAccessKeys, DeleteAccessKey, CreateInstanceProfile, GetInstanceProfile, DeleteInstanceProfile, AddRoleToInstanceProfile, RemoveRoleFromInstanceProfile, ListInstanceProfiles, CreateGroup, GetGroup, AddUserToGroup, RemoveUserFromGroup, CreateServiceLinkedRole, DeleteServiceLinkedRole, GetServiceLinkedRoleDeletionStatus, CreateOpenIDConnectProvider, 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, TagRole, UntagRole, TagUser, UntagUser, TagPolicy, UntagPolicy | || **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 257e7da7..ff5411be 100644--- a/ministack/services/iam.py+++ b/ministack/services/iam.py@@ -12,7 +12,7 @@ IAM actions:PutRolePolicy, GetRolePolicy, DeleteRolePolicy, ListRolePolicies,AttachUserPolicy, DetachUserPolicy, ListAttachedUserPolicies,PutUserPolicy, GetUserPolicy, DeleteUserPolicy, ListUserPolicies,- CreateAccessKey, ListAccessKeys, DeleteAccessKey,+ CreateAccessKey, ListAccessKeys, DeleteAccessKey, UpdateAccessKey, GetAccessKeyLastUsed,CreateInstanceProfile, DeleteInstanceProfile, GetInstanceProfile,AddRoleToInstanceProfile, RemoveRoleFromInstanceProfile,ListInstanceProfiles, ListInstanceProfilesForRole,@@ -965,6 +965,49 @@ def _delete_access_key(p):return _xml(200, "DeleteAccessKeyResponse", "", ns="iam")+def _update_access_key(p):+ key_id = _p(p, "AccessKeyId")+ status = _p(p, "Status")+ user_name = _p(p, "UserName")++ if not key_id:+ return _error(400, "InvalidInput", "AccessKeyId is required.", ns="iam")+ if status not in ("Active", "Inactive"):+ return _error(400, "InvalidInput",+ f"Invalid status value: {status!r}. Must be Active or Inactive.",+ ns="iam")+ if key_id not in _access_keys:+ return _error(404, "NoSuchEntity",+ f"The Access Key with id {key_id} cannot be found.", ns="iam")+ if user_name and _access_keys[key_id]["UserName"] != user_name:+ return _error(404, "NoSuchEntity",+ f"The Access Key with id {key_id} cannot be found.", ns="iam")+ _access_keys[key_id]["Status"] = status+ return _xml(200, "UpdateAccessKeyResponse", "", ns="iam")+++def _get_access_key_last_used(p):+ key_id = _p(p, "AccessKeyId")+ if not key_id:+ return _error(400, "InvalidInput", "AccessKeyId is required.", ns="iam")+ if key_id not in _access_keys:+ return _error(404, "NoSuchEntity",+ f"The Access Key with id {key_id} cannot be found.", ns="iam")+ user_name = _access_keys[key_id]["UserName"]+ # Ministack does not track per-key usage; return the "never used" shape+ # that real AWS returns for keys that have never made a signed request+ # (no LastUsedDate element, Region/ServiceName = "N/A").+ return _xml(200, "GetAccessKeyLastUsedResponse",+ f"<GetAccessKeyLastUsedResult>"+ f"<UserName>{user_name}</UserName>"+ f"<AccessKeyLastUsed>"+ f"<Region>N/A</Region>"+ f"<ServiceName>N/A</ServiceName>"+ f"</AccessKeyLastUsed>"+ f"</GetAccessKeyLastUsedResult>",+ ns="iam")++# -------------------- Instance profiles --------------------def _create_instance_profile(p):@@ -1823,6 +1866,8 @@ _IAM_HANDLERS = {"CreateAccessKey": _create_access_key,"ListAccessKeys": _list_access_keys,"DeleteAccessKey": _delete_access_key,+ "UpdateAccessKey": _update_access_key,+ "GetAccessKeyLastUsed": _get_access_key_last_used,"CreateInstanceProfile": _create_instance_profile,"DeleteInstanceProfile": _delete_instance_profile,"GetInstanceProfile": _get_instance_profile,diff --git a/tests/test_iam.py b/tests/test_iam.pyindex 34f0faad..f6452a0a 100644--- a/tests/test_iam.py+++ b/tests/test_iam.py@@ -199,12 +199,84 @@ def test_iam_list_role_policies(iam):assert "inline-logs" in resp["PolicyNames"]def test_iam_create_access_key(iam):- resp = iam.create_access_key(UserName="iam-test-user")- key = resp["AccessKey"]- assert key["UserName"] == "iam-test-user"- assert key["AccessKeyId"].startswith("AKIA")- assert len(key["SecretAccessKey"]) > 0- assert key["Status"] == "Active"+ username = f"create-key-user-{_uuid_mod.uuid4().hex[:8]}"+ iam.create_user(UserName=username)+ try:+ resp = iam.create_access_key(UserName=username)+ key = resp["AccessKey"]+ assert key["UserName"] == username+ assert key["AccessKeyId"].startswith("AKIA")+ assert len(key["SecretAccessKey"]) > 0+ assert key["Status"] == "Active"+ finally:+ keys = iam.list_access_keys(UserName=username)["AccessKeyMetadata"]+ for k in keys:+ iam.delete_access_key(AccessKeyId=k["AccessKeyId"])+ iam.delete_user(UserName=username)+++def test_iam_update_access_key(iam):+ username = f"upd-key-user-{_uuid_mod.uuid4().hex[:8]}"+ iam.create_user(UserName=username)+ resp = iam.create_access_key(UserName=username)+ key_id = resp["AccessKey"]["AccessKeyId"]+ try:+ iam.update_access_key(UserName=username, AccessKeyId=key_id, Status="Inactive")+ keys = iam.list_access_keys(UserName=username)["AccessKeyMetadata"]+ found = next(k for k in keys if k["AccessKeyId"] == key_id)+ assert found["Status"] == "Inactive"++ iam.update_access_key(UserName=username, AccessKeyId=key_id, Status="Active")+ keys = iam.list_access_keys(UserName=username)["AccessKeyMetadata"]+ found = next(k for k in keys if k["AccessKeyId"] == key_id)+ assert found["Status"] == "Active"+ finally:+ iam.delete_access_key(AccessKeyId=key_id)+ iam.delete_user(UserName=username)+++def test_iam_update_access_key_not_found(iam):+ with pytest.raises(ClientError) as exc:+ iam.update_access_key(AccessKeyId="AKIAIOSFODNN7EXAMPLE", Status="Inactive")+ assert exc.value.response["Error"]["Code"] == "NoSuchEntity"+++def test_iam_update_access_key_invalid_status(iam):+ username = f"inv-status-user-{_uuid_mod.uuid4().hex[:8]}"+ iam.create_user(UserName=username)+ resp = iam.create_access_key(UserName=username)+ key_id = resp["AccessKey"]["AccessKeyId"]+ try:+ with pytest.raises(ClientError) as exc:+ iam.update_access_key(AccessKeyId=key_id, Status="Disabled")+ assert exc.value.response["Error"]["Code"] == "InvalidInput"+ finally:+ iam.delete_access_key(AccessKeyId=key_id)+ iam.delete_user(UserName=username)+++def test_iam_get_access_key_last_used(iam):+ username = f"key-last-used-{_uuid_mod.uuid4().hex[:8]}"+ iam.create_user(UserName=username)+ resp = iam.create_access_key(UserName=username)+ key_id = resp["AccessKey"]["AccessKeyId"]+ try:+ result = iam.get_access_key_last_used(AccessKeyId=key_id)+ assert result["UserName"] == username+ last_used = result["AccessKeyLastUsed"]+ assert last_used["Region"] == "N/A"+ assert last_used["ServiceName"] == "N/A"+ assert "LastUsedDate" not in last_used+ finally:+ iam.delete_access_key(AccessKeyId=key_id)+ iam.delete_user(UserName=username)+++def test_iam_get_access_key_last_used_not_found(iam):+ with pytest.raises(ClientError) as exc:+ iam.get_access_key_last_used(AccessKeyId="AKIAIOSFODNN7EXAMPLE")+ assert exc.value.response["Error"]["Code"] == "NoSuchEntity"+def test_iam_instance_profile(iam):assume = json.dumps({"Version": "2012-10-17", "Statement": []})