Skip to content

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

fix(firehose): closing open issues (#2126)

Nahuel Nucerae7881b132c97
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a66fcd47..1172b48b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,11 +8,14 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Added
-- **DocumentDB** — the `docdb` API runs on the RDS control plane as it does on AWS: `CreateDBCluster` and `CreateDBInstance` with `Engine=docdb` default to engine `8.0.0`, port `27017`, the `default.docdb8.0` parameter group and `docdb.amazonaws.com` endpoints, and each cluster runs a `documentdb-local` container serving the MongoDB protocol over TLS. The `rds` client lists the same clusters, and the `engine=docdb` filter selects them. CloudFormation provisions `AWS::DocDB::DBCluster`, `DBInstance`, `DBSubnetGroup` and `DBClusterParameterGroup`, and `AWS::SecretsManager::SecretTargetAttachment` accepts DocumentDB targets. Contributed by @xPTM1219.
+- **CloudFormation — `AWS::IAM::User`** — templates with an IAM user now provision it with `Path`, `Groups`, `ManagedPolicyArns`, inline `Policies`, `LoginProfile`, `PermissionsBoundary` and `Tags`; every property updates in place except `UserName`, which replaces the user. `Ref` returns the user name and `Fn::GetAtt` returns `Arn`. IAM gains `PutUserPermissionsBoundary` and `DeleteUserPermissionsBoundary`, and `CreateUser` and `GetUser` carry the boundary. Reported by @gakuto-cw21.
+- **DocumentDB** — a new service for the `docdb` API: `CreateDBCluster`, `CreateDBInstance`, `DescribeDBClusters`, `DescribeDBInstances`, `ModifyDBCluster`, `ModifyDBInstance`, `RebootDBInstance`, `StartDBCluster`, `StopDBCluster`, `FailoverDBCluster`, `DeleteDBCluster`, `DeleteDBInstance` and the tag operations. Each cluster runs a `documentdb-local` container serving the MongoDB protocol over TLS. Defaults follow AWS: engine `8.0.0`, port `27017`, the `default.docdb8.0` parameter group and `docdb.amazonaws.com` endpoints. The `docdb` client reaches it on the normal endpoint, and an unfiltered `DescribeDBClusters` or `DescribeDBInstances` lists RDS and DocumentDB together, as on AWS. Subnet and parameter groups are shared with RDS. CloudFormation provisions `AWS::DocDB::DBCluster`, `DBInstance`, `DBSubnetGroup` and `DBClusterParameterGroup`, and `AWS::SecretsManager::SecretTargetAttachment` accepts DocumentDB targets. Contributed by @xPTM1219.
- **CloudFormation — `AWS::Logs::MetricFilter`** — templates with a metric filter failed with `Unrecognized resource types`; the filter now provisions, updates in place and is replaced on a `FilterName` or `LogGroupName` change. Contributed by @iot-rocket.
- **DynamoDB — vector search** — `CreateTable` accepts `VectorIndexes`, `UpdateTable` takes `VectorIndexUpdates` (resource allocation, then backfilling, then `ACTIVE`), and `DescribeTable` reports them. `SearchVectors` scores with `COSINE`, `EUCLIDEAN` or `DOT_PRODUCT` at 32-bit float precision and filters on the `SearchSchema`. Writes are checked against each vector index, `INDEXES` capacity reports `VectorWriteRequestBytes` on single, batch and transactional writes, and a PartiQL `SELECT` or `Scan` on a vector index returns "Scan operation not supported on this index type". Backups record the indexes in `SourceTableFeatureDetails`, `RestoreTableFromBackup` and `RestoreTableToPointInTime` restore them or apply `VectorIndexOverride`, and `ImportTable` creates them from `TableCreationParameters`. Reported by @hicksy and the paritysuite.org project.
### Fixed
+- **ELBv2 — `http-header` rule conditions keep their `HttpHeaderConfig`** — the header name and values were dropped when a rule was created, modified or provisioned through CloudFormation, so `DescribeRules` returned an empty condition and requests never matched. Matching follows AWS: the header name and values compare case-insensitively, `*` and `?` are the only wildcards, and a request without the header does not match. Reported by @kinoh.
+- **Firehose — dynamic partitioning and Parquet conversion on S3 delivery** — `PutRecord`, `PutRecordBatch` and Kinesis-sourced records ignored `DynamicPartitioningConfiguration` and `DataFormatConversionConfiguration`. The `Prefix` and `ErrorOutputPrefix` now evaluate `!{timestamp:...}`, `!{firehose:random-string}`, `!{firehose:error-output-type}`, `!{partitionKeyFromQuery:...}` (JQ `MetadataExtraction`) and `!{partitionKeyFromLambda:...}` (Lambda `metadata.partitionKeys`), with `yyyy/MM/dd/HH/` appended when the prefix has no timestamp. Records convert to Parquet against the Glue table schema with the configured compression and land as `<stream>-<version>-<timestamp>-<uuid>.parquet` or the `FileExtension`. Failed records go to the error prefix as AWS's error document under `processing-failed` or `format-conversion-failed`. Parquet output needs DuckDB (the full image); ORC is not supported. Reported by @mintel-hgli.
- **CloudWatch Logs — `DescribeMetricFilters` by metric** — `metricName` and `metricNamespace` now select the filters that publish that metric, `filterNamePrefix` applies only with `logGroupName`, and `DeleteLogGroup` removes the group's filters. Contributed by @iot-rocket.
### Fixed
- **Cognito — `Username` is the `sub` in pools with `UsernameAttributes`** — `AdminCreateUser` and `SignUp` now use the `sub` as the `Username`, keep the email or phone number as an alias, and refuse a `Username` that is not a sign-in attribute, a differing email or phone attribute and a caller-supplied `sub`. Contributed by @iot-rocket.
diff --git a/README.md b/README.md
index b753cb88..03d59d74 100644
--- a/README.md
+++ b/README.md
@@ -408,7 +408,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 every write that changes an item, respects `StreamViewType`; `Query` and `Scan` pages stop at 1 MB of data read; GSIs accept multi-attribute keys (up to four `HASH` and four `RANGE` attributes); Kinesis streaming destinations (`aws_dynamodb_kinesis_streaming_destination`) fan item mutations out into any Kinesis stream by ARN while the destination is ACTIVE; global tables (version 2019.11.21) through `UpdateTable` `ReplicaUpdates`: a replica is a copy of the table in the other region, and writes replicate between them |
| **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 that expire after 15 minutes; `GetRecords` pages stop at 1,000 records or 1 MB; a disabled stream, or the stream of a deleted table, stays readable for 24 hours as `DISABLED` |
| **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 reuse local bootstrap processes via the Lambda Runtime API (Go, Rust, C++ support), or use Docker RIE when configured; `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; **SnapStart** — `SnapStart.ApplyOn=PublishedVersions` round-trips on `CreateFunction`/`UpdateFunctionConfiguration` (Java 11+/Python 3.12+/.NET 8+ and container images, per AWS's constraints); publishing a version initializes its execution environment then and there, so the version reports `OptimizationStatus: On`, walks `Pending` → `Active`, answers `ResourceConflictException` while `Pending`, fails the publish on a broken init, and runs `snapshot-restore-py` before-snapshot/after-restore hooks during init (Python); **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, UpdateRoleDescription, PutRolePermissionsBoundary, DeleteRolePermissionsBoundary, 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, AttachGroupPolicy, DetachGroupPolicy, ListAttachedGroupPolicies, PutGroupPolicy, GetGroupPolicy, DeleteGroupPolicy, ListGroupPolicies, 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 | Role descriptions and permissions boundaries round-trip through role reads; boundaries support put/delete updates. |
+| **IAM** | CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles, DeleteRole, UpdateRoleDescription, PutRolePermissionsBoundary, DeleteRolePermissionsBoundary, PutUserPermissionsBoundary, DeleteUserPermissionsBoundary, 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, AttachGroupPolicy, DetachGroupPolicy, ListAttachedGroupPolicies, PutGroupPolicy, GetGroupPolicy, DeleteGroupPolicy, ListGroupPolicies, 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 | Role descriptions and permissions boundaries round-trip through role reads; boundaries support put/delete updates. |
| **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`) |
@@ -490,6 +490,7 @@ subnet = ec2.create_subnet(
| `AWS::DynamoDB::Table` | Table name | Arn, StreamArn |
| `AWS::Lambda::Function` | Function name | Arn |
| `AWS::IAM::Role` | Role name | Arn, RoleId |
+| `AWS::IAM::User` | User name | Arn |
| `AWS::IAM::Policy` | Generated id | Id |
| `AWS::IAM::InstanceProfile` | Profile name | Arn |
| `AWS::SSM::Parameter` | Parameter name | Type, Value |
@@ -623,13 +624,13 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i
|---------|-----------|-------|
| **ECS** | CreateCluster, DeleteCluster, DescribeClusters, ListClusters, UpdateCluster, UpdateClusterSettings, PutClusterCapacityProviders, RegisterTaskDefinition, DeregisterTaskDefinition, DescribeTaskDefinition, ListTaskDefinitions, ListTaskDefinitionFamilies, DeleteTaskDefinitions, CreateService, DeleteService, DescribeServices, UpdateService, ListServices, ListServicesByNamespace, RunTask, StopTask, DescribeTasks, ListTasks, ExecuteCommand, UpdateTaskProtection, GetTaskProtection, CreateCapacityProvider, UpdateCapacityProvider, DeleteCapacityProvider, DescribeCapacityProviders, TagResource, UntagResource, ListTagsForResource, ListAccountSettings, PutAccountSetting, PutAccountSettingDefault, DeleteAccountSetting, PutAttributes, DeleteAttributes, ListAttributes, DescribeServiceDeployments, ListServiceDeployments, DescribeServiceRevisions, SubmitTaskStateChange, SubmitContainerStateChange, SubmitAttachmentStateChanges, DiscoverPollEndpoint | 47 actions; `RunTask` starts real Docker containers via Docker socket; full Terraform ECS coverage |
| **RDS** | CreateDBInstance, DeleteDBInstance, DescribeDBInstances, ModifyDBInstance, StartDBInstance, StopDBInstance, RebootDBInstance, CreateDBInstanceReadReplica, RestoreDBInstanceFromDBSnapshot, CreateDBCluster, DeleteDBCluster, DescribeDBClusters, ModifyDBCluster, StartDBCluster, StopDBCluster, FailoverDBCluster, SwitchoverGlobalCluster, FailoverGlobalCluster, CreateDBSnapshot, DeleteDBSnapshot, DescribeDBSnapshots, CreateDBClusterSnapshot, DescribeDBClusterSnapshots, DescribeDBClusterSnapshotAttributes, DeleteDBClusterSnapshot, CreateDBSubnetGroup, DeleteDBSubnetGroup, DescribeDBSubnetGroups, ModifyDBSubnetGroup, CreateDBParameterGroup, DeleteDBParameterGroup, DescribeDBParameterGroups, DescribeDBParameters, ModifyDBParameterGroup, CreateDBClusterParameterGroup, DescribeDBClusterParameterGroups, DeleteDBClusterParameterGroup, DescribeDBClusterParameters, ModifyDBClusterParameterGroup, CreateOptionGroup, DeleteOptionGroup, DescribeOptionGroups, DescribeOptionGroupOptions, ListTagsForResource, AddTagsToResource, RemoveTagsFromResource, DescribeDBEngineVersions, DescribeOrderableDBInstanceOptions, CreateGlobalCluster, DescribeGlobalClusters, DeleteGlobalCluster, RemoveFromGlobalCluster, ModifyGlobalCluster, CreateDBProxy, DescribeDBProxies, ModifyDBProxy, DeleteDBProxy, CreateDBProxyEndpoint, DescribeDBProxyEndpoints, ModifyDBProxyEndpoint, DeleteDBProxyEndpoint, DescribeDBProxyTargetGroups, ModifyDBProxyTargetGroup, RegisterDBProxyTargets, DeregisterDBProxyTargets, DescribeDBProxyTargets | `CreateDBInstance` spins up real Postgres/MySQL Docker container, returns actual `host:port` endpoint; a standalone MySQL or MariaDB instance starts with its DB parameter group's set values, `immediate` changes to dynamic parameters reach running instances, and `BackupRetentionPeriod=0` turns binary logging off; a cluster's endpoint is its stable AWS-shaped name, registered as a Docker network alias on the backing container (on user-defined networks; the default bridge keeps the address form), so a stored endpoint keeps resolving after the container is replaced; Aurora MySQL 8.0/8.4 compatibility objects (`AWSAuthenticationPlugin`, RDS/Aurora stored procedures, predefined S3 roles) install automatically for supported MySQL images so Aurora provisioning workflows run. IAM database authentication on MySQL and Aurora MySQL 8.0/8.4 (not MariaDB): a user created `IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS'` logs in with an SDK-generated auth token over `mysql_clear_password` when the instance or cluster has `IAMDatabaseAuthenticationEnabled`; with `AUTH=true` the token and the `rds-db:connect` policy are verified too. Planned Aurora MySQL switchover (`SwitchoverGlobalCluster`, and `FailoverGlobalCluster` without data loss allowed) performs a coordinated no-data-loss writer exchange on provisioned two-member MySQL 8 global clusters; other configurations keep the metadata-only path. RDS Proxy is control plane only — proxies, proxy endpoints, the default target group and registered targets are stored and returned with the AWS shapes, but nothing listens on the proxy endpoint hostname; clients keep connecting to the instance or cluster endpoint |
-| **DocumentDB** | CreateDBCluster, CreateDBInstance, DeleteDBCluster, DeleteDBInstance, DescribeDBClusters, DescribeDBInstances, StartDBCluster, StopDBCluster, ModifyDBCluster, AddTagsToResource, ListTagsForResource, CreateDBSubnetGroup, CreateDBClusterParameterGroup | Same control plane as RDS (`Engine=docdb`): the `docdb` and `rds` clients see the same clusters. Each cluster runs a `documentdb-local` container speaking the MongoDB protocol over TLS on its endpoint; engine versions 3.6.0, 4.0.0, 5.0.x and 8.0.x (default 8.0.0) |
+| **DocumentDB** | CreateDBCluster, CreateDBInstance, DescribeDBClusters, DescribeDBInstances, ModifyDBCluster, ModifyDBInstance, RebootDBInstance, StartDBCluster, StopDBCluster, FailoverDBCluster, DeleteDBCluster, DeleteDBInstance, AddTagsToResource, RemoveTagsFromResource, ListTagsForResource | Each cluster runs a `documentdb-local` container speaking the MongoDB protocol over TLS on its endpoint; engine versions 3.6.0, 4.0.0, 5.0.x and 8.0.x (default 8.0.0). The `docdb` client works on the normal endpoint; subnet and parameter groups are shared with RDS |
| **Aurora DSQL** | CreateCluster, GetCluster, UpdateCluster, DeleteCluster, ListClusters, PutClusterPolicy, GetClusterPolicy, DeleteClusterPolicy, CreateStream, GetStream, ListStreams, DeleteStream, GetVpcEndpointServiceName, TagResource, UntagResource, ListTagsForResource | `CreateCluster` spins up a real `postgres:16-alpine` Docker container fronted by a validating PG wire-protocol proxy that **fails like real DSQL** — rejects unsupported SQL (`serial`, extensions, temp tables, ...), accepts `CREATE INDEX ASYNC` + `sys.jobs`; endpoint is `localhost:<port>`; any password accepted |
| **ElastiCache** | CreateCacheCluster, DeleteCacheCluster, DescribeCacheClusters, ModifyCacheCluster, RebootCacheCluster, CreateReplicationGroup, DeleteReplicationGroup, DescribeReplicationGroups, ModifyReplicationGroup, IncreaseReplicaCount, DecreaseReplicaCount, CreateCacheSubnetGroup, DescribeCacheSubnetGroups, ModifyCacheSubnetGroup, DeleteCacheSubnetGroup, CreateCacheParameterGroup, DescribeCacheParameterGroups, ModifyCacheParameterGroup, ResetCacheParameterGroup, DeleteCacheParameterGroup, DescribeCacheParameters, DescribeCacheEngineVersions, CreateUser, DescribeUsers, DeleteUser, ModifyUser, CreateUserGroup, DescribeUserGroups, DeleteUserGroup, ModifyUserGroup, ListTagsForResource, AddTagsToResource, RemoveTagsFromResource, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, CreateServerlessCache, DescribeServerlessCaches, ModifyServerlessCache, DeleteServerlessCache, DescribeEvents | `CreateCacheCluster` spins up a real Redis, Valkey, or Memcached Docker container (`Engine=redis`/`valkey`/`memcached`); a serverless cache gets a TLS-only, single-shard cluster-mode Valkey/Redis container whose certificate chains to the CA at `GET /_ministack/elasticache/ca.pem` |
| **Glue** | CreateDatabase, DeleteDatabase, GetDatabase, GetDatabases, UpdateDatabase, CreateTable, DeleteTable, GetTable, GetTables, UpdateTable, BatchDeleteTable, CreatePartition, DeletePartition, GetPartition, GetPartitions, BatchCreatePartition, BatchGetPartition, CreatePartitionIndex, GetPartitionIndexes, GetColumnStatisticsForTable, UpdateColumnStatisticsForTable, DeleteColumnStatisticsForTable, GetColumnStatisticsForPartition, UpdateColumnStatisticsForPartition, DeleteColumnStatisticsForPartition, 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, CreateUserDefinedFunction, UpdateUserDefinedFunction, DeleteUserDefinedFunction, GetUserDefinedFunction, GetUserDefinedFunctions, 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; Glue-backed Iceberg REST catalog at `/iceberg` (signed with the `glue` credential scope, prefix `catalogs/{catalog}`) — read path for tables whose `metadata_location` parameter points at a metadata.json on MiniStack S3, e.g. DuckDB `ATTACH ... (TYPE iceberg, ENDPOINT 'localhost:4566/iceberg', AUTHORIZATION_TYPE 'sigv4')` with `USE_SSL=1` |
| **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, each catalog scoped to the table bucket ARN in its prefix and commits checked against their update requirements; 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, GetDatabase, ListDatabases, GetTableMetadata, ListTableMetadata, TagResource, UntagResource, ListTagsForResource | Real SQL via **DuckDB** when installed (`pip install duckdb`), otherwise returns mock results; databases and tables come from the Glue Data Catalog, and `CREATE EXTERNAL TABLE` / `DROP TABLE` change it; 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`; `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) |
+| **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); S3 prefixes evaluate timestamp, random-string, error-output-type and dynamic partition keys (JQ `MetadataExtraction` or Lambda `partitionKeys`); `DataFormatConversionConfiguration` writes Parquet from the Glue schema (DuckDB, full image) |
| **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, AssociateIamInstanceProfile, DescribeIamInstanceProfileAssociations, DisassociateIamInstanceProfile, ReplaceIamInstanceProfileAssociation, DescribeImages, RegisterImage, DeregisterImage, ModifyImageAttribute, DescribeImageAttribute, ResetImageAttribute, CreateSecurityGroup, DeleteSecurityGroup, DescribeSecurityGroups, AuthorizeSecurityGroupIngress, RevokeSecurityGroupIngress, AuthorizeSecurityGroupEgress, RevokeSecurityGroupEgress, DescribeSecurityGroupRules, CreateKeyPair, DeleteKeyPair, DescribeKeyPairs, ImportKeyPair, CreatePlacementGroup, DeletePlacementGroup, DescribePlacementGroups, 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, CreateFleet, DescribeFleets | 133 actions; EC2 Fleet (`CreateFleet` / `DescribeFleets`) with `instant`-type synchronous launch and `maintain` / `request` async fulfillment, multi-config × multi-override round-robin capacity distribution, and `DefaultTargetCapacityType`-driven spot/on-demand selection — unblocks Karpenter / Cluster Autoscaler local validation; IAM instance profile association lifecycle is persisted (`Associate*`, `Describe*`, `Replace*`, `Disassociate*`) so Terraform `aws_instance.iam_instance_profile` round-trips without drift; `AuthorizeSecurityGroupIngress` is idempotent on duplicate rules (same behavior as egress; avoids Terraform re-apply failures); metadata-only instance records by default — `RegisterImage` with a container reference makes an AMI whose launches get a real box, so SSM Run Command returns a real exit code (see *Instances with a real box*); CreateVpc provisions per-VPC default route table, network ACL, and security group; cross-account AMI sharing via launch permissions (`ModifyImageAttribute` add/remove, `Group=all` makes the image public, `DescribeImages` shows shared images with the owner's `OwnerId`, `ExecutableUsers` honored, shared AMIs launch); 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 |
@@ -896,6 +897,9 @@ come from `repositoryCredentials.credentialsParameter` (a Secrets Manager secret
| `DSQL_BASE_PORT` | `25432` | Starting host port for Aurora DSQL cluster proxies (one port per cluster) |
| `DSQL_STRICT` | `0` | Set `1` to run a real Postgres container per DSQL cluster (requires Docker; capped by a fixed port window off `DSQL_BASE_PORT`, default 30 — further clusters are metadata-only stubs). Default `0` is control-plane-only |
| `DSQL_PG_IMAGE` | `postgres:16-alpine` | Image used for per-cluster DSQL backend containers |
+| `DOCDB_BASE_PORT` | `27117` | Starting host port for DocumentDB cluster containers |
+| `DOCDB_PERSIST` | `0` | Set `1` to keep DocumentDB data in Docker named volumes instead of tmpfs |
+| `DOCDB_TMPFS_SIZE` | `256m` | tmpfs size for DocumentDB data when `DOCDB_PERSIST=0` |
| `DSQL_PERSIST` | `0` | Set `1` to use Docker named volumes for DSQL backend containers instead of tmpfs |
| `DOCKER_NETWORK` | _(unset)_ | Docker network for all container-backed services (RDS, DSQL, EKS, ElastiCache, Lambda). Set to your Docker Compose network name so containers can reach each other. Replaces `LAMBDA_DOCKER_NETWORK` |
| `ELASTICACHE_BASE_PORT` | `16379` | Starting host port for ElastiCache containers |
diff --git a/ministack/services/alb.py b/ministack/services/alb.py
index 10bb1221..e2affb5d 100644
--- a/ministack/services/alb.py
+++ b/ministack/services/alb.py
@@ -27,10 +27,12 @@ import json
import logging
import os
import random
+import re
import socket
import string
import time
from urllib.parse import parse_qs, urlencode
+from xml.sax.saxutils import escape as _esc
from ministack.core.arn import ArnParseError, parse_arn
from ministack.core.concurrency import run_reentrant
@@ -342,7 +344,17 @@ def _parse_conditions(params, prefix="Conditions"):
field = _p(params, f"{base}.Field")
if not field:
break
- conditions.append({"Field": field, "Values": _parse_condition_values(params, base)})
+ condition = {"Field": field, "Values": _parse_condition_values(params, base)}
+ if field == "http-header":
+ values, j = [], 1
+ while value := _p(params, f"{base}.HttpHeaderConfig.Values.member.{j}"):
+ values.append(value)
+ j += 1
+ condition["HttpHeaderConfig"] = {
+ "HttpHeaderName": _p(params, f"{base}.HttpHeaderConfig.HttpHeaderName"),
+ "Values": values,
+ }
+ conditions.append(condition)
i += 1
return conditions
@@ -535,6 +547,11 @@ def _condition_xml(c):
config_key = _CONDITION_VALUE_KEYS.get(c.get("Field"))
if config_key:
xml += f"<{config_key}><Values>{members}</Values></{config_key}>"
+ header = c.get("HttpHeaderConfig")
+ if header:
+ header_values = "".join(f"<member>{_esc(v)}</member>" for v in header.get("Values", []))
+ xml += (f"<HttpHeaderConfig><HttpHeaderName>{_esc(header.get('HttpHeaderName', ''))}</HttpHeaderName>"
+ f"<Values>{header_values}</Values></HttpHeaderConfig>")
return xml + "</member>"
@@ -1238,6 +1255,11 @@ def _find_lb_by_name(name):
# Data-plane: rule matching
# ---------------------------------------------------------------------------
+def _header_value_matches(actual, pattern):
+ regex = re.escape(pattern).replace(r"\*", ".*").replace(r"\?", ".")
+ return re.fullmatch(regex, actual, re.IGNORECASE | re.DOTALL) is not None
+
+
def _match_condition(cond, method, path, headers, query_params):
field = cond.get("Field", "")
values = cond.get("Values", [])
@@ -1268,11 +1290,12 @@ def _match_condition(cond, method, path, headers, query_params):
return True
if field == "http-header":
- cfg = cond.get("HttpHeaderConfig", {})
- hname = cfg.get("HttpHeaderName", "").lower()
- hvals = cfg.get("Values", values)
- actual = headers.get(hname, "")
- return any(fnmatch.fnmatch(actual, v) for v in hvals)
+ # Case-insensitive name and values; only * and ? are wildcards.
+ cfg = cond.get("HttpHeaderConfig") or {}
+ actual = headers.get(cfg.get("HttpHeaderName", "").lower())
+ if actual is None:
+ return False
+ return any(_header_value_matches(actual, v) for v in cfg.get("Values") or values)
# source-ip is not implemented (no real network in emulator) — always matches.
# Unknown condition types also always match to avoid silently dropping traffic.
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index bb7c560b..d53f45eb 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -734,6 +734,7 @@ _CUSTOM_NAME_REPLACEMENT = {
"requires_replacement": lambda old, new: old.get("Path", "/") != new.get("Path", "/"),
},
"AWS::IAM::Role": {"name": "RoleName"},
+ "AWS::IAM::User": {"name": "UserName"},
"AWS::IAM::ManagedPolicy": {
"name": "ManagedPolicyName",
"exists": "A policy called {name} already exists. Duplicate names are not allowed.",
@@ -1135,6 +1136,7 @@ _STACK_TAG_PROPERTY: dict[str, tuple[str, str]] = {
"AWS::ElasticLoadBalancingV2::TargetGroup": ("Tags", "list"),
"AWS::Events::EventBus": ("Tags", "list"),
"AWS::IAM::Role": ("Tags", "list"),
+ "AWS::IAM::User": ("Tags", "list"),
"AWS::KMS::Key": ("Tags", "list"),
"AWS::Kinesis::Stream": ("Tags", "list"),
"AWS::Lambda::Function": ("Tags", "list"),
@@ -2498,6 +2500,107 @@ def _iam_role_delete(physical_id, props):
_iam.detach_managed_policy(role, policy_arn)
+# --- IAM User ---
+
+def _iam_user_call(fn, params, action):
+ status, _headers, body = fn(params)
+ if status >= 400:
+ _rds_raise(status, body, "AWS::IAM::User", action)
+
+
+def _iam_user_policies(props):
+ out = {}
+ for pol in props.get("Policies") or []:
+ doc = pol.get("PolicyDocument", {})
+ out[pol.get("PolicyName", "")] = doc if isinstance(doc, str) else json.dumps(doc)
+ return out
+
+
+def _iam_user_login_profile(name, old, new, action):
+ if old == new:
+ return
+ if not new:
+ _iam_user_call(_iam._delete_login_profile, {"UserName": name}, action)
+ return
+ params = {"UserName": name, "Password": new.get("Password", ""),
+ "PasswordResetRequired": str(_cfn_bool(new.get("PasswordResetRequired", False))).lower()}
+ _iam_user_call(_iam._update_login_profile if old else _iam._create_login_profile, params, action)
+
+
+def _iam_user_reconcile(name, old_props, new_props, action):
+ """Bring groups, managed and inline policies, boundary and login profile to the template."""
+ old_groups, new_groups = set(old_props.get("Groups") or []), set(new_props.get("Groups") or [])
+ for group in sorted(old_groups - new_groups):
+ _iam_user_call(_iam._remove_user_from_group, {"UserName": name, "GroupName": group}, action)
+ for group in sorted(new_groups - old_groups):
+ _iam_user_call(_iam._add_user_to_group, {"UserName": name, "GroupName": group}, action)
+ old_managed = set(old_props.get("ManagedPolicyArns") or [])
+ new_managed = set(new_props.get("ManagedPolicyArns") or [])
+ for arn in sorted(old_managed - new_managed):
+ _iam_user_call(_iam._detach_user_policy, {"UserName": name, "PolicyArn": arn}, action)
+ for arn in sorted(new_managed - old_managed):
+ _iam_user_call(_iam._attach_user_policy, {"UserName": name, "PolicyArn": arn}, action)
+ old_inline, new_inline = _iam_user_policies(old_props), _iam_user_policies(new_props)
+ for policy_name in sorted(old_inline.keys() - new_inline.keys()):
+ _iam_user_call(_iam._delete_user_policy, {"UserName": name, "PolicyName": policy_name}, action)
+ for policy_name, doc in new_inline.items():
+ if old_inline.get(policy_name) != doc:
+ _iam_user_call(_iam._put_user_policy,
+ {"UserName": name, "PolicyName": policy_name, "PolicyDocument": doc}, action)
+ old_boundary, new_boundary = old_props.get("PermissionsBoundary"), new_props.get("PermissionsBoundary")
+ if new_boundary and new_boundary != old_boundary:
+ _iam_user_call(_iam._put_user_permissions_boundary,
+ {"UserName": name, "PermissionsBoundary": new_boundary}, action)
+ elif old_boundary and not new_boundary:
+ _iam_user_call(_iam._delete_user_permissions_boundary, {"UserName": name}, action)
+ _iam_user_login_profile(name, old_props.get("LoginProfile"), new_props.get("LoginProfile"), action)
+
+
+def _iam_user_create(logical_id, props, stack_name):
+ name = props.get("UserName") or _physical_name(stack_name, logical_id, max_len=64)
+ _iam_user_call(_iam._create_user, {"UserName": name, **_ec_query({
+ k: props[k] for k in ("Path", "PermissionsBoundary", "Tags") if props.get(k)})}, "create")
+ try:
+ _iam_user_reconcile(name, {"PermissionsBoundary": props.get("PermissionsBoundary")}, props, "create")
+ except ValueError:
+ _iam_user_delete(name, props)
+ raise
+ return name, {"Arn": _iam._users[name]["Arn"]}
+
+
+def _iam_user_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ user = _iam._users.get(physical_id)
+ if user is None:
+ return _iam_user_create(logical_id or physical_id, new_props, stack_name)
+ path = new_props.get("Path") or "/"
+ if path != user["Path"]:
+ user["Path"] = path
+ user["Arn"] = f"arn:aws:iam::{get_account_id()}:user{path}{physical_id}"
+ _iam_user_reconcile(physical_id, old_props, new_props, "update")
+ old_tags, new_tags = _tag_map(old_props.get("Tags")), _tag_map(new_props.get("Tags"))
+ removed = sorted(old_tags.keys() - new_tags.keys())
+ if removed:
+ _iam_user_call(_iam._untag_user, {"UserName": physical_id, **_ec_query({"TagKeys": removed})}, "update")
+ changed = [{"Key": k, "Value": v} for k, v in new_tags.items() if old_tags.get(k) != v]
+ if changed:
+ _iam_user_call(_iam._tag_user, {"UserName": physical_id, **_ec_query({"Tags": changed})}, "update")
+ return physical_id, {"Arn": user["Arn"]}
+
+
+def _iam_user_delete(physical_id, props):
+ user = _iam._users.get(physical_id)
+ if user is None:
+ return
+ for group in _iam._groups.values():
+ if physical_id in group.get("Users", []):
+ group["Users"].remove(physical_id)
+ for arn in list(user.get("AttachedPolicies", [])):
+ _iam.detach_managed_policy(user, arn)
+ _iam._user_inline_policies.pop(physical_id, None)
+ _iam._login_profiles.pop(physical_id, None)
+ _iam_user_call(_iam._delete_user, {"UserName": physical_id}, "delete")
+
+
# --- IAM Policy ---
#
# AWS::IAM::ManagedPolicy creates a managed policy and attaches it;
@@ -9092,7 +9195,12 @@ def _flatten_listener_rule_conditions(cfn_conditions):
values = cfg.get("Values") or []
if not values and field == "query-string" and cfg.get("Values") is None:
values = [f"{q.get('Key','')}={q.get('Value','')}" for q in (cfg.get("Values") or [])]
- out.append({"Field": field, "Values": list(values)})
+ condition = {"Field": field, "Values": list(values)}
+ header = c.get("HttpHeaderConfig") if field == "http-header" else None
+ if header:
+ condition = {"Field": field, "Values": [], "HttpHeaderConfig": {
+ "HttpHeaderName": header.get("HttpHeaderName", ""), "Values": list(header.get("Values") or [])}}
+ out.append(condition)
return out
@@ -14054,6 +14162,7 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {
),
"AWS::IAM::InstanceProfile": ("InstanceProfileName", "Path"),
"AWS::IAM::Role": ("RoleName", "Path"),
+ "AWS::IAM::User": ("UserName",),
"AWS::IAM::ManagedPolicy": ("ManagedPolicyName", "Description", "Path"),
"AWS::ECR::Repository": ("RepositoryName", "EncryptionConfiguration"),
"AWS::IoT::ProvisioningTemplate": ("TemplateName", "TemplateType"),
@@ -14310,6 +14419,12 @@ _RESOURCE_HANDLERS = {
"delete": _iam_role_delete,
"import": _iam_role_import,
},
+ "AWS::IAM::User": {
+ "create": _iam_user_create,
+ "update": _iam_user_update,
+ "update_with_logical_id": True,
+ "delete": _iam_user_delete,
+ },
"AWS::IAM::Policy": {
"create": _iam_policy_create,
"update": _iam_policy_update,
diff --git a/ministack/services/firehose.py b/ministack/services/firehose.py
index c5a06c3d..04e69850 100644
--- a/ministack/services/firehose.py
+++ b/ministack/services/firehose.py
@@ -234,7 +234,8 @@ def _resolve_dest_update_config(data: dict):
return None, None
-def _apply_lambda_processors(stream: dict, dest: dict, records: list, metadata_sink: dict = None) -> list:
+def _apply_lambda_processors(stream: dict, dest: dict, records: list, metadata_sink: dict = None,
+ partition_sink: dict = None) -> list:
"""Apply a destination's ProcessingConfiguration Lambda processors to a
batch of records.
@@ -343,6 +344,10 @@ def _apply_lambda_processors(stream: dict, dest: dict, records: list, metadata_s
otf = (r.get("metadata") or {}).get("otfMetadata")
if isinstance(otf, dict):
metadata_sink[rid] = otf
+ if partition_sink is not None:
+ keys = (r.get("metadata") or {}).get("partitionKeys")
+ if isinstance(keys, dict):
+ partition_sink[rid] = {str(k): str(v) for k, v in keys.items()}
outcome = r.get("result", "Ok")
if outcome in ("Dropped", "ProcessingFailed"):
continue
@@ -360,39 +365,437 @@ def _apply_lambda_processors(stream: dict, dest: dict, records: list, metadata_s
return current
-def _deliver_to_s3(stream: dict, dest: dict, record_data: bytes):
- """Best-effort delivery of a record to the local S3 emulator.
+# ─── S3 delivery: prefixes, dynamic partitioning, record format conversion ────
- Called while holding _lock so must not block the event loop.
- Schedules a coroutine on the running loop (fire-and-forget).
- """
+
+class _DeliveryError(Exception):
+ """A record goes to the error prefix with this error-output-type."""
+
+ def __init__(self, output_type, message, code=None):
+ super().__init__(message)
+ self.output_type = output_type
+ self.message = message
+ self.code = code
+
+
+_PREFIX_EXPR_RE = re.compile(r"!\{([A-Za-z]+):([^}]*)\}")
+_MONTHS = ("January", "February", "March", "April", "May", "June", "July", "August", "September",
+ "October", "November", "December")
+
+
+def _java_time(pattern, t):
+ """Format ``t`` (struct_time) with a Java DateTimeFormatter pattern: y M d H m s D, 'quoted' literals."""
+ out, i = [], 0
+ while i < len(pattern):
+ c = pattern[i]
+ if c == "'":
+ end = pattern.find("'", i + 1)
+ if end == i + 1:
+ out.append("'")
+ i += 2
+ continue
+ out.append(pattern[i + 1:] if end < 0 else pattern[i + 1:end])
+ i = len(pattern) if end < 0 else end + 1
+ continue
+ if c in "yMdHmsD":
+ n = 1
+ while i + n < len(pattern) and pattern[i + n] == c:
+ n += 1
+ value = {"y": t.tm_year, "M": t.tm_mon, "d": t.tm_mday, "H": t.tm_hour,
+ "m": t.tm_min, "s": t.tm_sec, "D": t.tm_yday}[c]
+ if c == "y" and n == 2:
+ out.append(f"{value % 100:02d}")
+ elif c == "M" and n >= 3:
+ out.append(_MONTHS[value - 1][:3] if n == 3 else _MONTHS[value - 1])
+ else:
+ out.append(str(value).zfill(n))
+ i += n
+ continue
+ out.append(c)
+ i += 1
+ return "".join(out)
+
+
+def _evaluate_prefix(template, t, query_keys=None, lambda_keys=None, error_type=None):
+ """Evaluate a Prefix / ErrorOutputPrefix; ``yyyy/MM/dd/HH/`` is appended when it has no timestamp expression."""
+ has_timestamp = False
+
+ def expand(match):
+ nonlocal has_timestamp
+ namespace, value = match.group(1), match.group(2)
+ if namespace == "timestamp":
+ has_timestamp = True
+ return _java_time(value, t)
+ if namespace == "firehose" and value == "random-string":
+ return new_uuid().replace("-", "")[:11]
+ if namespace == "firehose" and value == "error-output-type" and error_type:
+ return error_type
+ keys = {"partitionKeyFromQuery": query_keys, "partitionKeyFromLambda": lambda_keys}.get(namespace)
+ if keys is not None and value in keys:
+ return keys[value]
+ raise _DeliveryError("processing-failed", f"Cannot evaluate !{{{namespace}:{value}}} in the S3 prefix.")
+
+ evaluated = _PREFIX_EXPR_RE.sub(expand, template or "")
+ if not has_timestamp:
+ evaluated += _java_time("yyyy/MM/dd/HH/", t)
+ return evaluated
+
+
+# jq 1.6, the subset Firehose metadata extraction uses: an object of
+# key: .path (fields, ["key"], [n], [m:n]) optionally piped to strftime("fmt").
+_JQ_TOKEN_RE = re.compile(r'\s*(?:("(?:[^"\\]|\\.)*")|(-?\d+)|([A-Za-z_][A-Za-z0-9_]*)|([{}\[\]:,.|()]))')
+
+
+def _jq_tokens(expression):
+ tokens, pos = [], 0
+ while pos < len(expression):
+ if expression[pos:].strip() == "":
+ break
+ match = _JQ_TOKEN_RE.match(expression, pos)
+ if not match:
+ raise ValueError(f"unsupported jq syntax at {expression[pos:]!r}")
+ string, number, ident, punct = match.groups()
+ if string is not None:
+ tokens.append(("str", json.loads(string)))
+ elif number is not None:
+ tokens.append(("num", int(number)))
+ elif ident is not None:
+ tokens.append(("ident", ident))
+ else:
+ tokens.append(("punct", punct))
+ pos = match.end()
+ return tokens
+
+
+def _jq_parse(expression):
+ """Parse ``{key: .path | strftime("fmt"), ...}`` into ``[(key, steps, functions)]``."""
+ tokens, i = _jq_tokens(expression), 0
+
+ def peek(kind=None, value=None):
+ if i >= len(tokens):
+ return False
+ tk, tv = tokens[i]
+ return (kind is None or tk == kind) and (value is None or tv == value)
+
+ def take(kind=None, value=None):
+ nonlocal i
+ if not peek(kind, value):
+ raise ValueError(f"unsupported jq expression: {expression!r}")
+ i += 1
+ return tokens[i - 1][1]
+
+ def path():
+ steps = []
+ take("punct", ".")
+ if peek("ident") or peek("str"):
+ steps.append(("key", take()))
+ while peek("punct", ".") or peek("punct", "["):
+ if peek("punct", "."):
+ take()
+ steps.append(("key", take("str") if peek("str") else take("ident")))
+ continue
+ take("punct", "[")
+ if peek("str"):
+ steps.append(("key", take()))
+ else:
+ start = take("num") if peek("num") else None
+ if peek("punct", ":"):
+ take()
+ end = take("num") if peek("num") else None
+ steps.append(("slice", start, end))
+ elif start is None:
+ raise ValueError(f"unsupported jq expression: {expression!r}")
+ else:
+ steps.append(("index", start))
+ take("punct", "]")
+ return steps
+
+ pairs = []
+ take("punct", "{")
+ while not peek("punct", "}"):
+ key = take("str") if peek("str") else take("ident")
+ if peek("punct", ":"):
+ take()
+ steps, functions = path(), []
+ while peek("punct", "|"):
+ take()
+ name = take("ident")
+ if name != "strftime":
+ raise ValueError(f"unsupported jq function: {name}")
+ take("punct", "(")
+ functions.append(("strftime", take("str")))
+ take("punct", ")")
+ else:
+ steps, functions = [("key", key)], []
+ pairs.append((key, steps, functions))
+ if not peek("punct", ","):
+ break
+ take()
+ take("punct", "}")
+ if i != len(tokens):
+ raise ValueError(f"unsupported jq expression: {expression!r}")
+ return pairs
+
+
+def _jq_value(document, steps, functions):
+ value = document
+ for step in steps:
+ if value is None:
+ return None
+ if step[0] == "key":
+ if not isinstance(value, dict):
+ raise ValueError(f"Cannot index {type(value).__name__} with \"{step[1]}\"")
+ value = value.get(step[1])
+ elif step[0] == "index":
+ if not isinstance(value, list):
+ raise ValueError(f"Cannot index {type(value).__name__} with number")
+ value = value[step[1]] if -len(value) <= step[1] < len(value) else None
+ else:
+ if not isinstance(value, (list, str)):
+ raise ValueError(f"Cannot index {type(value).__name__} with object")
+ value = value[step[1]:step[2]]
+ for _name, fmt in functions:
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise ValueError("strftime/1 requires parsed datetime inputs")
+ value = time.strftime(fmt, time.gmtime(value))
+ return value
+
+
+def _metadata_extraction_keys(cfg, data):
+ """Partition keys from a MetadataExtraction processor, or None when there is none."""
+ processing = cfg.get("ProcessingConfiguration") or {}
+ if not processing.get("Enabled"):
+ return None
+ query = None
+ for processor in processing.get("Processors") or []:
+ if processor.get("Type") == "MetadataExtraction":
+ for parameter in processor.get("Parameters") or []:
+ if parameter.get("ParameterName") == "MetadataExtractionQuery":
+ query = parameter.get("ParameterValue")
+ if query is None:
+ return None
try:
- from ministack.services import s3 as s3_svc
+ document = json.loads(data)
+ if not isinstance(document, dict):
+ raise ValueError("the record is not a JSON object")
+ keys = {}
+ for key, steps, functions in _jq_parse(query):
+ value = _jq_value(document, steps, functions)
+ if value is None or isinstance(value, (dict, list)):
+ raise ValueError(f"partition key {key} has no scalar value")
+ keys[key] = value if isinstance(value, str) else json.dumps(value)
+ return keys
+ except (ValueError, UnicodeDecodeError) as exc:
+ raise _DeliveryError("processing-failed", f"Metadata extraction failed: {exc}") from exc
+
+
+_CONVERSION_ERRORS = {
+ "empty": ("DataFormatConversion.MalformedData", "The record was empty or contained only whitespace."),
+ "primitive": ("DataFormatConversion.MalformedData",
+ "The input JSON contained a primitive at the top level. The top level must be an object or array."),
+ "malformed": ("DataFormatConversion.ParseError", "Encountered malformed JSON."),
+ "mismatch": ("DataFormatConversion.MalformedData", "Data does not match the schema."),
+ "table": ("DataFormatConversion.EntityNotFound",
+ "The specified table/database could not be found. Please ensure that the table/database exists and "
+ "that the values provided in the schema configuration are correct, especially with regards to casing."),
+ "unsupported": ("DataFormatConversion.ConversionFailureException", "ConversionFailureException"),
+}
- cfg = dest["config"]
- bucket_arn = cfg.get("BucketARN", "")
- bucket = _s3_bucket_from_arn(bucket_arn)
- prefix = cfg.get("Prefix", "")
- ts = time.strftime("%Y/%m/%d/%H", time.gmtime())
- key = f"{prefix}{ts}/{stream['name']}-{new_uuid()}"
-
- async def _put():
- fake_headers = {
- "content-type": "application/octet-stream",
- "content-length": str(len(record_data)),
- "host": "s3.localhost",
- }
- await s3_svc.handle_request("PUT", f"/{bucket}/{key}", fake_headers, record_data, {})
+def _conversion_error(kind):
+ code, message = _CONVERSION_ERRORS[kind]
+ return _DeliveryError("format-conversion-failed", message, code)
+
+
+def _hive_to_duckdb_type(hive_type):
+ """Glue/Hive column type to a DuckDB type, nested types included."""
+ text = hive_type.strip()
+ lower = text.lower()
+
+ def split_args(inner):
+ parts, depth, start = [], 0, 0
+ for pos, ch in enumerate(inner):
+ if ch in "<(":
+ depth += 1
+ elif ch in ">)":
+ depth -= 1
+ elif ch == "," and depth == 0:
+ parts.append(inner[start:pos])
+ start = pos + 1
+ parts.append(inner[start:])
+ return [p.strip() for p in parts]
+
+ if lower.startswith("array<") and lower.endswith(">"):
+ return f"{_hive_to_duckdb_type(text[6:-1])}[]"
+ if lower.startswith("map<") and lower.endswith(">"):
+ key, value = split_args(text[4:-1])
+ return f"MAP({_hive_to_duckdb_type(key)}, {_hive_to_duckdb_type(value)})"
+ if lower.startswith("struct<") and lower.endswith(">"):
+ fields = []
+ for field in split_args(text[7:-1]):
+ name, _, ftype = field.partition(":")
+ fields.append(f'"{name.strip()}" {_hive_to_duckdb_type(ftype)}')
+ return f"STRUCT({', '.join(fields)})"
+ if lower.startswith("decimal"):
+ return text.upper()
+ from ministack.services.athena import _DUCKDB_TYPE_BY_ATHENA
+
+ return _DUCKDB_TYPE_BY_ATHENA.get(lower.split("(")[0], "VARCHAR")
+
+
+def _json_documents(data):
+ """The JSON objects in a record: one, or several concatenated."""
+ try:
+ text = data.decode("utf-8")
+ except UnicodeDecodeError as exc:
+ raise _conversion_error("malformed") from exc
+ if not text.strip():
+ raise _conversion_error("empty")
+ decoder, pos, documents = json.JSONDecoder(), 0, []
+ while True:
+ while pos < len(text) and text[pos].isspace():
+ pos += 1
+ if pos >= len(text):
+ return documents
try:
- loop = asyncio.get_running_loop()
- loop.create_task(_put())
- except RuntimeError:
- asyncio.run(_put())
+ document, pos = decoder.raw_decode(text, pos)
+ except ValueError as exc:
+ raise _conversion_error("malformed") from exc
+ if not isinstance(document, dict):
+ raise _conversion_error("primitive" if not isinstance(document, list) else "mismatch")
+ documents.append(document)
+
+
+def _convert_to_parquet(conversion, data):
+ """JSON record to a Parquet object with the Glue table's columns, or a _DeliveryError."""
+ serializer = ((conversion.get("OutputFormatConfiguration") or {}).get("Serializer") or {})
+ if "ParquetSerDe" not in serializer:
+ raise _conversion_error("unsupported")
+ schema = conversion.get("SchemaConfiguration") or {}
+ from ministack.services import glue as glue_svc
+
+ table = glue_svc._tables.get(f"{schema.get('DatabaseName', '')}/{schema.get('TableName', '')}")
+ columns = ((table or {}).get("StorageDescriptor") or {}).get("Columns") or []
+ if not columns:
+ raise _conversion_error("table")
+ deserializer = ((conversion.get("InputFormatConfiguration") or {}).get("Deserializer") or {})
+ openx = deserializer.get("OpenXJsonSerDe")
+ case_insensitive = True if openx is None else openx.get("CaseInsensitive", True)
+ dots_to_underscores = bool(openx and openx.get("ConvertDotsInJsonKeysToUnderscores"))
+ key_mappings = (openx or {}).get("ColumnToJsonKeyMappings") or {}
+
+ rows = []
+ for document in _json_documents(data):
+ fields = {}
+ for key, value in document.items():
+ name = key.replace(".", "_") if dots_to_underscores else key
+ fields[name.lower() if case_insensitive else name] = value
+ row = []
+ for column in columns:
+ name = column["Name"]
+ source = key_mappings.get(name, name)
+ row.append(fields.get(source.lower() if case_insensitive else source))
+ rows.append(row)
+
+ try:
+ import duckdb
+ except ImportError as exc:
+ logger.warning("Firehose record format conversion needs DuckDB (the full image)")
+ raise _conversion_error("unsupported") from exc
+ import tempfile
+
+ compression = {"GZIP": "gzip", "UNCOMPRESSED": "uncompressed"}.get(
+ (serializer.get("ParquetSerDe") or {}).get("Compression", "SNAPPY"), "snappy")
+ definition = ", ".join(f'"{c["Name"]}" {_hive_to_duckdb_type(c.get("Type", "string"))}' for c in columns)
+ with tempfile.TemporaryDirectory() as tmp:
+ path = os.path.join(tmp, "out.parquet")
+ con = duckdb.connect()
+ try:
+ con.execute(f"CREATE TABLE t ({definition})")
+ con.executemany(f"INSERT INTO t VALUES ({', '.join('?' for _ in columns)})", rows)
+ con.execute(f"COPY t TO '{path}' (FORMAT PARQUET, COMPRESSION {compression})")
+ except duckdb.Error as exc:
+ raise _conversion_error("mismatch") from exc
+ finally:
+ con.close()
+ with open(path, "rb") as fh:
+ return fh.read()
+
+
+def _put_s3_object(bucket, key, body):
+ from ministack.services import s3 as s3_svc
+
+ async def _put():
+ headers = {"content-type": "application/octet-stream", "content-length": str(len(body)),
+ "host": "s3.localhost"}
+ await s3_svc.handle_request("PUT", f"/{bucket}/{key}", headers, body, {})
+
+ try:
+ asyncio.get_running_loop().create_task(_put())
+ except RuntimeError:
+ asyncio.run(_put())
+
+
+def _arrival_time(cfg):
+ zone = cfg.get("CustomTimeZone")
+ if zone and zone != "UTC":
+ try:
+ import datetime
+ from zoneinfo import ZoneInfo
+
+ return datetime.datetime.now(ZoneInfo(zone)).timetuple()
+ except Exception:
+ pass
+ return time.gmtime()
+
+
+def _deliver_to_s3(stream: dict, dest: dict, record_data: bytes, lambda_keys=None):
+ """Deliver one record: partition keys, format conversion, evaluated prefix, AWS object name."""
+ try:
+ cfg = dest["config"]
+ bucket = _s3_bucket_from_arn(cfg.get("BucketARN", ""))
+ t = _arrival_time(cfg)
+ suffix = f"{stream['name']}-{stream.get('version', 1)}-{_java_time('yyyy-MM-dd-HH-mm-ss', t)}-{new_uuid()}"
+ conversion = cfg.get("DataFormatConversionConfiguration") or {}
+ try:
+ query_keys = None
+ if (cfg.get("DynamicPartitioningConfiguration") or {}).get("Enabled"):
+ query_keys = _metadata_extraction_keys(cfg, record_data)
+ prefix = _evaluate_prefix(cfg.get("Prefix", ""), t, query_keys, lambda_keys)
+ body, extension = record_data, ""
+ if conversion and conversion.get("Enabled", True):
+ body, extension = _convert_to_parquet(conversion, record_data), ".parquet"
+ _put_s3_object(bucket, f"{prefix}{suffix}{cfg.get('FileExtension') or extension}", body)
+ except _DeliveryError as err:
+ now_ms = int(time.time() * 1000)
+ document = {"attemptsMade": 1, "arrivalTimestamp": now_ms, "attemptEndingTimestamp": now_ms,
+ "rawData": base64.b64encode(record_data).decode()}
+ if err.code:
+ document["ErrorCode"] = err.code
+ document["ErrorMessage"] = err.message
+ if err.output_type == "format-conversion-failed":
+ schema = conversion.get("SchemaConfiguration") or {}
+ document["dataCatalogTable"] = {
+ "catalogId": schema.get("CatalogId") or get_account_id(),
+ "databaseName": schema.get("DatabaseName"), "tableName": schema.get("TableName"),
+ "region": schema.get("Region") or get_region(), "versionId": schema.get("VersionId", "LATEST")}
+ error_prefix = cfg.get("ErrorOutputPrefix")
+ if error_prefix:
+ prefix = _evaluate_prefix(error_prefix, t, error_type=err.output_type)
+ else:
+ prefix = f"{cfg.get('Prefix', '')}{err.output_type}/{_java_time('yyyy/MM/dd/HH/', t)}"
+ _put_s3_object(bucket, f"{prefix}{suffix}", (json.dumps(document) + "\n").encode())
except Exception as e:
logger.warning("Firehose S3 delivery failed: %s", e)
+def _deliver_records_to_s3(stream: dict, dest: dict, records: list):
+ """Run the processors over ``records`` [(recordId, bytes)] and deliver each result to S3."""
+ partition_keys = {}
+ for rid, payload in _apply_lambda_processors(stream, dest, records, partition_sink=partition_keys):
+ _deliver_to_s3(stream, dest, payload, partition_keys.get(rid))
+
+
def _gateway_port() -> str:
return os.environ.get("GATEWAY_PORT", "4566")
@@ -605,8 +1008,7 @@ def ingest_from_kinesis_source(stream_arn: str, records: list) -> None:
plan.append((stream, dest, rid, raw))
for stream, dest, rid, raw in plan:
try:
- for _rid, payload in _apply_lambda_processors(stream, dest, [(rid, raw)]):
- _deliver_to_s3(stream, dest, payload)
+ _deliver_records_to_s3(stream, dest, [(rid, raw)])
except Exception as exc:
logger.warning(
"Firehose Kinesis-source delivery to %s failed: %s",
@@ -770,9 +1172,7 @@ 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"):
- # Apply ProcessingConfiguration.Lambda transforms before S3.
- for _rid, payload in _apply_lambda_processors(stream, dest, [(record_id, decoded)]):
- _deliver_to_s3(stream, dest, payload)
+ _deliver_records_to_s3(stream, dest, [(record_id, decoded)])
elif dest["type"] == "Iceberg":
_deliver_to_iceberg(stream, dest, [(record_id, decoded)])
@@ -807,8 +1207,7 @@ 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"):
- for _rid, payload in _apply_lambda_processors(stream, dest, [(record_id, decoded)]):
- _deliver_to_s3(stream, dest, payload)
+ _deliver_records_to_s3(stream, dest, [(record_id, decoded)])
elif dest["type"] == "Iceberg":
_deliver_to_iceberg(stream, dest, [(record_id, decoded)])
responses.append({"RecordId": record_id, "Encrypted": False})
diff --git a/ministack/services/iam.py b/ministack/services/iam.py
index cf261216..03a87293 100644
--- a/ministack/services/iam.py
+++ b/ministack/services/iam.py
@@ -9,6 +9,7 @@ IAM actions:
CreateUser, GetUser, ListUsers, DeleteUser,
CreateRole, GetRole, ListRoles, DeleteRole,
UpdateRoleDescription, PutRolePermissionsBoundary, DeleteRolePermissionsBoundary,
+ PutUserPermissionsBoundary, DeleteUserPermissionsBoundary,
CreatePolicy, GetPolicy, GetPolicyVersion, ListPolicyVersions, ListPolicies, DeletePolicy,
CreatePolicyVersion, DeletePolicyVersion,
AttachRolePolicy, DetachRolePolicy, ListAttachedRolePolicies,
@@ -426,6 +427,7 @@ def _create_user(p):
"UserId": _gen_id("AIDA"),
"CreateDate": _now(),
"Path": path,
+ "PermissionsBoundary": _p(p, "PermissionsBoundary"),
"AttachedPolicies": [],
"Tags": _extract_tags(p),
}
@@ -467,6 +469,26 @@ def _list_users(p):
ns="iam")
+def _put_user_permissions_boundary(p):
+ name = _p(p, "UserName")
+ user = _users.get(name)
+ if not user:
+ return _error(404, "NoSuchEntity",
+ f"The user with name {name} cannot be found.", ns="iam")
+ user["PermissionsBoundary"] = _p(p, "PermissionsBoundary")
+ return _xml(200, "PutUserPermissionsBoundaryResponse", "", ns="iam")
+
+
+def _delete_user_permissions_boundary(p):
+ name = _p(p, "UserName")
+ user = _users.get(name)
+ if not user:
+ return _error(404, "NoSuchEntity",
+ f"The user with name {name} cannot be found.", ns="iam")
+ user["PermissionsBoundary"] = None
+ return _xml(200, "DeleteUserPermissionsBoundaryResponse", "", ns="iam")
+
+
def _delete_user(p):
name = _p(p, "UserName")
user = _users.get(name)
@@ -2945,11 +2967,20 @@ def _user_xml(name):
for t in u["Tags"]
)
tags_xml = f"<Tags>{tag_members}</Tags>"
+ boundary_xml = ""
+ if u.get("PermissionsBoundary"):
+ boundary_xml = (
+ "<PermissionsBoundary>"
+ "<PermissionsBoundaryType>PermissionsBoundaryPolicy</PermissionsBoundaryType>"
+ f"<PermissionsBoundaryArn>{u['PermissionsBoundary']}</PermissionsBoundaryArn>"
+ "</PermissionsBoundary>"
+ )
return (f"<UserName>{u['UserName']}</UserName>"
f"<UserId>{u['UserId']}</UserId>"
f"<Arn>{u['Arn']}</Arn>"
f"<Path>{u['Path']}</Path>"
f"<CreateDate>{u['CreateDate']}</CreateDate>"
+ f"{boundary_xml}"
f"{tags_xml}")
@@ -3129,6 +3160,8 @@ _IAM_HANDLERS = {
"UpdateAssumeRolePolicy": _update_assume_role_policy,
"UpdateRoleDescription": _update_role_description,
"PutRolePermissionsBoundary": _put_role_permissions_boundary,
+ "PutUserPermissionsBoundary": _put_user_permissions_boundary,
+ "DeleteUserPermissionsBoundary": _delete_user_permissions_boundary,
"DeleteRolePermissionsBoundary": _delete_role_permissions_boundary,
"TagRole": _tag_role,
"UntagRole": _untag_role,
diff --git a/tests/test_alb.py b/tests/test_alb.py
index 43f1ab4b..2d4f6580 100644
--- a/tests/test_alb.py
+++ b/tests/test_alb.py
@@ -1896,3 +1896,37 @@ def test_alb_describe_lbs_validates_name_length_before_existence(elbv2):
with pytest.raises(ClientError) as exc:
elbv2.describe_load_balancers(Names=["definitely-not-there"])
assert exc.value.response["Error"]["Code"] == "LoadBalancerNotFound"
+
+
+def test_alb_http_header_condition_round_trips_and_matches(elbv2):
+ """An http-header condition keeps its HttpHeaderConfig, and the data plane matches
+ the header name and values case-insensitively with * and ? wildcards."""
+ name = f"hdr-{_uuid_mod.uuid4().hex[:8]}"
+ lb_arn = elbv2.create_load_balancer(Name=name, Subnets=["subnet-1"])["LoadBalancers"][0]["LoadBalancerArn"]
+
+ def fixed(body):
+ return {"Type": "fixed-response",
+ "FixedResponseConfig": {"StatusCode": "200", "ContentType": "text/plain", "MessageBody": body}}
+
+ l_arn = elbv2.create_listener(LoadBalancerArn=lb_arn, Protocol="HTTP", Port=80,
+ DefaultActions=[fixed("default")])["Listeners"][0]["ListenerArn"]
+ header = {"HttpHeaderName": "X-Example-Origin-Token", "Values": ["example-token", "tok?n-*"]}
+ try:
+ elbv2.create_rule(ListenerArn=l_arn, Priority=1,
+ Conditions=[{"Field": "http-header", "HttpHeaderConfig": header}],
+ Actions=[fixed("matched")])
+ rule = next(r for r in elbv2.describe_rules(ListenerArn=l_arn)["Rules"] if r["Priority"] == "1")
+ assert rule["Conditions"][0]["Field"] == "http-header"
+ assert rule["Conditions"][0]["HttpHeaderConfig"] == header
+
+ def body(headers):
+ return _req.urlopen(_req.Request(f"{_endpoint}/_alb/{name}/", headers=headers)).read()
+
+ assert body({"x-example-origin-token": "example-token"}) == b"matched"
+ assert body({"X-EXAMPLE-ORIGIN-TOKEN": "EXAMPLE-TOKEN"}) == b"matched"
+ assert body({"X-Example-Origin-Token": "token-123"}) == b"matched"
+ assert body({"X-Example-Origin-Token": "wrong"}) == b"default"
+ assert body({}) == b"default"
+ finally:
+ elbv2.delete_listener(ListenerArn=l_arn)
+ elbv2.delete_load_balancer(LoadBalancerArn=lb_arn)
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 0b20c545..71110ec1 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -34692,3 +34692,117 @@ def test_cfn_docdb_cluster_lifecycle(cfn, sm):
assert _wait_stack(cfn, stack, timeout=120)["StackStatus"] == "DELETE_COMPLETE"
with pytest.raises(ClientError):
docdb.describe_db_clusters(DBClusterIdentifier=outputs["ClusterId"])
+
+
+def test_cfn_elbv2_listener_rule_keeps_http_header_config(cfn, elbv2):
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-hdr-{uid}"
+ header = {"HttpHeaderName": "X-Origin-Token", "Values": ["secret"]}
+ template = json.loads(_cfn_elbv2_template(uid))
+ template["Resources"]["R"]["Properties"]["Conditions"] = [
+ {"Field": "http-header", "HttpHeaderConfig": header}]
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ rule = elbv2.describe_rules(RuleArns=[_output(stack, "RuleRef")])["Rules"][0]
+ assert rule["Conditions"][0]["HttpHeaderConfig"] == header
+ finally:
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+
+
+def _cfn_iam_user_template(group_names, policy_doc, login, tags, path="/", user_name=None, boundary=None):
+ user = {"Groups": list(group_names),
+ "ManagedPolicyArns": [{"Ref": "Managed"}],
+ "Policies": [{"PolicyName": "inline", "PolicyDocument": policy_doc}],
+ "Path": path, "Tags": tags}
+ if login:
+ user["LoginProfile"] = login
+ if user_name:
+ user["UserName"] = user_name
+ if boundary:
+ user["PermissionsBoundary"] = boundary
+ doc = {"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "s3:ListBucket", "Resource": "*"}]}
+ return json.dumps({
+ "Resources": {
+ "Managed": {"Type": "AWS::IAM::ManagedPolicy", "Properties": {"PolicyDocument": doc}},
+ "User": {"Type": "AWS::IAM::User", "Properties": user},
+ },
+ "Outputs": {"UserRef": {"Value": {"Ref": "User"}},
+ "UserArn": {"Value": {"Fn::GetAtt": ["User", "Arn"]}},
+ "ManagedArn": {"Value": {"Ref": "Managed"}}},
+ })
+
+
+def test_cfn_iam_user_lifecycle(cfn, iam):
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-user-{uid}"
+ allow = {"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]}
+ deny = {"Version": "2012-10-17", "Statement": [{"Effect": "Deny", "Action": "s3:*", "Resource": "*"}]}
+ boundary = "arn:aws:iam::aws:policy/PowerUserAccess"
+ group_a, group_b = f"ga-{uid}", f"gb-{uid}"
+ iam.create_group(GroupName=group_a)
+ iam.create_group(GroupName=group_b)
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_iam_user_template(
+ [group_a, group_b], allow, {"Password": "Initial-Passw0rd!", "PasswordResetRequired": True},
+ [{"Key": "team", "Value": "a"}], user_name=f"named-{uid}", boundary=boundary))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ name = _output(stack, "UserRef")
+ assert name == f"named-{uid}"
+ user = iam.get_user(UserName=name)["User"]
+ assert _output(stack, "UserArn") == user["Arn"] == f"arn:aws:iam::000000000000:user/{name}"
+ assert user["PermissionsBoundary"]["PermissionsBoundaryArn"] == boundary
+ assert [t for t in user["Tags"] if not t["Key"].startswith("aws:")] == [{"Key": "team", "Value": "a"}]
+ groups = {g["GroupName"] for g in iam.list_groups_for_user(UserName=name)["Groups"]}
+ assert groups == {group_a, group_b}
+ attached = [p["PolicyArn"] for p in iam.list_attached_user_policies(UserName=name)["AttachedPolicies"]]
+ assert attached == [_output(stack, "ManagedArn")]
+ assert iam.list_user_policies(UserName=name)["PolicyNames"] == ["inline"]
+ assert iam.get_login_profile(UserName=name)["LoginProfile"]["PasswordResetRequired"] is True
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_iam_user_template(
+ [group_a], deny, None, [{"Key": "team", "Value": "b"}], path="/ops/", user_name=f"named-{uid}"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ user = iam.get_user(UserName=name)["User"]
+ assert user["Path"] == "/ops/" and user["Arn"] == f"arn:aws:iam::000000000000:user/ops/{name}"
+ assert _output(stack, "UserArn") == user["Arn"]
+ assert "PermissionsBoundary" not in user
+ assert [t for t in user["Tags"] if not t["Key"].startswith("aws:")] == [{"Key": "team", "Value": "b"}]
+ groups = {g["GroupName"] for g in iam.list_groups_for_user(UserName=name)["Groups"]}
+ assert groups == {group_a}
+ doc = iam.get_user_policy(UserName=name, PolicyName="inline")["PolicyDocument"]
+ doc = json.loads(doc) if isinstance(doc, str) else doc
+ assert doc["Statement"][0]["Effect"] == "Deny"
+ with pytest.raises(ClientError) as exc:
+ iam.get_login_profile(UserName=name)
+ assert exc.value.response["Error"]["Code"] == "NoSuchEntity"
+ finally:
+ cfn.delete_stack(StackName=stack_name)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"
+ with pytest.raises(ClientError) as exc:
+ iam.get_user(UserName=f"named-{uid}")
+ assert exc.value.response["Error"]["Code"] == "NoSuchEntity"
+ assert iam.get_group(GroupName=group_a)["Users"] == []
+ iam.delete_group(GroupName=group_a)
+ iam.delete_group(GroupName=group_b)
+
+
+def test_cfn_iam_user_generated_name(cfn, iam):
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-genuser-{uid}"
+ template = json.dumps({"Resources": {"User": {"Type": "AWS::IAM::User"}},
+ "Outputs": {"UserRef": {"Value": {"Ref": "User"}}}})
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ name = _output(stack, "UserRef")
+ assert name.startswith(stack_name)
+ assert iam.get_user(UserName=name)["User"]["Path"] == "/"
+ finally:
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
diff --git a/tests/test_firehose.py b/tests/test_firehose.py
index bde325f6..ed036389 100644
--- a/tests/test_firehose.py
+++ b/tests/test_firehose.py
@@ -1,6 +1,8 @@
+import base64
import io
import json
import os
+import re
import time
import uuid as _uuid_mod
import zipfile
@@ -949,3 +951,127 @@ def test_firehose_iceberg_delivery_writes_queryable_rows(fh):
assert rows == [(1, "alice")]
finally:
fh.delete_delivery_stream(DeliveryStreamName=stream)
+
+
+def _wait_objects(s3, bucket, prefix, count=1):
+ for _ in range(40):
+ objs = s3.list_objects_v2(Bucket=bucket, Prefix=prefix).get("Contents", [])
+ if len(objs) >= count:
+ return objs
+ time.sleep(0.1)
+ return s3.list_objects_v2(Bucket=bucket, Prefix=prefix).get("Contents", [])
+
+
+def _partitioned_parquet_stream(fh, glue, s3, suffix, query):
+ bucket, database, name = f"fh-dp-{suffix}", f"fh_dp_{suffix}", f"fh-dp-{suffix}"
+ s3.create_bucket(Bucket=bucket)
+ glue.create_database(DatabaseInput={"Name": database})
+ glue.create_table(DatabaseName=database, TableInput={"Name": "events", "StorageDescriptor": {
+ "Columns": [{"Name": "timestamp", "Type": "string"}, {"Name": "action", "Type": "int"}],
+ "Location": f"s3://{bucket}/usage/"}})
+ fh.create_delivery_stream(DeliveryStreamName=name, DeliveryStreamType="DirectPut",
+ ExtendedS3DestinationConfiguration={
+ "RoleARN": "arn:aws:iam::000000000000:role/firehose", "BucketARN": f"arn:aws:s3:::{bucket}",
+ "Prefix": "usage/year=!{partitionKeyFromQuery:year}/month=!{partitionKeyFromQuery:month}/"
+ "day=!{partitionKeyFromQuery:day}/",
+ "ErrorOutputPrefix": "errors/!{firehose:error-output-type}/",
+ "DynamicPartitioningConfiguration": {"Enabled": True},
+ "ProcessingConfiguration": {"Enabled": True, "Processors": [{"Type": "MetadataExtraction", "Parameters": [
+ {"ParameterName": "JsonParsingEngine", "ParameterValue": "JQ-1.6"},
+ {"ParameterName": "MetadataExtractionQuery", "ParameterValue": query}]}]},
+ "DataFormatConversionConfiguration": {"Enabled": True, "SchemaConfiguration": {
+ "RoleARN": "arn:aws:iam::000000000000:role/firehose", "DatabaseName": database,
+ "TableName": "events", "Region": "us-east-1"},
+ "InputFormatConfiguration": {"Deserializer": {"HiveJsonSerDe": {}}},
+ "OutputFormatConfiguration": {"Serializer": {"ParquetSerDe": {"Compression": "SNAPPY"}}}},
+ })
+ return bucket, name
+
+
+def test_firehose_dynamic_partitioning_writes_parquet(fh, glue, s3, tmp_path):
+ duckdb = pytest.importorskip("duckdb")
+ bucket, name = _partitioned_parquet_stream(
+ fh, glue, s3, _uuid_mod.uuid4().hex[:8],
+ "{year: .timestamp[0:4], month: .timestamp[5:7], day: .timestamp[8:10]}")
+ fh.put_record(DeliveryStreamName=name,
+ Record={"Data": json.dumps({"timestamp": "2026-04-23T11:30:00Z", "action": 1})})
+ objs = _wait_objects(s3, bucket, "usage/")
+ assert len(objs) == 1, objs
+ key = objs[0]["Key"]
+ # No timestamp expression in the prefix, so Firehose appends yyyy/MM/dd/HH/.
+ assert re.fullmatch(rf"usage/year=2026/month=04/day=23/\d{{4}}/\d{{2}}/\d{{2}}/\d{{2}}/{name}-1-"
+ r"\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}-[0-9a-f-]{36}\.parquet", key), key
+ body = s3.get_object(Bucket=bucket, Key=key)["Body"].read()
+ assert body[:4] == b"PAR1" and body[-4:] == b"PAR1"
+ path = tmp_path / "out.parquet"
+ path.write_bytes(body)
+ con = duckdb.connect()
+ assert con.execute(f"SELECT * FROM '{path}'").fetchall() == [("2026-04-23T11:30:00Z", 1)]
+ assert con.execute(f"SELECT DISTINCT compression FROM parquet_metadata('{path}')").fetchall() == [("SNAPPY",)]
+
+
+def test_firehose_failed_records_go_to_the_error_prefix(fh, glue, s3):
+ pytest.importorskip("duckdb")
+ bucket, name = _partitioned_parquet_stream(
+ fh, glue, s3, _uuid_mod.uuid4().hex[:8], "{year: .timestamp[0:4], month: .month, day: .day}")
+ missing_key = json.dumps({"timestamp": "2026-04-23T11:30:00Z", "action": 1})
+ fh.put_record(DeliveryStreamName=name, Record={"Data": missing_key})
+ failed = _wait_objects(s3, bucket, "errors/processing-failed/")
+ assert len(failed) == 1, failed
+ document = json.loads(s3.get_object(Bucket=bucket, Key=failed[0]["Key"])["Body"].read())
+ assert base64.b64decode(document["rawData"]).decode() == missing_key
+ assert {"attemptsMade", "arrivalTimestamp", "attemptEndingTimestamp", "ErrorMessage"} <= set(document)
+
+ bad_type = json.dumps({"timestamp": "2026-04-23T11:30:00Z", "action": "abc", "month": "04", "day": "23"})
+ fh.put_record(DeliveryStreamName=name, Record={"Data": bad_type})
+ failed = _wait_objects(s3, bucket, "errors/format-conversion-failed/")
+ assert len(failed) == 1, failed
+ document = json.loads(s3.get_object(Bucket=bucket, Key=failed[0]["Key"])["Body"].read())
+ assert document["ErrorCode"] == "DataFormatConversion.MalformedData"
+ assert document["ErrorMessage"] == "Data does not match the schema."
+ assert document["dataCatalogTable"]["tableName"] == "events"
+ assert not s3.list_objects_v2(Bucket=bucket, Prefix="usage/").get("Contents")
+
+
+def test_firehose_prefix_timestamp_expressions_replace_the_default(fh, s3):
+ suffix = _uuid_mod.uuid4().hex[:8]
+ bucket, name = f"fh-ts-{suffix}", f"fh-ts-{suffix}"
+ s3.create_bucket(Bucket=bucket)
+ fh.create_delivery_stream(DeliveryStreamName=name, ExtendedS3DestinationConfiguration={
+ "RoleARN": "arn:aws:iam::000000000000:role/firehose", "BucketARN": f"arn:aws:s3:::{bucket}",
+ "Prefix": "logs/year=!{timestamp:yyyy}/", "ErrorOutputPrefix": "errors/!{firehose:error-output-type}/"})
+ fh.put_record(DeliveryStreamName=name, Record={"Data": b"raw"})
+ objs = _wait_objects(s3, bucket, "logs/")
+ assert len(objs) == 1
+ assert re.fullmatch(rf"logs/year=\d{{4}}/{name}-1-\d{{4}}(-\d{{2}}){{5}}-[0-9a-f-]{{36}}", objs[0]["Key"]), objs
+ assert s3.get_object(Bucket=bucket, Key=objs[0]["Key"])["Body"].read() == b"raw"
+
+
+def test_firehose_partition_keys_from_lambda(fh, s3, lam):
+ suffix = _uuid_mod.uuid4().hex[:8]
+ bucket, fn, name = f"fh-lk-{suffix}", f"fh-lk-fn-{suffix}", f"fh-lk-{suffix}"
+ s3.create_bucket(Bucket=bucket)
+ handler = (
+ "import base64, json\n"
+ "def handler(event, context):\n"
+ " out = []\n"
+ " for r in event['records']:\n"
+ " doc = json.loads(base64.b64decode(r['data']))\n"
+ " out.append({'recordId': r['recordId'], 'result': 'Ok', 'data': r['data'],\n"
+ " 'metadata': {'partitionKeys': {'customer': doc['customer']}}})\n"
+ " return {'records': out}\n"
+ )
+ arn = _make_processor_fn(lam, fn, handler)
+ fh.create_delivery_stream(DeliveryStreamName=name, ExtendedS3DestinationConfiguration={
+ "RoleARN": "arn:aws:iam::000000000000:role/firehose", "BucketARN": f"arn:aws:s3:::{bucket}",
+ "Prefix": "c=!{partitionKeyFromLambda:customer}/", "ErrorOutputPrefix": "errors/!{firehose:error-output-type}/",
+ "DynamicPartitioningConfiguration": {"Enabled": True},
+ "ProcessingConfiguration": {"Enabled": True, "Processors": [{"Type": "Lambda", "Parameters": [
+ {"ParameterName": "LambdaArn", "ParameterValue": arn}]}]}})
+ try:
+ fh.put_record(DeliveryStreamName=name, Record={"Data": json.dumps({"customer": "acme"})})
+ objs = _wait_objects(s3, bucket, "c=acme/")
+ assert len(objs) == 1, s3.list_objects_v2(Bucket=bucket).get("Contents")
+ finally:
+ fh.delete_delivery_stream(DeliveryStreamName=name)
+ lam.delete_function(FunctionName=fn)
diff --git a/tests/test_iam.py b/tests/test_iam.py
index 661dd049..b501095d 100644
--- a/tests/test_iam.py
+++ b/tests/test_iam.py
@@ -127,6 +127,35 @@ def test_iam_role_permissions_boundary_missing_role(iam, operation):
iam.delete_role_permissions_boundary(RoleName=name)
assert exc.value.response["Error"]["Code"] == "NoSuchEntity"
+def test_iam_user_permissions_boundary_roundtrip(iam):
+ name = f"boundary-user-{_uuid_mod.uuid4().hex[:8]}"
+ original_boundary = "arn:aws:iam::000000000000:policy/original-boundary"
+ replacement_boundary = "arn:aws:iam::000000000000:policy/replacement-boundary"
+
+ created = iam.create_user(UserName=name, PermissionsBoundary=original_boundary)["User"]
+ assert created["PermissionsBoundary"] == {
+ "PermissionsBoundaryType": "PermissionsBoundaryPolicy",
+ "PermissionsBoundaryArn": original_boundary,
+ }
+ iam.put_user_permissions_boundary(UserName=name, PermissionsBoundary=replacement_boundary)
+ assert iam.get_user(UserName=name)["User"]["PermissionsBoundary"]["PermissionsBoundaryArn"] == replacement_boundary
+ iam.delete_user_permissions_boundary(UserName=name)
+ assert "PermissionsBoundary" not in iam.get_user(UserName=name)["User"]
+ iam.delete_user(UserName=name)
+
+
[email protected]("operation", ["put", "delete"])
+def test_iam_user_permissions_boundary_missing_user(iam, operation):
+ name = f"missing-boundary-user-{_uuid_mod.uuid4().hex[:8]}"
+ with pytest.raises(ClientError) as exc:
+ if operation == "put":
+ iam.put_user_permissions_boundary(
+ UserName=name, PermissionsBoundary="arn:aws:iam::000000000000:policy/boundary")
+ else:
+ iam.delete_user_permissions_boundary(UserName=name)
+ assert exc.value.response["Error"]["Code"] == "NoSuchEntity"
+
+
def test_iam_list_roles(iam):
resp = iam.list_roles()
names = [r["RoleName"] for r in resp["Roles"]]