Skip to content

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

release v1.3.56 (#787)

Nahuel Nucera14162423dfb4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8a1eb4dd..991b1a3d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,20 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.3.56] — 2026-06-02
+
+### Added
+- **Cognito User Pools — `CUSTOM_AUTH` flow with DefineAuthChallenge / CreateAuthChallenge / VerifyAuthChallengeResponse triggers** — `InitiateAuth` / `AdminInitiateAuth` / `RespondToAuthChallenge` / `AdminRespondToAuthChallenge` now run the full custom-auth state machine through the configured Lambdas. `DefineAuthChallenge` decides next-step / `issueTokens` / `failAuthentication`; `CreateAuthChallenge` builds public + private challenge parameters carried through the opaque session token; `VerifyAuthChallengeResponse` evaluates the answer. Session TTL honors the client's `AuthSessionValidity` (minutes), capped at 3 answered rounds per AWS. Unblocks passwordless / magic-link / SMS-OTP flows that previously failed with `Unsupported AuthFlow: CUSTOM_AUTH`. Reported by @aahoughton. Contributed by @AdigaAkhil.
+- **EKS Access Entries (modern IAM bindings — replace aws-auth ConfigMap)** — 8 new ops at `/clusters/{name}/access-entries[/{principalArn}[/access-policies[/{policyArn}]]]`: `CreateAccessEntry`, `DescribeAccessEntry`, `ListAccessEntries`, `UpdateAccessEntry`, `DeleteAccessEntry`, `AssociateAccessPolicy`, `DisassociateAccessPolicy`, `ListAssociatedAccessPolicies`. `accessScope` validated against `{cluster, namespace}` with `namespaces` required when scope is namespace-bound; deleting an access entry cascades its associated policies. Unblocks Crossplane `accessentry.eks.aws.upbound.io`, Terraform `aws_eks_access_entry` + `aws_eks_access_policy_association`, and any tool using the post-`1.29` EKS IAM binding API. Reported by @b-rajesh.
+
+### Fixed
+- **Lambda — `_X_AMZN_TRACE_ID` injected for `TracingConfig.Mode=Active`** — the runtime env var the AWS X-Ray SDK reads on every segment was never being set, so `aws-xray-sdk-python` raised `Missing AWS Lambda trace data for X-Ray` on any active-tracing function. Now synthesized per invocation (`Root=1-<8hex>-<24hex>;Parent=<16hex>;Sampled=1`) and threaded into the warm worker pool (Python + Node bootstraps pop the event field into `os.environ` / `process.env`), the provided-runtime executor (per-spawn `proc_env`), and the local subprocess executor. The docker RIE executor is documented as unsupported — AWS RIE itself drops X-Ray, the pool reuses containers so a baked env would go stale — and now logs a warning when Active mode is configured on that path. Reported by @arivazhaganjeganathan-abc.
+- **Firehose — Lambda processor invoked in the delivery pipeline** — `ProcessingConfiguration.Processors[].Type=Lambda` was persisted on the destination but never consulted at invocation time; records flowed straight to S3 without the configured transformation. The full AWS contract is now honored: per-batch event `{invocationId, deliveryStreamArn, region, records:[{recordId, approximateArrivalTimestamp, data}]}`, response `{records:[{recordId, result, data}]}` with `result ∈ {Ok, Dropped, ProcessingFailed}`. `Ok` → transformed `data` written downstream; `Dropped` / `ProcessingFailed` → omitted; Lambda not-found / crash / malformed body → records pass through unchanged (best-effort per AWS). Applies to both `PutRecord` / `PutRecordBatch` and `KinesisStreamAsSource` fan-out. Reported by @arivazhaganjeganathan-abc.
+- **Cognito CUSTOM_AUTH — `issueTokens` on the cap-boundary attempt now wins over `MaxAttempts`** — a correct answer on the 3rd round (cap boundary) was being silently rejected with `Max authentication attempts exceeded` because the cap check fired before the `issueTokens` branch. The cap is meant to prevent a NEXT (4th) round, not penalize success on the boundary. Reordered: `failAuthentication` → `issueTokens` → max-attempts → next round. Applies to both `RespondToAuthChallenge` and `AdminRespondToAuthChallenge`.
+- **DynamoDB — AWS-canonical error-message parity across 24 operations** — `PutItem` set-duplicates now include the collection contents (`Input collection [a, a] contains duplicates.`); `UpdateItem` syntax errors carry token-context (`token: "INVALID", near: "INVALID SYNTAX"`); `Query` empty `KeyConditionExpression` short-circuits before unused-EAV; `Scan` `Limit=0` quotes the value (`Value '0' at 'limit'`); `Scan` `Segment` negative path returns the standard `1 validation error detected` envelope with lowercase `segment`; redundant-parentheses check pre-fires on `FilterExpression` / `KeyConditionExpression` so empty tables still reject (rather than silently passing); `begins_with` non-string operand pre-validated at parse time. `BatchExecuteStatement` per-statement `Error.Code` now drops the `Exception` suffix to match `BatchStatementErrorCodeEnum` (`DuplicateItem` / `ResourceNotFound`). `TransactGetItems` reports per-action missing-key errors via `TransactionCanceledException` cancellation reasons (not a request-level error). `CreateTable` `>2 KeySchema` error dumps the Java-toString `KeySchemaElement(attributeName=…, keyType=…)` shape. `GetItem` / `TransactGetItems` `ProjectionExpression` parses syntactically + rejects reserved keywords up front. `UpdateItem` pre-rejects mutation of hash / range key attributes regardless of whether the item exists. `BatchWriteItem` / `TransactWriteItems` / `TransactGetItems` size-exceeded errors include the AWS-shape Java-toString dump in the envelope.
+
+---
+
## [1.3.55] — 2026-06-01
### Added
diff --git a/README.md b/README.md
index a32d611c..88664193 100644
--- a/README.md
+++ b/README.md
@@ -348,7 +348,7 @@ subnet = ec2.create_subnet(
| **SNS** | CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes, Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, GetSubscriptionAttributes, SetSubscriptionAttributes, ConfirmSubscription, Publish, PublishBatch, TagResource, UntagResource, ListTagsForResource, CreatePlatformApplication, CreatePlatformEndpoint | SNS→SQS fanout delivery; SNS→Lambda fanout (synchronous invocation); FIFO topics with 5-minute deduplication, sequence numbers, content-based deduplication, and subscription validation |
| **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` |
+| **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, 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 |
@@ -493,13 +493,13 @@ Unsupported resource types fail with `CREATE_FAILED` (or `ROLLBACK_COMPLETE` if
| **Glue** | CreateDatabase, DeleteDatabase, GetDatabase, GetDatabases, UpdateDatabase, CreateTable, DeleteTable, GetTable, GetTables, UpdateTable, BatchDeleteTable, CreatePartition, DeletePartition, GetPartition, GetPartitions, BatchCreatePartition, BatchGetPartition, CreatePartitionIndex, GetPartitionIndexes, CreateConnection, DeleteConnection, GetConnection, GetConnections, CreateCrawler, DeleteCrawler, GetCrawler, GetCrawlers, UpdateCrawler, StartCrawler, StopCrawler, GetCrawlerMetrics, CreateJob, DeleteJob, GetJob, GetJobs, UpdateJob, StartJobRun, GetJobRun, GetJobRuns, BatchStopJobRun, CreateTrigger, GetTrigger, DeleteTrigger, UpdateTrigger, StartTrigger, StopTrigger, ListTriggers, BatchGetTriggers, GetTriggers, CreateWorkflow, GetWorkflow, DeleteWorkflow, UpdateWorkflow, StartWorkflowRun, CreateSecurityConfiguration, DeleteSecurityConfiguration, GetSecurityConfiguration, GetSecurityConfigurations, CreateClassifier, GetClassifier, GetClassifiers, DeleteClassifier, TagResource, UntagResource, GetTags | Python shell jobs actually execute via subprocess; Spark jobs run on the official `amazon/aws-glue-libs` PySpark image (`GlueVersion: 4.0` / `3.0`) on MiniStack's Docker network |
| **S3 Tables** | CreateTableBucket, ListTableBuckets, GetTableBucket, DeleteTableBucket, CreateNamespace, ListNamespaces, GetNamespace, DeleteNamespace, CreateTable, ListTables, GetTable, DeleteTable, GetTableMetadataLocation, UpdateTableMetadataLocation | Iceberg-format tables; embedded Iceberg REST catalog at `/iceberg` so Spark jobs (`spark.sql.catalog.*.type=rest`) can create / load / commit without an external catalog; data files in S3, metadata in memory |
| **Athena** | StartQueryExecution, GetQueryExecution, GetQueryResults, StopQueryExecution, ListQueryExecutions, BatchGetQueryExecution, CreateWorkGroup, DeleteWorkGroup, GetWorkGroup, ListWorkGroups, UpdateWorkGroup, CreateNamedQuery, DeleteNamedQuery, GetNamedQuery, ListNamedQueries, BatchGetNamedQuery, CreateDataCatalog, GetDataCatalog, ListDataCatalogs, DeleteDataCatalog, UpdateDataCatalog, CreatePreparedStatement, GetPreparedStatement, DeletePreparedStatement, ListPreparedStatements, GetTableMetadata, ListTableMetadata, TagResource, UntagResource, ListTagsForResource | Real SQL via **DuckDB** when installed (`pip install duckdb`), otherwise returns mock results; result pagination; column type metadata |
-| **Firehose** | CreateDeliveryStream, DeleteDeliveryStream, DescribeDeliveryStream, ListDeliveryStreams, PutRecord, PutRecordBatch, UpdateDestination, TagDeliveryStream, UntagDeliveryStream, ListTagsForDeliveryStream, StartDeliveryStreamEncryption, StopDeliveryStreamEncryption | S3 destinations write records to the local S3 emulator; all other destination types buffer in-memory; concurrency-safe `UpdateDestination` via `VersionId`; `DeliveryStreamType=KinesisStreamAsSource` consumes records from the source Kinesis stream on `PutRecord` / `PutRecords` and forwards them to the configured S3 destination, honoring `Prefix` and `DeliveryStartTimestamp` |
+| **Firehose** | CreateDeliveryStream, DeleteDeliveryStream, DescribeDeliveryStream, ListDeliveryStreams, PutRecord, PutRecordBatch, UpdateDestination, TagDeliveryStream, UntagDeliveryStream, ListTagsForDeliveryStream, StartDeliveryStreamEncryption, StopDeliveryStreamEncryption | S3 destinations write records to the local S3 emulator; all other destination types buffer in-memory; concurrency-safe `UpdateDestination` via `VersionId`; `DeliveryStreamType=KinesisStreamAsSource` consumes records from the source Kinesis stream on `PutRecord` / `PutRecords` and forwards them to the configured S3 destination, honoring `Prefix` and `DeliveryStartTimestamp`; `ProcessingConfiguration.Processors[].Type=Lambda` invoked per-batch with the AWS-shape event (`{invocationId, deliveryStreamArn, region, records:[{recordId, approximateArrivalTimestamp, data}]}`) — `Ok` records ship the transformed data downstream, `Dropped`/`ProcessingFailed` are omitted, Lambda failures pass records through unchanged (best-effort per AWS) |
| **Route53** | CreateHostedZone, GetHostedZone, DeleteHostedZone, ListHostedZones, ListHostedZonesByName, UpdateHostedZoneComment, ChangeResourceRecordSets (CREATE/UPSERT/DELETE), ListResourceRecordSets, GetChange, CreateHealthCheck, GetHealthCheck, DeleteHealthCheck, ListHealthChecks, UpdateHealthCheck, ChangeTagsForResource, ListTagsForResource | REST/XML protocol; SOA + NS records auto-created; CallerReference idempotency; alias records, weighted/failover/latency routing; marker-based pagination |
| **EC2** | RunInstances, DescribeInstances, DescribeInstanceAttribute, DescribeInstanceTypes, DescribeVpcAttribute, TerminateInstances, StopInstances, StartInstances, RebootInstances, DescribeImages, CreateSecurityGroup, DeleteSecurityGroup, DescribeSecurityGroups, AuthorizeSecurityGroupIngress, RevokeSecurityGroupIngress, AuthorizeSecurityGroupEgress, RevokeSecurityGroupEgress, DescribeSecurityGroupRules, CreateKeyPair, DeleteKeyPair, DescribeKeyPairs, ImportKeyPair, CreateVpc, DeleteVpc, DescribeVpcs, ModifyVpcAttribute, CreateSubnet, DeleteSubnet, DescribeSubnets, ModifySubnetAttribute, CreateInternetGateway, DeleteInternetGateway, DescribeInternetGateways, AttachInternetGateway, DetachInternetGateway, CreateRouteTable, DeleteRouteTable, DescribeRouteTables, AssociateRouteTable, DisassociateRouteTable, ReplaceRouteTableAssociation, CreateRoute, ReplaceRoute, DeleteRoute, CreateNetworkInterface, DeleteNetworkInterface, DescribeNetworkInterfaces, AttachNetworkInterface, DetachNetworkInterface, CreateVpcEndpoint, DeleteVpcEndpoints, DescribeVpcEndpoints, ModifyVpcEndpoint, DescribePrefixLists, DescribeAvailabilityZones, AllocateAddress, ReleaseAddress, AssociateAddress, DisassociateAddress, DescribeAddresses, DescribeAddressesAttribute, CreateTags, DeleteTags, DescribeTags, CreateNatGateway, DescribeNatGateways, DeleteNatGateway, CreateNetworkAcl, DescribeNetworkAcls, DeleteNetworkAcl, CreateNetworkAclEntry, DeleteNetworkAclEntry, ReplaceNetworkAclEntry, ReplaceNetworkAclAssociation, CreateFlowLogs, DescribeFlowLogs, DeleteFlowLogs, CreateVpcPeeringConnection, AcceptVpcPeeringConnection, DescribeVpcPeeringConnections, DeleteVpcPeeringConnection, CreateDhcpOptions, AssociateDhcpOptions, DescribeDhcpOptions, DeleteDhcpOptions, CreateEgressOnlyInternetGateway, DescribeEgressOnlyInternetGateways, DeleteEgressOnlyInternetGateway, CreateManagedPrefixList, DescribeManagedPrefixLists, GetManagedPrefixListEntries, ModifyManagedPrefixList, DeleteManagedPrefixList, CreateVpnGateway, DescribeVpnGateways, AttachVpnGateway, DetachVpnGateway, DeleteVpnGateway, EnableVgwRoutePropagation, DisableVgwRoutePropagation, CreateCustomerGateway, DescribeCustomerGateways, DeleteCustomerGateway, DescribeInstanceCreditSpecifications, DescribeInstanceMaintenanceOptions, DescribeInstanceAutoRecoveryAttribute, ModifyInstanceMaintenanceOptions, DescribeInstanceTopology, DescribeSpotInstanceRequests, DescribeCapacityReservations, DescribeInstanceStatus, DescribeVpcClassicLink, DescribeVpcClassicLinkDnsSupport, CreateLaunchTemplate, CreateLaunchTemplateVersion, DescribeLaunchTemplates, DescribeLaunchTemplateVersions, ModifyLaunchTemplate, DeleteLaunchTemplate | 136 actions; `AuthorizeSecurityGroupIngress` is idempotent on duplicate rules (same behavior as egress; avoids Terraform re-apply failures); in-memory state only — no real VMs; CreateVpc provisions per-VPC default route table, network ACL, and security group; full Terraform VPC module v6.6.0 compatible; VPN/Customer gateways, managed prefix lists, VPC endpoints with modify support; launch templates with versioning ($Latest/$Default) |
| **EBS** | CreateVolume, DeleteVolume, DescribeVolumes, DescribeVolumeStatus, AttachVolume, DetachVolume, ModifyVolume, DescribeVolumesModifications, EnableVolumeIO, ModifyVolumeAttribute, DescribeVolumeAttribute, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, CopySnapshot, ModifySnapshotAttribute, DescribeSnapshotAttribute | Part of EC2 Query/XML service; attach/detach updates volume state; snapshots stored as completed immediately; Pro-only on LocalStack — free here |
| **EFS** | CreateFileSystem, DescribeFileSystems, DeleteFileSystem, UpdateFileSystem, CreateMountTarget, DescribeMountTargets, DeleteMountTarget, DescribeMountTargetSecurityGroups, ModifyMountTargetSecurityGroups, CreateAccessPoint, DescribeAccessPoints, DeleteAccessPoint, TagResource, UntagResource, ListTagsForResource, PutLifecycleConfiguration, DescribeLifecycleConfiguration, PutBackupPolicy, DescribeBackupPolicy, DescribeAccountPreferences, PutAccountPreferences | REST/JSON `/2015-02-01/*`; CreationToken idempotency; FileSystem deletion blocked when mount targets exist; Pro-only on LocalStack — free here |
| **EMR** | RunJobFlow, DescribeCluster, ListClusters, TerminateJobFlows, ModifyCluster, SetTerminationProtection, SetVisibleToAllUsers, AddJobFlowSteps, DescribeStep, ListSteps, CancelSteps, AddInstanceFleet, ListInstanceFleets, ModifyInstanceFleet, AddInstanceGroups, ListInstanceGroups, ModifyInstanceGroups, ListBootstrapActions, AddTags, RemoveTags, GetBlockPublicAccessConfiguration, PutBlockPublicAccessConfiguration | Control plane only — no real Spark/Hadoop; clusters start in WAITING (KeepAlive=true) or TERMINATED (KeepAlive=false); steps stored as COMPLETED immediately; all three instance modes (simple, InstanceGroups, InstanceFleets); TerminationProtected enforced; Pro-only on LocalStack — free here |
-| **Cognito** | **User Pools**: CreateUserPool, DeleteUserPool, DescribeUserPool, ListUserPools, UpdateUserPool, CreateUserPoolClient, DeleteUserPoolClient, DescribeUserPoolClient, ListUserPoolClients, UpdateUserPoolClient, AdminCreateUser, AdminDeleteUser, AdminGetUser, ListUsers, AdminSetUserPassword, AdminUpdateUserAttributes, AdminConfirmSignUp, AdminDisableUser, AdminEnableUser, AdminResetUserPassword, AdminUserGlobalSignOut, AdminAddUserToGroup, AdminRemoveUserFromGroup, AdminListGroupsForUser, AdminListUserAuthEvents, AdminInitiateAuth, AdminRespondToAuthChallenge, InitiateAuth, RespondToAuthChallenge, GlobalSignOut, RevokeToken, SignUp, ConfirmSignUp, ForgotPassword, ConfirmForgotPassword, ChangePassword, GetUser, UpdateUserAttributes, DeleteUser, CreateGroup, DeleteGroup, GetGroup, ListGroups, ListUsersInGroup, CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain, GetUserPoolMfaConfig, SetUserPoolMfaConfig, AssociateSoftwareToken, VerifySoftwareToken, AdminSetUserMFAPreference, SetUserMFAPreference, TagResource, UntagResource, ListTagsForResource; **Identity Pools**: CreateIdentityPool, DeleteIdentityPool, DescribeIdentityPool, ListIdentityPools, UpdateIdentityPool, GetId, GetCredentialsForIdentity, GetOpenIdToken, SetIdentityPoolRoles, GetIdentityPoolRoles, ListIdentities, DescribeIdentity, MergeDeveloperIdentities, UnlinkDeveloperIdentity, UnlinkIdentity, TagResource, UntagResource, ListTagsForResource; **OAuth2**: /oauth2/token (client_credentials) | Stub JWT tokens (structurally valid base64url JWTs); SRP auth returns PASSWORD_VERIFIER challenge; confirmation codes hardcoded (signup: 123456, forgot-password: 654321); TOTP SOFTWARE_TOKEN_MFA challenge flow; MFA config and per-user enrollment stored in-memory |
+| **Cognito** | **User Pools**: CreateUserPool, DeleteUserPool, DescribeUserPool, ListUserPools, UpdateUserPool, CreateUserPoolClient, DeleteUserPoolClient, DescribeUserPoolClient, ListUserPoolClients, UpdateUserPoolClient, AdminCreateUser, AdminDeleteUser, AdminGetUser, ListUsers, AdminSetUserPassword, AdminUpdateUserAttributes, AdminConfirmSignUp, AdminDisableUser, AdminEnableUser, AdminResetUserPassword, AdminUserGlobalSignOut, AdminAddUserToGroup, AdminRemoveUserFromGroup, AdminListGroupsForUser, AdminListUserAuthEvents, AdminInitiateAuth, AdminRespondToAuthChallenge, InitiateAuth, RespondToAuthChallenge, GlobalSignOut, RevokeToken, SignUp, ConfirmSignUp, ForgotPassword, ConfirmForgotPassword, ChangePassword, GetUser, UpdateUserAttributes, DeleteUser, CreateGroup, DeleteGroup, GetGroup, ListGroups, ListUsersInGroup, CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain, GetUserPoolMfaConfig, SetUserPoolMfaConfig, AssociateSoftwareToken, VerifySoftwareToken, AdminSetUserMFAPreference, SetUserMFAPreference, TagResource, UntagResource, ListTagsForResource; **Identity Pools**: CreateIdentityPool, DeleteIdentityPool, DescribeIdentityPool, ListIdentityPools, UpdateIdentityPool, GetId, GetCredentialsForIdentity, GetOpenIdToken, SetIdentityPoolRoles, GetIdentityPoolRoles, ListIdentities, DescribeIdentity, MergeDeveloperIdentities, UnlinkDeveloperIdentity, UnlinkIdentity, TagResource, UntagResource, ListTagsForResource; **OAuth2**: /oauth2/token (client_credentials) | Stub JWT tokens (structurally valid base64url JWTs); SRP auth returns PASSWORD_VERIFIER challenge; **CUSTOM_AUTH flow** wired through the configured `DefineAuthChallenge` / `CreateAuthChallenge` / `VerifyAuthChallengeResponse` Lambda triggers (passwordless / magic-link / SMS-OTP); session TTL honors `AuthSessionValidity`, capped at 3 answered rounds per AWS; confirmation codes hardcoded (signup: 123456, forgot-password: 654321); TOTP SOFTWARE_TOKEN_MFA challenge flow; MFA config and per-user enrollment stored in-memory |
| **ECR** | CreateRepository, DescribeRepositories, DeleteRepository, ListImages, DescribeImages, PutImage, BatchGetImage, BatchDeleteImage, GetAuthorizationToken, GetRepositoryPolicy, SetRepositoryPolicy, DeleteRepositoryPolicy, PutLifecyclePolicy, GetLifecyclePolicy, DeleteLifecyclePolicy, ListTagsForResource, TagResource, UntagResource, PutImageTagMutability, PutImageScanningConfiguration, DescribeRegistry, GetDownloadUrlForLayer, BatchCheckLayerAvailability, InitiateLayerUpload, UploadLayerPart, CompleteLayerUpload | In-memory image registry; Docker V2 manifest support; authorization token generation; lifecycle policies; tag mutability; Pro-only on LocalStack — free here |
| **AppSync** | **GraphQL APIs**: CreateGraphQLApi, GetGraphQLApi, ListGraphQLApis, UpdateGraphQLApi, DeleteGraphQLApi, CreateApiKey, DeleteApiKey, ListApiKeys, CreateDataSource, GetDataSource, ListDataSources, DeleteDataSource, CreateResolver, GetResolver, ListResolvers, DeleteResolver, CreateType, ListTypes, GetType, TagResource, UntagResource, ListTagsForResource; **Event APIs**: CreateApi, GetApi, ListApis, UpdateApi, DeleteApi, CreateChannelNamespace, GetChannelNamespace, ListChannelNamespaces, UpdateChannelNamespace, DeleteChannelNamespace, CreateApiKey, ListApiKeys, DeleteApiKey, HTTP Publish, WebSocket subscribe/publish | GraphQL queries/mutations execute against DynamoDB resolvers; Lambda resolvers supported. Event APIs support AWS-shaped `/v2/apis` management, `/v1/apis/{apiId}/apikeys` API-key operations, `POST /event` on `*.appsync-api.*`, and realtime `*.appsync-realtime-api.*` WebSocket flows with API-key and Lambda-authorizer checks |
| **Cloud Map** | CreateHttpNamespace, CreatePrivateDnsNamespace, CreatePublicDnsNamespace, GetNamespace, ListNamespaces, DeleteNamespace, UpdateHttpNamespace, UpdatePrivateDnsNamespace, UpdatePublicDnsNamespace, CreateService, GetService, ListServices, DeleteService, UpdateService, RegisterInstance, DeregisterInstance, DiscoverInstances, DiscoverInstancesRevision, ListInstances, GetInstancesHealthStatus, UpdateInstanceCustomHealthStatus, GetServiceAttributes, UpdateServiceAttributes, DeleteServiceAttributes, GetOperation, ListOperations, TagResource, UntagResource, ListTagsForResource | DNS namespaces create Route53 hosted zones; operation tracking; Terraform `aws_service_discovery_*` compatible |
@@ -511,7 +511,7 @@ Unsupported resource types fail with `CREATE_FAILED` (or `ROLLBACK_COMPLETE` if
| **Transfer Family** | CreateServer, DescribeServer, DeleteServer, ListServers, StartServer, StopServer, CreateUser, DescribeUser, DeleteUser, ListUsers, ImportSshPublicKey, DeleteSshPublicKey | 12 operations; **real SFTP listener** on `:2222` (override with `SFTP_PORT`) backed by S3 — `ls`, `put`, `get`, `mkdir`, `rename` work end-to-end against the local S3 emulator; `SFTP_PORT_PER_SERVER=1` allocates one port per `CreateServer` from `SFTP_BASE_PORT` (default 2300); SSH key auth scans every user across every server and account; `LOGICAL` and `PATH` home-directory mappings; host key persists across restarts when `PERSIST_STATE=1` |
| **IoT Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, CreateKeysAndCertificate, RegisterCertificate, UpdateCertificate, DeleteCertificate, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, DescribeEndpoint, Publish (HTTP), MQTT-over-WebSocket pub/sub | 24 operations + **real MQTT 3.1.1 over WebSocket** on the gateway port — clients use the address returned by `DescribeEndpoint`; local CA signs `CreateKeysAndCertificate` certificates (CA persists across restarts when `PERSIST_STATE=1`); multi-tenancy via transparent topic prefixing (same pattern as Transfer Family's shared SFTP listener); no plain TCP 1883 (real AWS IoT requires TLS or SigV4 on every connection); local CA cert available at `GET /_ministack/iot/ca.pem` for SDK trust configuration; IoT policies are stored but **not enforced** on the data plane |
| **EventBridge Scheduler** | CreateSchedule, GetSchedule, UpdateSchedule, DeleteSchedule, ListSchedules, CreateScheduleGroup, GetScheduleGroup, DeleteScheduleGroup, ListScheduleGroups, TagResource, UntagResource, ListTagsForResource | 12 actions; 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, 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); OIDC discovery + JWKS served at the cluster's `identity.oidc.issuer` URL so Terraform's `aws_iam_openid_connect_provider` (IRSA) works against ministack; CFN `AWS::EKS::Cluster` and `AWS::EKS::Nodegroup` supported |
+| **EKS** | CreateCluster, DescribeCluster, ListClusters, DeleteCluster, CreateNodegroup, DescribeNodegroup, ListNodegroups, DeleteNodegroup, CreateAddon, DescribeAddon, ListAddons, UpdateAddon, DeleteAddon, AssociateEncryptionConfig, CreateAccessEntry, DescribeAccessEntry, ListAccessEntries, UpdateAccessEntry, DeleteAccessEntry, AssociateAccessPolicy, DisassociateAccessPolicy, ListAssociatedAccessPolicies, 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; 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 | Single-master-account org auto-initialised on first call; nested OUs with `Path` field (additive 2026-03 AWS change); `FeatureSet=ALL` |
| **Account** | GetAccountInformation, GetContactInformation, ListRegions, GetRegionOptStatus | rest-json `/getAccountInformation`, etc.; returns `AccountState=ACTIVE` (additive 2026-04 AWS change); 31-region opt-in matrix |
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 522f8c4c..946cb1e1 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -2432,7 +2432,19 @@ def _admin_respond_to_auth_challenge(data):
return error_response_json("NotAuthorizedException",
"Incorrect username or password", 400)
- # Enforce the max challenge-attempts ceiling (AWS parity — issue #725 step 4)
+ # Check issueTokens FIRST — a correct answer on the Nth attempt must
+ # issue tokens even when N == MAX_CHALLENGE_ATTEMPTS. The cap is
+ # meant to prevent a NEXT (e.g. 4th) round of CreateAuthChallenge,
+ # not penalize success on the boundary attempt.
+ if define_resp.get("issueTokens"):
+ del _challenge_sessions[token]
+ return json_response({"AuthenticationResult": _build_auth_result(
+ session["pool_id"], session["client_id"], user
+ )})
+
+ # Enforce the max challenge-attempts ceiling (AWS parity — issue #725 step 4).
+ # Applied only after issueTokens has been ruled out so a correct
+ # answer on the cap-boundary attempt isn't silently rejected.
answered_count = sum(1 for c in session["challenges"]
if c.get("challengeResult") is not None)
if answered_count >= _MAX_CHALLENGE_ATTEMPTS:
@@ -2440,13 +2452,6 @@ def _admin_respond_to_auth_challenge(data):
return error_response_json("NotAuthorizedException",
"Max authentication attempts exceeded", 400)
- # Check if issueTokens
- if define_resp.get("issueTokens"):
- del _challenge_sessions[token]
- return json_response({"AuthenticationResult": _build_auth_result(
- session["pool_id"], session["client_id"], user
- )})
-
# Determine next challenge
next_challenge = define_resp.get("challengeName")
if next_challenge == "CUSTOM_CHALLENGE":
@@ -2778,7 +2783,19 @@ def _respond_to_auth_challenge(data):
return error_response_json("NotAuthorizedException",
"Incorrect username or password", 400)
- # Enforce the max challenge-attempts ceiling (AWS parity — issue #725 step 4)
+ # Check issueTokens FIRST — a correct answer on the Nth attempt must
+ # issue tokens even when N == MAX_CHALLENGE_ATTEMPTS. The cap is
+ # meant to prevent a NEXT (e.g. 4th) round of CreateAuthChallenge,
+ # not penalize success on the boundary attempt.
+ if define_resp.get("issueTokens"):
+ del _challenge_sessions[token]
+ return json_response({"AuthenticationResult": _build_auth_result(
+ session["pool_id"], session["client_id"], user
+ )})
+
+ # Enforce the max challenge-attempts ceiling (AWS parity — issue #725 step 4).
+ # Applied only after issueTokens has been ruled out so a correct
+ # answer on the cap-boundary attempt isn't silently rejected.
answered_count = sum(1 for c in session["challenges"]
if c.get("challengeResult") is not None)
if answered_count >= _MAX_CHALLENGE_ATTEMPTS:
@@ -2786,13 +2803,6 @@ def _respond_to_auth_challenge(data):
return error_response_json("NotAuthorizedException",
"Max authentication attempts exceeded", 400)
- # Check if issueTokens
- if define_resp.get("issueTokens"):
- del _challenge_sessions[token]
- return json_response({"AuthenticationResult": _build_auth_result(
- session["pool_id"], session["client_id"], user
- )})
-
# Determine next challenge
next_challenge = define_resp.get("challengeName")
if next_challenge == "CUSTOM_CHALLENGE":
diff --git a/ministack/services/eks.py b/ministack/services/eks.py
index 630de987..c34c7bb1 100644
--- a/ministack/services/eks.py
+++ b/ministack/services/eks.py
@@ -20,6 +20,7 @@ import os
import re
import threading
import time
+import urllib.parse
from ministack.core.persistence import load_state
from ministack.core.responses import (
@@ -53,6 +54,8 @@ except ImportError:
_clusters = AccountScopedDict() # name -> cluster record
_nodegroups = AccountScopedDict() # "cluster/nodegroup" -> nodegroup record
_addons = AccountScopedDict() # "cluster/addonName" -> addon record
+_access_entries = AccountScopedDict() # "cluster\x00principalArn" -> access entry record
+_access_policies = AccountScopedDict()# "cluster\x00principalArn\x00policyArn" -> associated policy
_tags = AccountScopedDict() # arn -> {key: value}
_port_counter_lock = threading.Lock()
_port_counter = [EKS_BASE_PORT]
@@ -109,6 +112,8 @@ def reset():
_clusters.clear()
_nodegroups.clear()
_addons.clear()
+ _access_entries.clear()
+ _access_policies.clear()
_tags.clear()
_port_counter[0] = EKS_BASE_PORT
_stop_all_k3s()
@@ -127,6 +132,8 @@ def get_state():
"clusters": clusters,
"nodegroups": copy.deepcopy(_nodegroups),
"addons": copy.deepcopy(_addons),
+ "access_entries": copy.deepcopy(_access_entries),
+ "access_policies": copy.deepcopy(_access_policies),
"tags": copy.deepcopy(_tags),
"port_counter": _port_counter[0],
}
@@ -136,6 +143,8 @@ def restore_state(data):
_clusters.update(data.get("clusters", {}))
_nodegroups.update(data.get("nodegroups", {}))
_addons.update(data.get("addons", {}))
+ _access_entries.update(data.get("access_entries", {}))
+ _access_policies.update(data.get("access_policies", {}))
_tags.update(data.get("tags", {}))
if "port_counter" in data:
_port_counter[0] = data["port_counter"]
@@ -181,6 +190,22 @@ def _addon_arn(cluster_name, addon_name):
return f"arn:aws:eks:{get_region()}:{get_account_id()}:addon/{cluster_name}/{addon_name}/{new_uuid()[:8]}"
+def _access_entry_arn(cluster_name, principal_arn):
+ # AWS: arn:aws:eks:{region}:{account}:access-entry/{cluster}/{principalArnId}/{uuid}.
+ return (
+ f"arn:aws:eks:{get_region()}:{get_account_id()}:"
+ f"access-entry/{cluster_name}/{new_uuid()[:8]}"
+ )
+
+
+def _ae_key(cluster_name: str, principal_arn: str) -> str:
+ return f"{cluster_name}\x00{principal_arn}"
+
+
+def _ap_key(cluster_name: str, principal_arn: str, policy_arn: str) -> str:
+ return f"{cluster_name}\x00{principal_arn}\x00{policy_arn}"
+
+
def _now():
return int(time.time())
@@ -634,6 +659,174 @@ def _update_addon(cluster_name, addon_name, body):
return _json_resp(200, {"update": update})
+# ---------------------------------------------------------------------------
+# Access Entries (modern EKS IAM bindings — replace aws-auth ConfigMap)
+# ---------------------------------------------------------------------------
+
+_VALID_ACCESS_ENTRY_TYPES = (
+ "STANDARD", "EC2_LINUX", "EC2_WINDOWS", "FARGATE_LINUX",
+)
+
+
+def _build_access_entry(cluster_name, principal_arn, body):
+ now = _now()
+ return {
+ "clusterName": cluster_name,
+ "principalArn": principal_arn,
+ "kubernetesGroups": body.get("kubernetesGroups", []),
+ "accessEntryArn": _access_entry_arn(cluster_name, principal_arn),
+ "createdAt": now,
+ "modifiedAt": now,
+ "tags": body.get("tags", {}),
+ "username": body.get("username", ""),
+ "type": body.get("type", "STANDARD"),
+ }
+
+
+def _create_access_entry(cluster_name, body):
+ if cluster_name not in _clusters:
+ return _error(404, "ResourceNotFoundException",
+ f"No cluster found for name: {cluster_name}.")
+ principal_arn = body.get("principalArn", "")
+ if not principal_arn:
+ return _error(400, "InvalidParameterException",
+ "principalArn is required.")
+ ae_type = body.get("type", "STANDARD")
+ if ae_type not in _VALID_ACCESS_ENTRY_TYPES:
+ return _error(400, "InvalidParameterException",
+ f"Invalid type {ae_type}. Must be one of "
+ f"{list(_VALID_ACCESS_ENTRY_TYPES)}.")
+ key = _ae_key(cluster_name, principal_arn)
+ if key in _access_entries:
+ return _error(409, "ResourceInUseException",
+ f"Access entry already exists for principal {principal_arn}.")
+ entry = _build_access_entry(cluster_name, principal_arn, body)
+ _access_entries[key] = entry
+ if entry["tags"]:
+ _tags[entry["accessEntryArn"]] = dict(entry["tags"])
+ return _json_resp(200, {"accessEntry": entry})
+
+
+def _describe_access_entry(cluster_name, principal_arn):
+ entry = _access_entries.get(_ae_key(cluster_name, principal_arn))
+ if not entry:
+ return _error(404, "ResourceNotFoundException",
+ f"No access entry for principal {principal_arn}.")
+ return _json_resp(200, {"accessEntry": entry})
+
+
+def _list_access_entries(cluster_name, query):
+ if cluster_name not in _clusters:
+ return _error(404, "ResourceNotFoundException",
+ f"No cluster found for name: {cluster_name}.")
+ prefix = f"{cluster_name}\x00"
+ associated = query.get("associatedPolicyArn")
+ arns = []
+ for k, e in _access_entries.items():
+ if not k.startswith(prefix):
+ continue
+ if associated:
+ # Only include entries that have this policy associated.
+ if not any(
+ ak.startswith(f"{cluster_name}\x00{e['principalArn']}\x00")
+ and ak.endswith(f"\x00{associated}")
+ for ak in _access_policies
+ ):
+ continue
+ arns.append(e["principalArn"])
+ max_results = int(query.get("maxResults", 100))
+ return _json_resp(200, {"accessEntries": arns[:max_results]})
+
+
+def _delete_access_entry(cluster_name, principal_arn):
+ key = _ae_key(cluster_name, principal_arn)
+ entry = _access_entries.get(key)
+ if not entry:
+ return _error(404, "ResourceNotFoundException",
+ f"No access entry for principal {principal_arn}.")
+ # Cascading: drop associated access policies for this entry.
+ ap_prefix = f"{cluster_name}\x00{principal_arn}\x00"
+ for ak in [k for k in _access_policies if k.startswith(ap_prefix)]:
+ _access_policies.pop(ak, None)
+ _tags.pop(entry.get("accessEntryArn", ""), None)
+ _access_entries.pop(key, None)
+ return _json_resp(200, {})
+
+
+def _update_access_entry(cluster_name, principal_arn, body):
+ key = _ae_key(cluster_name, principal_arn)
+ entry = _access_entries.get(key)
+ if not entry:
+ return _error(404, "ResourceNotFoundException",
+ f"No access entry for principal {principal_arn}.")
+ # AWS-allowed update fields only (per botocore model).
+ for field in ("kubernetesGroups", "username"):
+ if field in body:
+ entry[field] = body[field]
+ entry["modifiedAt"] = _now()
+ return _json_resp(200, {"accessEntry": entry})
+
+
+def _associate_access_policy(cluster_name, principal_arn, body):
+ if _ae_key(cluster_name, principal_arn) not in _access_entries:
+ return _error(404, "ResourceNotFoundException",
+ f"No access entry for principal {principal_arn}.")
+ policy_arn = body.get("policyArn", "")
+ if not policy_arn:
+ return _error(400, "InvalidParameterException",
+ "policyArn is required.")
+ access_scope = body.get("accessScope") or {}
+ scope_type = access_scope.get("type")
+ if scope_type not in ("cluster", "namespace"):
+ return _error(400, "InvalidParameterException",
+ "accessScope.type must be 'cluster' or 'namespace'.")
+ if scope_type == "namespace" and not access_scope.get("namespaces"):
+ return _error(400, "InvalidParameterException",
+ "namespaces is required when accessScope.type is 'namespace'.")
+ now = _now()
+ associated = {
+ "policyArn": policy_arn,
+ "accessScope": {
+ "type": scope_type,
+ "namespaces": access_scope.get("namespaces", []),
+ },
+ "associatedAt": now,
+ "modifiedAt": now,
+ }
+ _access_policies[_ap_key(cluster_name, principal_arn, policy_arn)] = associated
+ return _json_resp(200, {
+ "clusterName": cluster_name,
+ "principalArn": principal_arn,
+ "associatedAccessPolicy": associated,
+ })
+
+
+def _disassociate_access_policy(cluster_name, principal_arn, policy_arn):
+ if _ae_key(cluster_name, principal_arn) not in _access_entries:
+ return _error(404, "ResourceNotFoundException",
+ f"No access entry for principal {principal_arn}.")
+ key = _ap_key(cluster_name, principal_arn, policy_arn)
+ if key not in _access_policies:
+ return _error(404, "ResourceNotFoundException",
+ f"Policy {policy_arn} is not associated with {principal_arn}.")
+ _access_policies.pop(key, None)
+ return _json_resp(200, {})
+
+
+def _list_associated_access_policies(cluster_name, principal_arn, query):
+ if _ae_key(cluster_name, principal_arn) not in _access_entries:
+ return _error(404, "ResourceNotFoundException",
+ f"No access entry for principal {principal_arn}.")
+ prefix = f"{cluster_name}\x00{principal_arn}\x00"
+ policies = [p for k, p in _access_policies.items() if k.startswith(prefix)]
+ max_results = int(query.get("maxResults", 100))
+ return _json_resp(200, {
+ "clusterName": cluster_name,
+ "principalArn": principal_arn,
+ "associatedAccessPolicies": policies[:max_results],
+ })
+
+
# ---------------------------------------------------------------------------
# Encryption config (AssociateEncryptionConfig)
# ---------------------------------------------------------------------------
@@ -819,6 +1012,56 @@ async def handle_request(method, path, headers, body_bytes, query_params):
if method == "DELETE":
return _delete_addon(cluster_name, addon_name)
+ # Access Entries. botocore sends principalArn raw in the path (includes
+ # colons and forward slashes from the ARN, e.g.
+ # ``arn:aws:iam::000000000000:role/foo``), so the regex must accept
+ # slashes. Most-specific routes first; non-greedy `.+?` against the
+ # ``/access-policies`` suffix prevents the principalArn capture from
+ # swallowing the policy segment.
+ # DELETE /clusters/{name}/access-entries/{principalArn}/access-policies/{policyArn}
+ m = re.fullmatch(
+ r"/clusters/([A-Za-z0-9_-]+)/access-entries/(.+?)/access-policies/(.+)", path)
+ if m:
+ cluster_name = m.group(1)
+ principal_arn = urllib.parse.unquote(m.group(2))
+ policy_arn = urllib.parse.unquote(m.group(3))
+ if method == "DELETE":
+ return _disassociate_access_policy(cluster_name, principal_arn, policy_arn)
+
+ # POST/GET /clusters/{name}/access-entries/{principalArn}/access-policies
+ m = re.fullmatch(
+ r"/clusters/([A-Za-z0-9_-]+)/access-entries/(.+?)/access-policies", path)
+ if m:
+ cluster_name = m.group(1)
+ principal_arn = urllib.parse.unquote(m.group(2))
+ if method == "POST":
+ return _associate_access_policy(cluster_name, principal_arn, body)
+ if method == "GET":
+ return _list_associated_access_policies(cluster_name, principal_arn, query)
+
+ # POST/GET /clusters/{name}/access-entries — CreateAccessEntry / ListAccessEntries
+ m = re.fullmatch(r"/clusters/([A-Za-z0-9_-]+)/access-entries", path)
+ if m:
+ cluster_name = m.group(1)
+ if method == "POST":
+ return _create_access_entry(cluster_name, body)
+ if method == "GET":
+ return _list_access_entries(cluster_name, query)
+
+ # /clusters/{name}/access-entries/{principalArn} — Describe / Update / Delete.
+ # Greedy `.+` is safe here only because the more-specific
+ # `/access-policies` routes above already matched and returned.
+ m = re.fullmatch(r"/clusters/([A-Za-z0-9_-]+)/access-entries/(.+)", path)
+ if m:
+ cluster_name = m.group(1)
+ principal_arn = urllib.parse.unquote(m.group(2))
+ if method == "GET":
+ return _describe_access_entry(cluster_name, principal_arn)
+ if method == "POST":
+ return _update_access_entry(cluster_name, principal_arn, body)
+ if method == "DELETE":
+ return _delete_access_entry(cluster_name, principal_arn)
+
# Tags: /tags/{arn+}
if path.startswith("/tags/"):
arn = path[6:]
diff --git a/ministack/services/firehose.py b/ministack/services/firehose.py
index b99b94d9..39b7a68b 100644
--- a/ministack/services/firehose.py
+++ b/ministack/services/firehose.py
@@ -199,6 +199,117 @@ def _resolve_dest_update_config(data: dict):
return None, None
+def _apply_lambda_processors(stream: dict, dest: dict, records: list) -> list:
+ """Apply a destination's ProcessingConfiguration Lambda processors to a
+ batch of records.
+
+ ``records``: list of ``(recordId, raw_bytes)`` — pre-decoded so the
+ Lambda invocation matches AWS's contract (base64 over the wire).
+
+ Returns the post-processing list of ``(recordId, raw_bytes)`` to deliver
+ downstream. Per the AWS Firehose Lambda processor contract:
+ - ``result == "Ok"`` → use the Lambda's returned (base64) data.
+ - ``result == "Dropped"`` → omit from the output entirely.
+ - ``result == "ProcessingFailed"`` → omit; AWS routes to the
+ S3 backup destination if configured (ministack: omit + warn).
+
+ On any Lambda lookup / invocation / response-parsing error the original
+ record is passed through. Firehose is best-effort by AWS contract — a
+ processor problem must never break the producer side.
+ """
+ cfg = (dest.get("config") or {}).get("ProcessingConfiguration") or {}
+ if not cfg.get("Enabled"):
+ return records
+ processors = cfg.get("Processors") or []
+ lambda_arns = []
+ for proc in processors:
+ if proc.get("Type") != "Lambda":
+ continue
+ for p in proc.get("Parameters") or []:
+ if p.get("ParameterName") == "LambdaArn":
+ arn = p.get("ParameterValue", "")
+ if arn:
+ lambda_arns.append(arn)
+ break
+ if not lambda_arns:
+ return records
+
+ from ministack.services import lambda_svc
+ current = list(records)
+ stream_arn = stream.get("arn", "")
+ stream_name = stream.get("name", "?")
+ for arn in lambda_arns:
+ try:
+ name, qualifier = lambda_svc._resolve_name_and_qualifier(arn)
+ func_record, _ = lambda_svc._get_func_record_for_qualifier(name, qualifier)
+ except Exception:
+ func_record = None
+ if func_record is None:
+ logger.warning(
+ "Firehose %s: processor Lambda %s not found; passing records through",
+ stream_name, arn,
+ )
+ continue
+ now_ms = int(time.time() * 1000)
+ event = {
+ "invocationId": new_uuid(),
+ "deliveryStreamArn": stream_arn,
+ "region": get_region(),
+ "records": [
+ {
+ "recordId": rid,
+ "approximateArrivalTimestamp": now_ms,
+ "data": base64.b64encode(raw).decode(),
+ }
+ for rid, raw in current
+ ],
+ }
+ try:
+ result = lambda_svc._execute_function(func_record, event)
+ except Exception as exc:
+ logger.warning("Firehose %s: processor Lambda %s invocation failed: %s; passing through",
+ stream_name, arn, exc)
+ continue
+ if result.get("error"):
+ logger.warning("Firehose %s: processor Lambda %s returned error: %s; passing through",
+ stream_name, arn, result.get("body"))
+ continue
+ body = result.get("body")
+ if isinstance(body, (str, bytes)):
+ try:
+ body = json.loads(body)
+ except (ValueError, TypeError):
+ body = None
+ if not isinstance(body, dict) or "records" not in body:
+ logger.warning("Firehose %s: processor Lambda %s returned malformed body; passing through",
+ stream_name, arn)
+ continue
+ by_id = {r.get("recordId"): r for r in body.get("records", []) if isinstance(r, dict)}
+ next_round = []
+ for rid, raw in current:
+ r = by_id.get(rid)
+ if r is None:
+ # Lambda didn't include this recordId — treat as pass-through
+ # rather than silently dropping.
+ next_round.append((rid, raw))
+ continue
+ outcome = r.get("result", "Ok")
+ if outcome in ("Dropped", "ProcessingFailed"):
+ continue
+ new_data_b64 = r.get("data")
+ if new_data_b64:
+ try:
+ next_round.append((rid, base64.b64decode(new_data_b64)))
+ continue
+ except Exception:
+ pass
+ next_round.append((rid, raw))
+ current = next_round
+ if not current:
+ break
+ return current
+
+
def _deliver_to_s3(stream: dict, dest: dict, record_data: bytes):
"""Best-effort delivery of a record to the local S3 emulator.
@@ -280,10 +391,13 @@ def ingest_from_kinesis_source(stream_arn: str, records: list) -> None:
for _pkey, raw in records:
rid = _record_id()
dest["records"].append({"id": rid, "data": raw, "ts": now_ts})
- plan.append((stream, dest, raw))
- for stream, dest, raw in plan:
+ plan.append((stream, dest, rid, raw))
+ for stream, dest, rid, raw in plan:
try:
- _deliver_to_s3(stream, dest, raw)
+ for _rid, payload in _apply_lambda_processors(
+ stream, dest, [(rid, raw)]
+ ):
+ _deliver_to_s3(stream, dest, payload)
except Exception as exc:
logger.warning(
"Firehose Kinesis-source delivery to %s failed: %s",
@@ -431,7 +545,11 @@ def _put_record(data: dict):
for dest in stream["destinations"]:
dest["records"].append({"id": record_id, "data": raw_data, "ts": now_epoch()})
if dest["type"] in ("ExtendedS3", "S3"):
- _deliver_to_s3(stream, dest, decoded)
+ # Apply ProcessingConfiguration.Lambda transforms before S3.
+ for _rid, payload in _apply_lambda_processors(
+ stream, dest, [(record_id, decoded)]
+ ):
+ _deliver_to_s3(stream, dest, payload)
return json_response({"RecordId": record_id, "Encrypted": False})
@@ -464,7 +582,10 @@ def _put_record_batch(data: dict):
for dest in stream["destinations"]:
dest["records"].append({"id": record_id, "data": raw_data, "ts": now_epoch()})
if dest["type"] in ("ExtendedS3", "S3"):
- _deliver_to_s3(stream, dest, decoded)
+ for _rid, payload in _apply_lambda_processors(
+ stream, dest, [(record_id, decoded)]
+ ):
+ _deliver_to_s3(stream, dest, payload)
responses.append({"RecordId": record_id, "Encrypted": False})
except Exception as e:
failed += 1
diff --git a/pyproject.toml b/pyproject.toml
index 71bb6d34..a6bca841 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.3.55"
+version = "1.3.56"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_cognito_custom_auth.py b/tests/test_cognito_custom_auth.py
index 6a2648ee..0a2f3c5f 100644
--- a/tests/test_cognito_custom_auth.py
+++ b/tests/test_cognito_custom_auth.py
@@ -1030,6 +1030,68 @@ def test_custom_auth_max_attempts_exceeded(cognito_idp, lam):
assert last_exc.response["Error"]["Code"] == "NotAuthorizedException"
+# ── Test: issueTokens on cap-boundary attempt must win over MaxAttempts ──────
+
+def test_custom_auth_issue_tokens_on_third_attempt_boundary(cognito_idp, lam):
+ """A correct answer on attempt N == MAX_CHALLENGE_ATTEMPTS must issue
+ tokens, not be rejected for hitting the cap.
+
+ Regression for the order-of-checks bug: the cap is meant to prevent a
+ NEXT (4th) round, not penalize success on the boundary. Define returns
+ issueTokens=True only after the 3rd answer; the prior buggy ordering
+ rejected with `Max authentication attempts exceeded` before reaching the
+ issueTokens branch.
+ """
+ create_handler = (
+ "def handler(event, ctx):\n"
+ " event['response']['publicChallengeParameters'] = {'challenge': 'TEST'}\n"
+ " return event\n"
+ )
+ verify_handler = (
+ "def handler(event, ctx):\n"
+ " event['response']['answerCorrect'] = True\n"
+ " return event\n"
+ )
+ define_handler = (
+ "def handler(event, ctx):\n"
+ " answered = sum(1 for c in event['request']['session']"
+ " if c.get('challengeResult') is not None)\n"
+ # Issue tokens exactly on the 3rd answered attempt (cap boundary).
+ " if answered >= 3:\n"
+ " event['response']['issueTokens'] = True\n"
+ " else:\n"
+ " event['response']['challengeName'] = 'CUSTOM_CHALLENGE'\n"
+ " return event\n"
+ )
+ create_arn = _create_lambda(lam, "create-boundary", create_handler)
+ verify_arn = _create_lambda(lam, "verify-boundary", verify_handler)
+ define_arn = _create_lambda(lam, "define-boundary", define_handler)
+
+ pid, cid = _setup_pool(cognito_idp, "BoundaryPool", {
+ "CreateAuthChallenge": create_arn,
+ "VerifyAuthChallengeResponse": verify_arn,
+ "DefineAuthChallenge": define_arn,
+ })
+
+ step = cognito_idp.initiate_auth(
+ ClientId=cid, AuthFlow="CUSTOM_AUTH",
+ AuthParameters={"USERNAME": "[email protected]"},
+ )
+ session = step["Session"]
+ # Answer 3 times — the 3rd must issue tokens, not hit the cap.
+ last = None
+ for i in range(3):
+ last = cognito_idp.respond_to_auth_challenge(
+ ClientId=cid,
+ ChallengeName="CUSTOM_CHALLENGE",
+ Session=session,
+ ChallengeResponses={"ANSWER": f"attempt{i}", "USERNAME": "[email protected]"},
+ )
+ session = last.get("Session", session)
+ assert "AuthenticationResult" in last, last
+ assert last["AuthenticationResult"].get("AccessToken")
+
+
# ── Test 30: Issue #725 reproduction ─────────────────────────────────────────
def test_custom_auth_issue_725_repro(cognito_idp, lam):
diff --git a/tests/test_eks.py b/tests/test_eks.py
index 94285ebc..20f3362f 100644
--- a/tests/test_eks.py
+++ b/tests/test_eks.py
@@ -473,3 +473,184 @@ def test_eks_oidc_discovery_document(eks):
finally:
try: eks.delete_cluster(name=cn)
except Exception: pass
+
+
+# ---------------------------------------------------------------------------
+# Access Entries — modern EKS IAM bindings (replace aws-auth ConfigMap).
+# Crossplane / Terraform `aws_eks_access_entry` + `aws_eks_access_policy_association`
+# both flow through these APIs.
+# ---------------------------------------------------------------------------
+
+
+def _create_basic_cluster(eks):
+ cn = f"ae-{_uid()}"
+ eks.create_cluster(
+ name=cn, roleArn="arn:aws:iam::000000000000:role/eks",
+ resourcesVpcConfig={"subnetIds": ["subnet-1"]},
+ )
+ return cn
+
+
+def test_eks_access_entry_create_describe_delete(eks):
+ cn = _create_basic_cluster(eks)
+ principal = f"arn:aws:iam::000000000000:user/test-{_uid()}"
+ try:
+ resp = eks.create_access_entry(
+ clusterName=cn, principalArn=principal,
+ kubernetesGroups=["admins"], username="admin",
+ type="STANDARD",
+ )
+ ae = resp["accessEntry"]
+ assert ae["clusterName"] == cn
+ assert ae["principalArn"] == principal
+ assert ae["kubernetesGroups"] == ["admins"]
+ assert ae["username"] == "admin"
+ assert ae["type"] == "STANDARD"
+ assert ae["accessEntryArn"].startswith(
+ f"arn:aws:eks:{REGION}:")
+
+ desc = eks.describe_access_entry(
+ clusterName=cn, principalArn=principal)["accessEntry"]
+ assert desc["principalArn"] == principal
+
+ # Delete returns empty body.
+ eks.delete_access_entry(clusterName=cn, principalArn=principal)
+ with pytest.raises(ClientError) as e:
+ eks.describe_access_entry(
+ clusterName=cn, principalArn=principal)
+ assert e.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ finally:
+ try: eks.delete_cluster(name=cn)
+ except Exception: pass
+
+
+def test_eks_access_entry_create_duplicate_rejected(eks):
+ cn = _create_basic_cluster(eks)
+ principal = f"arn:aws:iam::000000000000:role/dup-{_uid()}"
+ try:
+ eks.create_access_entry(clusterName=cn, principalArn=principal)
+ with pytest.raises(ClientError) as e:
+ eks.create_access_entry(clusterName=cn, principalArn=principal)
+ assert e.value.response["Error"]["Code"] == "ResourceInUseException"
+ finally:
+ try: eks.delete_cluster(name=cn)
+ except Exception: pass
+
+
+def test_eks_access_entry_create_missing_cluster(eks):
+ bogus = f"no-such-{_uid()}"
+ with pytest.raises(ClientError) as e:
+ eks.create_access_entry(
+ clusterName=bogus,
+ principalArn="arn:aws:iam::000000000000:role/r")
+ assert e.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_eks_access_entry_list_returns_principal_arns(eks):
+ cn = _create_basic_cluster(eks)
+ p1 = f"arn:aws:iam::000000000000:role/list-1-{_uid()}"
+ p2 = f"arn:aws:iam::000000000000:role/list-2-{_uid()}"
+ try:
+ eks.create_access_entry(clusterName=cn, principalArn=p1)
+ eks.create_access_entry(clusterName=cn, principalArn=p2)
+ listed = eks.list_access_entries(clusterName=cn)["accessEntries"]
+ assert set(listed) == {p1, p2}
+ finally:
+ try: eks.delete_cluster(name=cn)
+ except Exception: pass
+
+
+def test_eks_access_entry_update_patches_allowed_fields(eks):
+ cn = _create_basic_cluster(eks)
+ principal = f"arn:aws:iam::000000000000:role/upd-{_uid()}"
+ try:
+ eks.create_access_entry(
+ clusterName=cn, principalArn=principal,
+ kubernetesGroups=["before"], username="old",
+ )
+ updated = eks.update_access_entry(
+ clusterName=cn, principalArn=principal,
+ kubernetesGroups=["after"], username="new",
+ )["accessEntry"]
+ assert updated["kubernetesGroups"] == ["after"]
+ assert updated["username"] == "new"
+ finally:
+ try: eks.delete_cluster(name=cn)
+ except Exception: pass
+
+
+def test_eks_associate_access_policy_full_cycle(eks):
+ cn = _create_basic_cluster(eks)
+ principal = f"arn:aws:iam::000000000000:role/policy-{_uid()}"
+ policy = ("arn:aws:eks::aws:cluster-access-policy/"
+ "AmazonEKSClusterAdminPolicy")
+ try:
+ eks.create_access_entry(clusterName=cn, principalArn=principal)
+
+ resp = eks.associate_access_policy(
+ clusterName=cn, principalArn=principal,
+ policyArn=policy,
+ accessScope={"type": "cluster", "namespaces": []},
+ )
+ ap = resp["associatedAccessPolicy"]
+ assert ap["policyArn"] == policy
+ assert ap["accessScope"]["type"] == "cluster"
+
+ listed = eks.list_associated_access_policies(
+ clusterName=cn, principalArn=principal,
+ )["associatedAccessPolicies"]
+ assert len(listed) == 1
+ assert listed[0]["policyArn"] == policy
+
+ eks.disassociate_access_policy(
+ clusterName=cn, principalArn=principal, policyArn=policy)
+ listed_after = eks.list_associated_access_policies(
+ clusterName=cn, principalArn=principal,
+ )["associatedAccessPolicies"]
+ assert listed_after == []
+ finally:
+ try: eks.delete_cluster(name=cn)
+ except Exception: pass
+
+
+def test_eks_associate_access_policy_namespace_scope_requires_namespaces(eks):
+ cn = _create_basic_cluster(eks)
+ principal = f"arn:aws:iam::000000000000:role/ns-{_uid()}"
+ policy = ("arn:aws:eks::aws:cluster-access-policy/"
+ "AmazonEKSEditPolicy")
+ try:
+ eks.create_access_entry(clusterName=cn, principalArn=principal)
+ with pytest.raises(ClientError) as e:
+ eks.associate_access_policy(
+ clusterName=cn, principalArn=principal,
+ policyArn=policy,
+ accessScope={"type": "namespace"}, # missing namespaces
+ )
+ assert e.value.response["Error"]["Code"] == "InvalidParameterException"
+ finally:
+ try: eks.delete_cluster(name=cn)
+ except Exception: pass
+
+
+def test_eks_delete_access_entry_cascades_associated_policies(eks):
+ cn = _create_basic_cluster(eks)
+ principal = f"arn:aws:iam::000000000000:role/casc-{_uid()}"
+ policy = ("arn:aws:eks::aws:cluster-access-policy/"
+ "AmazonEKSViewPolicy")
+ try:
+ eks.create_access_entry(clusterName=cn, principalArn=principal)
+ eks.associate_access_policy(
+ clusterName=cn, principalArn=principal,
+ policyArn=policy,
+ accessScope={"type": "cluster", "namespaces": []},
+ )
+ eks.delete_access_entry(clusterName=cn, principalArn=principal)
+ # Recreate to verify the policy was cascaded out (not lingering).
+ eks.create_access_entry(clusterName=cn, principalArn=principal)
+ listed = eks.list_associated_access_policies(
+ clusterName=cn, principalArn=principal,
+ )["associatedAccessPolicies"]
+ assert listed == []
+ finally:
+ try: eks.delete_cluster(name=cn)
+ except Exception: pass
diff --git a/tests/test_firehose.py b/tests/test_firehose.py
index 5a322da7..6cfbe416 100644
--- a/tests/test_firehose.py
+++ b/tests/test_firehose.py
@@ -385,3 +385,224 @@ def test_firehose_kinesis_stream_as_source_fans_out_to_s3(fh, kin, s3):
except Exception: pass
try: kin.delete_stream(StreamName=stream_name)
except Exception: pass
+
+
+# ---------------------------------------------------------------------------
+# ProcessingConfiguration — Lambda processor invocation.
+#
+# Real AWS Firehose invokes the configured Lambda for every batch of records
+# in flight, with payload shape:
+# {invocationId, deliveryStreamArn, region, records:[{recordId, approximateArrivalTimestamp, data(base64)}]}
+# and expects a response shape:
+# {records:[{recordId, result:"Ok"|"Dropped"|"ProcessingFailed", data(base64)}]}
+# Records marked Dropped/ProcessingFailed are not written to the destination;
+# Ok records are written with the transformed data. On any Lambda failure
+# Firehose passes records through unchanged (best-effort by AWS contract).
+# ---------------------------------------------------------------------------
+
+
+def _processor_lambda_zip(handler_src: str) -> bytes:
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", handler_src)
+ return buf.getvalue()
+
+
+def _make_processor_fn(lam, name: str, handler_src: str) -> str:
+ lam.create_function(
+ FunctionName=name,
+ Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/r",
+ Handler="index.handler",
+ Code={"ZipFile": _processor_lambda_zip(handler_src)},
+ )
+ return f"arn:aws:lambda:us-east-1:000000000000:function:{name}"
+
+
+def _create_firehose_with_processor(fh, name: str, bucket: str, lambda_arn: str,
+ delivery_type: str = "DirectPut",
+ kinesis_arn: str | None = None) -> None:
+ ext_s3 = {
+ "BucketARN": f"arn:aws:s3:::{bucket}",
+ "RoleARN": "arn:aws:iam::000000000000:role/firehose-role",
+ "BufferingHints": {"SizeInMBs": 1, "IntervalInSeconds": 1},
+ "CompressionFormat": "UNCOMPRESSED",
+ "Prefix": "out/",
+ "ProcessingConfiguration": {
+ "Enabled": True,
+ "Processors": [{
+ "Type": "Lambda",
+ "Parameters": [
+ {"ParameterName": "LambdaArn", "ParameterValue": lambda_arn},
+ ],
+ }],
+ },
+ }
+ if delivery_type == "KinesisStreamAsSource" and kinesis_arn:
+ fh.create_delivery_stream(
+ DeliveryStreamName=name,
+ DeliveryStreamType="KinesisStreamAsSource",
+ KinesisStreamSourceConfiguration={
+ "KinesisStreamARN": kinesis_arn,
+ "RoleARN": "arn:aws:iam::000000000000:role/firehose-role",
+ },
+ ExtendedS3DestinationConfiguration=ext_s3,
+ )
+ else:
+ fh.create_delivery_stream(
+ DeliveryStreamName=name,
+ DeliveryStreamType="DirectPut",
+ ExtendedS3DestinationConfiguration=ext_s3,
+ )
+
+
+def test_firehose_lambda_processor_transforms_record(fh, s3, lam):
+ """Lambda processor returns transformed data → S3 object contains the
+ transform output, not the original record."""
+ import base64 as _b64
+ suffix = _uuid_mod.uuid4().hex[:8]
+ bucket = f"fh-proc-{suffix}"
+ fn = f"fh-proc-fn-{suffix}"
+ delivery = f"fh-proc-{suffix}"
+ s3.create_bucket(Bucket=bucket)
+ handler = (
+ "import base64, json\n"
+ "def handler(event, context):\n"
+ " out = []\n"
+ " for r in event['records']:\n"
+ " raw = base64.b64decode(r['data'])\n"
+ " transformed = raw.upper()\n"
+ " out.append({\n"
+ " 'recordId': r['recordId'],\n"
+ " 'result': 'Ok',\n"
+ " 'data': base64.b64encode(transformed).decode(),\n"
+ " })\n"
+ " return {'records': out}\n"
+ )
+ arn = _make_processor_fn(lam, fn, handler)
+ _create_firehose_with_processor(fh, delivery, bucket, arn)
+ try:
+ fh.put_record(DeliveryStreamName=delivery, Record={"Data": b"hello"})
+ for _ in range(20):
+ objs = s3.list_objects_v2(Bucket=bucket, Prefix="out/").get("Contents", [])
+ if objs:
+ break
+ time.sleep(0.1)
+ objs = s3.list_objects_v2(Bucket=bucket, Prefix="out/").get("Contents", [])
+ assert len(objs) == 1, f"expected 1 transformed record, got {len(objs)}"
+ body = s3.get_object(Bucket=bucket, Key=objs[0]["Key"])["Body"].read()
+ assert body == b"HELLO", body
+ finally:
+ try: fh.delete_delivery_stream(DeliveryStreamName=delivery)
+ except Exception: pass
+ try: lam.delete_function(FunctionName=fn)
+ except Exception: pass
+
+
+def test_firehose_lambda_processor_dropped_record_not_written(fh, s3, lam):
+ """``result: Dropped`` → record is filtered out, no S3 object written."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ bucket = f"fh-drop-{suffix}"
+ fn = f"fh-drop-fn-{suffix}"
+ delivery = f"fh-drop-{suffix}"
+ s3.create_bucket(Bucket=bucket)
+ handler = (
+ "def handler(event, context):\n"
+ " return {'records': [\n"
+ " {'recordId': r['recordId'], 'result': 'Dropped', 'data': r['data']}\n"
+ " for r in event['records']\n"
+ " ]}\n"
+ )
+ arn = _make_processor_fn(lam, fn, handler)
+ _create_firehose_with_processor(fh, delivery, bucket, arn)
+ try:
+ fh.put_record(DeliveryStreamName=delivery, Record={"Data": b"hello"})
+ time.sleep(0.6) # give the fire-and-forget S3 task time
+ objs = s3.list_objects_v2(Bucket=bucket, Prefix="out/").get("Contents", [])
+ assert objs == [], f"expected no S3 objects, got {objs}"
+ finally:
+ try: fh.delete_delivery_stream(DeliveryStreamName=delivery)
+ except Exception: pass
+ try: lam.delete_function(FunctionName=fn)
+ except Exception: pass
+
+
+def test_firehose_lambda_processor_not_found_passes_through(fh, s3):
+ """Configured LambdaArn that doesn't exist → record delivered unchanged
+ (Firehose is best-effort; processor failure must not break the stream)."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ bucket = f"fh-miss-{suffix}"
+ delivery = f"fh-miss-{suffix}"
+ s3.create_bucket(Bucket=bucket)
+ missing_arn = (
+ f"arn:aws:lambda:us-east-1:000000000000:function:fh-no-such-{suffix}"
+ )
+ _create_firehose_with_processor(fh, delivery, bucket, missing_arn)
+ try:
+ fh.put_record(DeliveryStreamName=delivery, Record={"Data": b"untouched"})
+ for _ in range(20):
+ objs = s3.list_objects_v2(Bucket=bucket, Prefix="out/").get("Contents", [])
+ if objs:
+ break
+ time.sleep(0.1)
+ objs = s3.list_objects_v2(Bucket=bucket, Prefix="out/").get("Contents", [])
+ assert len(objs) == 1
+ body = s3.get_object(Bucket=bucket, Key=objs[0]["Key"])["Body"].read()
+ assert body == b"untouched"
+ finally:
+ try: fh.delete_delivery_stream(DeliveryStreamName=delivery)
+ except Exception: pass
+
+
+def test_firehose_kinesis_source_with_lambda_processor(fh, s3, lam, kin):
+ """End-to-end Kinesis → Firehose → Lambda processor → S3 — the user's
+ exact repro from issue #744 follow-up."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ bucket = f"fh-kin-proc-{suffix}"
+ fn = f"fh-kin-proc-fn-{suffix}"
+ delivery = f"fh-kin-proc-{suffix}"
+ stream = f"fh-kin-proc-src-{suffix}"
+ s3.create_bucket(Bucket=bucket)
+ kin.create_stream(StreamName=stream, ShardCount=1)
+ # Wait for stream to be ACTIVE.
+ for _ in range(20):
+ if kin.describe_stream(StreamName=stream)["StreamDescription"]["StreamStatus"] == "ACTIVE":
+ break
+ time.sleep(0.1)
+ stream_arn = kin.describe_stream(StreamName=stream)["StreamDescription"]["StreamARN"]
+ handler = (
+ "import base64\n"
+ "def handler(event, context):\n"
+ " out = []\n"
+ " for r in event['records']:\n"
+ " raw = base64.b64decode(r['data'])\n"
+ " out.append({\n"
+ " 'recordId': r['recordId'],\n"
+ " 'result': 'Ok',\n"
+ " 'data': base64.b64encode(b'proc:' + raw).decode(),\n"
+ " })\n"
+ " return {'records': out}\n"
+ )
+ arn = _make_processor_fn(lam, fn, handler)
+ _create_firehose_with_processor(
+ fh, delivery, bucket, arn,
+ delivery_type="KinesisStreamAsSource", kinesis_arn=stream_arn,
+ )
+ try:
+ kin.put_record(StreamName=stream, PartitionKey="pk", Data=b"payload")
+ for _ in range(30):
+ objs = s3.list_objects_v2(Bucket=bucket, Prefix="out/").get("Contents", [])
+ if objs:
+ break
+ time.sleep(0.1)
+ objs = s3.list_objects_v2(Bucket=bucket, Prefix="out/").get("Contents", [])
+ assert len(objs) >= 1, "expected at least 1 record delivered to S3"
+ body = s3.get_object(Bucket=bucket, Key=objs[0]["Key"])["Body"].read()
+ assert body == b"proc:payload", body
+ finally:
+ try: fh.delete_delivery_stream(DeliveryStreamName=delivery)
+ except Exception: pass
+ try: lam.delete_function(FunctionName=fn)
+ except Exception: pass
+ try: kin.delete_stream(StreamName=stream)
+ except Exception: pass