Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
prerelease-b (#1970)
Nahuel Nucera29495b4e531d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 51f5660c..c0c91d18 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,17 +9,17 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added+- **API Gateway v2 — custom domain names and API mappings** — `CreateDomainName`, `GetDomainName`, `GetDomainNames`, `UpdateDomainName`, `DeleteDomainName` and `Create`/`Get`/`Update`/`DeleteApiMapping(s)`, with domain tags through `TagResource`, list pagination, and `BadRequestException` "Invalid stage identifier specified" for a mapping to a missing stage; `AWS::ApiGatewayV2::DomainName` and `AWS::ApiGatewayV2::ApiMapping` in CloudFormation. A domain and its mappings are the same resource as the API Gateway v1 domain and base path mappings, and a request whose `Host` is the domain reaches the mapped HTTP API. Reported by @wparad.- **CloudFormation — stack updates replace resources** — a change to a property the change set reports as `RequiresRecreation: Always` now creates a new resource under a new generated name, points its dependents at it and deletes the old one after the update succeeds (a rollback deletes the new one instead). With an explicit, unchanged name the update fails with the AWS message naming the physical id; this now also covers `AWS::Lambda::Function`. A named SQS queue or SNS topic fails with AWS's already-exists error instead and keeps its messages or subscriptions.-- **CloudFormation — `AWS::EFS::FileSystem`, `AWS::EFS::MountTarget` and `AWS::EFS::AccessPoint`** — a template with an EFS resource failed validation with `Unrecognized resource types`. The three types now create, update and delete through the EFS store, so CDK `efs.FileSystem` stacks deploy. `Ref` and `Fn::GetAtt` follow the CloudFormation reference; `FileSystemPolicy`, `LifecyclePolicies`, `BackupPolicy`, `ThroughputMode`, `ProvisionedThroughputInMibps`, `FileSystemTags`, mount target `SecurityGroups` and `AccessPointTags` update in place, and the create-only properties replace the resource. `FileSystemProtection`, `ReplicationConfiguration` and `BypassPolicyLockoutSafetyCheck` are supported too.-- **EFS — policy, protection and replication operations; stricter mount targets** — added `PutFileSystemPolicy` (rejects malformed policies and an unconditional Deny of `PutFileSystemPolicy` with `InvalidPolicyException` unless `BypassPolicyLockoutSafetyCheck` is set; fills in `Id`, `Sid` and `Resource` as the API reference examples show), `DescribeFileSystemPolicy` (`PolicyNotFound` when none is set), `DeleteFileSystemPolicy`, `UpdateFileSystemProtection`, and `CreateReplicationConfiguration` / `DescribeReplicationConfigurations` / `DeleteReplicationConfiguration` (the destination file system is created, or an existing one with protection `DISABLED` used, and is `REPLICATING` until the configuration is deleted). File systems report `FileSystemProtection` (default `ENABLED`) and `AvailabilityZoneName`, and a file system in a replication configuration cannot be deleted. `CreateMountTarget` now checks the subnet (`SubnetNotFound`), security groups in the subnet's VPC (`SecurityGroupNotFound`, default group when none given), one mount target per zone and VPC (`MountTargetConflict`), One Zone file systems (`AvailabilityZonesMismatch`), and takes `IpAddress` from the subnet range (`IpAddressInUse`, `NoFreeAddressesInSubnet`); `IpAddressType` other than `IPV4_ONLY` needs a subnet with an IPv6 CIDR block, which MiniStack's EC2 subnets do not have yet. `DeleteFileSystem` with mount targets now answers 409, as the API reference says, and a deleted file system no longer leaves its lifecycle and backup settings behind.+- **CloudFormation — `AWS::EFS::FileSystem`, `AWS::EFS::MountTarget` and `AWS::EFS::AccessPoint`** — the three types create, update in place and are replaced on create-only changes through the EFS store, with `Ref` and `Fn::GetAtt` as in the template reference, so CDK `efs.FileSystem` stacks deploy. Contributed by @fabio-andre-rodrigues.+- **EFS — file system policy, protection and replication** — `PutFileSystemPolicy`, `DescribeFileSystemPolicy`, `DeleteFileSystemPolicy`, `UpdateFileSystemProtection` and `Create`/`Describe`/`DeleteReplicationConfiguration`; `CreateMountTarget` checks the subnet, security groups, zone and address (`SubnetNotFound`, `SecurityGroupNotFound`, `MountTargetConflict`, `AvailabilityZonesMismatch`, `IpAddressInUse`), and `DeleteFileSystem` with mount targets answers 409. Contributed by @fabio-andre-rodrigues.### Fixed+- **Docker — the image healthcheck probes `GATEWAY_PORT`** — it always requested `localhost:4566`, so a container started on another port reported `unhealthy` while serving; it now resolves the port as the server does (`GATEWAY_PORT`, then `EDGE_PORT`, then `4566`). Contributed by @skialpine.- **STS — role trust denies and conditions are enforced** — with `AUTH=true`, `AssumeRole` now rejects matching explicit denies, including `NotAction` exclusions, and evaluates `sts:ExternalId` and `sts:RoleSessionName` conditions before issuing credentials. A denied call registers no session. Local JSON requests use the supplied role ARN for authorization and receive JSON trust-denial errors; Query requests retain XML responses. With `AUTH=false`, trust denies and conditions remain permissive.### Added-- **Bedrock AgentCore — Memory resource lifecycle** — `CreateMemory`, `GetMemory`, `ListMemories`, `UpdateMemory` and `DeleteMemory` now provide account- and region-scoped local resources with pagination. Memory strategies and tagging return explicit validation errors instead of being silently discarded. Contributed by @pingedbrain.-- **CloudFormation — `IMPORT` change sets execute** — existing SQS queues, SSM parameters, S3 buckets, DynamoDB tables, IAM roles, log groups, Lambda functions, IoT policies, IoT CA certificates and Cognito user pools are adopted into a new or existing stack without being changed (`IMPORT_IN_PROGRESS` to `IMPORT_COMPLETE`, or a rollback when a resource is gone), and an import that changes `Outputs` or stack tags is refused, as on AWS.-- **CloudFormation — `Capabilities` check without `AUTH`** — `CFN_ENFORCE_CAPABILITIES=1` refuses a template whose IAM resources or macros the request does not acknowledge also without `AUTH=true`, as AWS always does.+- **Bedrock AgentCore — Memory resources** — `CreateMemory`, `GetMemory`, `ListMemories`, `UpdateMemory` and `DeleteMemory`; memory strategies are recorded without extraction. Contributed by @pingedbrain.- **Athena — databases, DDL, and Trino-style table references** — `ListDatabases` and `GetDatabase` read the Glue Data Catalog; `CREATE EXTERNAL TABLE` and `DROP TABLE` apply to it, creating the Glue table Athena would (formats, SerDe, TBLPROPERTIES); `CREATE TABLE` without `EXTERNAL` is rejected as Athena rejects it, and Iceberg tables are not supported; a query may name a table as `"awsdatacatalog"."db"."t"` or `db.t`. Contributed by @sjincho.- **CloudFront — distributions serve traffic, plus the AWS-managed policies and monitoring subscriptions** — a request to `<label>.cloudfront.net` (or `<label>.cloudfront.<MINISTACK_HOST>`) is served: ordered cache behaviors, `ViewerProtocolPolicy`, `AllowedMethods`, `DefaultRootObject`, cache and origin request policy forwarding (and legacy `ForwardedValues`), `viewer-request` / `viewer-response` CloudFront Functions, response headers policies, and S3 or custom origins; an S3 origin is read only as the bucket policy allows it (OAC, OAI or public). `DomainName` has the AWS `d` + 13-character shape. `List*Policies` return the AWS-managed cache, origin request and response headers policies, and `Create`/`Get`/`DeleteMonitoringSubscription` are implemented. Not modelled: caching, WAF, logging, geo restrictions, custom error pages, signed URLs and cookies, Lambda@Edge. Contributed by @skialpine.- **CloudFormation — EKS cluster and node group updates** — `AWS::EKS::Cluster` applies `Version`, `Logging`, `ResourcesVpcConfig`, `AccessConfig.AuthenticationMode` and `Tags` in place and `AWS::EKS::Nodegroup` applies `ScalingConfig`, `Labels`, `Taints`, `UpdateConfig`, `LaunchTemplate`, `Version`, `ReleaseVersion` and `Tags`, where every such change used to report `UPDATE_COMPLETE` and was dropped. Contributed by @iot-rocket.@@ -31,6 +31,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **Lambda — Node.js and Python functions start in the code directory** — `process.cwd()` and `os.getcwd()` were MiniStack's own directory, so libraries that read files relative to it (such as `node-config`) missed the function's files; the working directory is now the code root (`LAMBDA_TASK_ROOT`), as on AWS. Contributed by @drakeo338. Reported by @shane-patzlsberger.+- **STS — `AssumeRole` honors trust-policy denies and conditions** — with `AUTH=true`, a matching `Deny` (including `NotAction`) overrides an `Allow`, and `sts:ExternalId` and `sts:RoleSessionName` conditions are evaluated; a denied call returns `AccessDenied` and creates no session. Contributed by @AdrianAcala.+- **Cognito — federated sign-in tokens** — the ID token carries the `nonce` from `/oauth2/authorize`, both tokens carry `cognito:groups`, and a user linked by a PreSignUp trigger signs in as the linked profile instead of a new one. Contributed by @kjdev.- **Lambda — Node.js and Python functions start in the code directory** — `process.cwd()` and `os.getcwd()` were MiniStack's own working directory, so libraries that read files relative to the cwd (e.g. `node-config`) missed the function's code; the cwd is now the extracted code root, as `LAMBDA_TASK_ROOT` on AWS- **CloudFormation — nested stack with a `Transform`** — where `Capabilities` are checked, a nested stack whose template declares a `Transform` or calls `Fn::Transform` fails with `Requires capabilities : [CAPABILITY_AUTO_EXPAND]` unless the parent acknowledged `CAPABILITY_AUTO_EXPAND`, as on AWS.- **CloudFormation — `AWS::RDS::DBCluster` and `AWS::RDS::DBInstance` update in place** — a stack update re-ran the create, which gave the resource a new endpoint, resource id and create time and emptied the cluster's member list; the properties the create stores now change on the existing record, a create-only or `Engine` change replaces the resource or, under a custom identifier, is refused, a cluster `MasterUsername` change leaves the cluster as it is, change sets report which properties replace, and a stack-created cluster can now be described and answers `Fn::GetAtt DBClusterResourceId`. Contributed by @iot-rocket.@@ -38,9 +41,6 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **CloudFormation — `AWS::ECS::Cluster` and `AWS::ECS::TaskDefinition` update in place** — a cluster change keeps the cluster (settings or configuration dropped from the template stay), and a task definition change registers the next revision of the family and deregisters the old one instead of overwriting revision 1. Contributed by @iot-rocket.- **CloudFormation — more `IMPORT` types** — SNS topics, KMS keys and aliases, IoT thing types, Cognito user pool clients, groups, resource servers and identity pools, and API Gateway REST APIs and stages can be imported, including two-key identifiers, and `Fn::GetAtt` on an identity pool's `Id` resolves. Contributed by @iot-rocket.- **CloudFormation — `ImportExistingResources`** — a `CREATE` or `UPDATE` change set imports an added resource whose static custom name already exists (it needs `DeletionPolicy` `Retain` or `RetainExceptOnCreate`), and a rollback releases imported resources instead of deleting them. Contributed by @iot-rocket.--### Fixed-- **ECS — `UpdateService` with `forceNewDeployment` replaces the tasks** — it was ignored when the task definition did not change. Rolling deployments now pin image digests from the first task, honor `versionConsistency` `disabled`, use `repositoryCredentials` for private registries, and report `imageDigest` and the Fargate platform version; a task falls back to the local image when the pull fails. Contributed by @AdrianAcala.- **AutoScaling — target tracking alarms** — `PutScalingPolicy` with `TargetTrackingScaling` creates the `TargetTracking-<group>-AlarmHigh-<uuid>` alarm and, unless `DisableScaleIn` is set, the `AlarmLow` one on the tracked metric, lists them in `Alarms` of `PutScalingPolicy` and `DescribePolicies`, replaces them when the policy is updated and deletes them with the policy or its group. An `AWS::AutoScaling::ScalingPolicy` in a template does the same. Contributed by @iot-rocket.- **IoT — mTLS trusts every registered device certificate** — the listener no longer fails the TLS handshake for an ACTIVE certificate whose CA was deactivated or deleted before its first connect, or that was registered without a CA; as on AWS, only the certificate's own status refuses it. Contributed by @iot-rocket.@@ -57,14 +57,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **CloudFormation — `AWS::S3::MultiRegionAccessPoint` and `AWS::AutoScaling::LaunchConfiguration` are replaced on update** — every property of both types is create-only, so a change now creates the resource under a new generated name and deletes the old one after the update (a `Regions` change was dropped and the stack reported the alias as the physical id, a launch configuration was overwritten under its old name), fails with the custom-named-resource error when the name is explicit, and is reported as `Replacement: True` in a change set. Contributed by @iot-rocket.- **CloudFormation — `AWS::SQS::Queue` with `FifoQueue` gets a generated `.fifo` name** — `FifoQueue: true` without a `QueueName` creates a FIFO queue with a generated `.fifo` name instead of a standard queue, and a `QueueName` whose `.fifo` suffix disagrees with `FifoQueue` fails the resource. Contributed by @iot-rocket.- **CloudFormation — nested stack with a `Transform`** — under `AUTH=true`, a nested stack whose template declares a `Transform` or calls `Fn::Transform` fails with `Requires capabilities : [CAPABILITY_AUTO_EXPAND]` unless the parent acknowledged `CAPABILITY_AUTO_EXPAND`, as on AWS. Contributed by @iot-rocket.--### Fixed--- **CloudFormation — `Fn::Select` in a condition** — a condition that checks one member of a `CommaDelimitedList`, such as `!Not [!Equals [!Select [2, !Ref KeySpec], ""]]`, was always true, whatever the parameter value. Templates use this check for an optional member: `"id,S,,"` gives `["id", "S", "", ""]`, and an empty member means "no value". Conditions did not resolve `Fn::Select`, so `Fn::Equals` compared the unresolved function with `""`. Thus the stack made resources whose condition is false, and `Fn::If` took the wrong branch. Conditions now resolve `Fn::Select`, with the same comma split as resource properties. Contributed by @mishukdutta-cz.--### Fixed--- **CloudFormation — `Ref` to a list parameter** — a `Ref` to a `CommaDelimitedList` or `List<...>` parameter gave one string, such as `"attr_a, attr_b"`, not a list. Resource code that loops over a list property used each character as one item: `NonKeyAttributes: !Ref Projected` gave a GSI with the attributes `a`, `t`, `t`, `r`, and so on, and `!Join ["|", !Ref Projected]` gave `a|t|t|r|...`. `Ref` now gives a list, such as `["attr_a", "attr_b"]`. A template that uses this `Ref` as a string can now fail, as on AWS: an output `Value: !Ref Names` or a nested-stack parameter `Names: !Ref Names` rolls back the stack. A string property, such as the `Value` of an `AWS::SSM::Parameter`, now gets the list, not `a,b`. To use the list as one string, use `!Join [",", !Ref Names]`. Contributed by @mishukdutta-cz.+- **CloudFormation — `Fn::Select` in a condition** — a condition such as `!Not [!Equals [!Select [2, !Ref KeySpec], ""]]` was always true; conditions now resolve `Fn::Select`, and an index outside the list fails with `Template error: Fn::Select cannot select nonexistent value at index N`, in conditions and in properties. Contributed by @mishukdutta-cz.+- **CloudFormation — `Ref` to a list parameter** — a `Ref` to a `CommaDelimitedList` or `List<...>` parameter gave the raw string, so a list property got one item per character; it now gives the space-trimmed list. A list in a nested stack's `Parameters` or in an `AWS::SSM::Parameter` `Value` fails the resource. Contributed by @mishukdutta-cz.## [1.5.20] — 2026-10-01diff --git a/Dockerfile b/Dockerfileindex 0b464e89..a94defce 100644--- a/Dockerfile+++ b/Dockerfile@@ -92,6 +92,6 @@ EXPOSE 4566 2222# Pure Python healthcheck — no curl dependency; USE_SSL for HTTP/HTTPS.HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \- CMD python -c "import os,ssl,urllib.request as r; t=os.environ.get('USE_SSL','').strip().lower() in ('1','true','yes'); r.urlopen(('https' if t else 'http')+'://localhost:4566/_ministack/health',context=ssl._create_unverified_context() if t else None)" || exit 1+ CMD python -c "import os,ssl,urllib.request as r; t=os.environ.get('USE_SSL','').strip().lower() in ('1','true','yes'); p=os.environ.get('GATEWAY_PORT') or os.environ.get('EDGE_PORT') or '4566'; r.urlopen(('https' if t else 'http')+'://localhost:'+p+'/_ministack/health',context=ssl._create_unverified_context() if t else None)" || exit 1ENTRYPOINT ["python", "-m", "ministack"]diff --git a/Dockerfile.full b/Dockerfile.fullindex 7d5e3f4e..e21e5a6a 100644--- a/Dockerfile.full+++ b/Dockerfile.full@@ -231,6 +231,6 @@ EXPOSE 4566 2222# Pure Python healthcheck — no curl dependency; USE_SSL for HTTP/HTTPS.HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \- CMD python -c "import os,ssl,urllib.request as r; t=os.environ.get('USE_SSL','').strip().lower() in ('1','true','yes'); r.urlopen(('https' if t else 'http')+'://localhost:4566/_ministack/health',context=ssl._create_unverified_context() if t else None)" || exit 1+ CMD python -c "import os,ssl,urllib.request as r; t=os.environ.get('USE_SSL','').strip().lower() in ('1','true','yes'); p=os.environ.get('GATEWAY_PORT') or os.environ.get('EDGE_PORT') or '4566'; r.urlopen(('https' if t else 'http')+'://localhost:'+p+'/_ministack/health',context=ssl._create_unverified_context() if t else None)" || exit 1ENTRYPOINT ["python", "-m", "ministack"]diff --git a/README.md b/README.mdindex e8fd6af6..6e281517 100644--- a/README.md+++ b/README.md@@ -12,7 +12,7 @@<a href="https://hub.docker.com/r/ministackorg/ministack"><img src="https://img.shields.io/docker/pulls/ministackorg/ministack" alt="Docker Pulls"></a><a href="https://hub.docker.com/r/ministackorg/ministack"><img src="https://img.shields.io/docker/image-size/ministackorg/ministack/latest" alt="Docker Image Size"></a><a href="https://github.com/ministackorg/ministack/blob/main/LICENSE"><img src="https://img.shields.io/github/license/ministackorg/ministack" alt="License"></a>- <img src="https://img.shields.io/badge/python-3.12-blue" alt="Python">+ <img src="https://img.shields.io/badge/python-3.10%20to%203.13-blue" alt="Python"></p><p align="center">@@ -432,13 +432,13 @@ subnet = ec2.create_subnet(| **Bedrock Runtime** | Converse, ConverseStream, InvokeModel, InvokeModelWithResponseStream, ApplyGuardrail, StartAsyncInvoke, GetAsyncInvoke, ListAsyncInvokes | Real eventstream wire format on streaming operations; **guardrails enforce their deterministic policies** — word policy, sensitive-information regexes, and the pattern-matchable PII types with `BLOCK`/`ANONYMIZE` per input/output stage — on `ApplyGuardrail` and on `Converse`/`ConverseStream` via `guardrailConfig` (`GUARDRAIL_INTERVENED`, blocked messaging, per-policy assessments, `ResourceNotFoundException` for an unknown id); the model-graded policies (topic, content, contextual grounding, `PROFANITY`) are not evaluated; deterministic family-aware mock responses selected by model ID prefix (`anthropic.*`, `amazon.titan*`, `amazon.nova*`, `meta.llama*`, `mistral.*`, `cohere.*`, `ai21.*`); verified against botocore `bedrock-runtime-2023-09-30` || **Bedrock Agent** | 72 operations — agents (versions, aliases, action groups, collaborators, agent knowledge bases, PrepareAgent), knowledge bases (data sources, ingestion jobs — `StartIngestionJob` reads the S3 data source and reports real statistics, `FAILED` with `failureReasons` when the source is unreadable — documents), flows (aliases, versions, ValidateFlowDefinition, PrepareFlow), prompts with versions, tagging | All 72 operations verified against botocore `bedrock-agent-2023-06-05` || **Bedrock Agent Runtime** | InvokeAgent, InvokeInlineAgent, GetAgentMemory, DeleteAgentMemory, Retrieve, RetrieveAndGenerate, RetrieveAndGenerateStream, Rerank, CreateSession, GetSession, UpdateSession, DeleteSession, EndSession, ListSessions, CreateInvocation, ListInvocations, PutInvocationStep, GetInvocationStep, ListInvocationSteps, InvokeFlow, StartFlowExecution, StopFlowExecution, GetFlowExecution, ListFlowExecutions, ListFlowExecutionEvents, GetExecutionFlowSnapshot, OptimizePrompt | All 31 operations verified against botocore `bedrock-agent-runtime-2023-07-26`; eventstream responses on streaming operations; `Retrieve` searches the documents Knowledge Base ingestion stored (lexical scoring — no embeddings) and returns content, `s3Location` and score; `InvokeAgent` answers a canned reply without orchestration and emits no trace events — it never fabricates an `ORCHESTRATE` trace |-| **Bedrock AgentCore** | Control plane (`bedrock-agentcore-control`): CreateAgentRuntime, GetAgentRuntime, ListAgentRuntimes, UpdateAgentRuntime, DeleteAgentRuntime, ListAgentRuntimeVersions, CreateAgentRuntimeEndpoint, GetAgentRuntimeEndpoint, ListAgentRuntimeEndpoints, UpdateAgentRuntimeEndpoint, DeleteAgentRuntimeEndpoint, CreateMemory, GetMemory, ListMemories, UpdateMemory, DeleteMemory, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy. Data plane (`bedrock-agentcore`): InvokeAgentRuntime | Agent-runtime lifecycle, versions, endpoint pinning and resource policies; Memory lifecycle with account- and region-scoped state. Memory strategies and tagging are not emulated. Shapes verified against botocore `bedrock-agentcore-control` / `bedrock-agentcore`; `InvokeAgentRuntime` runs the runtime's `containerUri` image in Docker (full image), waits for `/ping` and forwards to `/invocations` on port 8080, with container errors as `RuntimeClientError` (424); without Docker (slim image) or for a code artifact it answers a deterministic echo |+| **Bedrock AgentCore** | Control plane (`bedrock-agentcore-control`): CreateAgentRuntime, GetAgentRuntime, ListAgentRuntimes, UpdateAgentRuntime, DeleteAgentRuntime, ListAgentRuntimeVersions, CreateAgentRuntimeEndpoint, GetAgentRuntimeEndpoint, ListAgentRuntimeEndpoints, UpdateAgentRuntimeEndpoint, DeleteAgentRuntimeEndpoint, CreateMemory, GetMemory, ListMemories, UpdateMemory, DeleteMemory, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy. Data plane (`bedrock-agentcore`): InvokeAgentRuntime | Agent-runtime lifecycle with `CREATING`/`UPDATING`→`READY` transitions, versioned ARNs (`agent/{uuid}:{version}`, `agentEndpoint/{uuid}`); request/response shapes verified against botocore `bedrock-agentcore-control` / `bedrock-agentcore`; account- and region-scoped state; Memory resources record their strategies, but no extraction runs; resource policies are evaluated for runtime and endpoint invocation when `AUTH=true`; `InvokeAgentRuntime` runs the runtime's `containerUri` image in Docker (full image), waits for `/ping` and forwards to `/invocations` on port 8080, with container errors as `RuntimeClientError` (424); without Docker (slim image) or for a code artifact it answers a deterministic echo || **Transcribe** | StartTranscriptionJob, GetTranscriptionJob, ListTranscriptionJobs, DeleteTranscriptionJob | Batch transcription jobs only; streaming is a separate endpoint (`transcribestreaming`). All four operations verified against botocore `transcribe-2017-10-26`. A job starts `IN_PROGRESS` with `StartTime` set, as on AWS, and reaches `COMPLETED` over two seconds; `QUEUED`, which AWS reaches only for a request that opted into job queueing (`JobExecutionSettings.AllowDeferredExecution`) while the account is at its concurrent job limit, is not modelled; the media object is read from MiniStack S3 via an `s3://`, path-style or virtual-hosted HTTPS URI, and an unreadable URI fails the job with a `FailureReason` rather than erroring at `Start`, as on AWS; the transcript is written back to S3 in the real result format (`results.transcripts`, word-level `results.items`, `results.audio_segments`, plus `results.segments` and `results.speaker_labels` when the matching `Settings` are set) at `OutputBucketName`/`OutputKey`, or to an auto-created `ministack-transcribe-output` bucket. `IdentifyLanguage` and `IdentifyMultipleLanguages` resolve a language on completion, `ContentRedaction` controls whether a `redacted-` copy replaces or accompanies the transcript, and `Subtitles` writes WebVTT and SubRip files, redacted alongside the transcript when redaction is on. Reaching a terminal state publishes a `Transcribe Job State Change` event, so EventBridge rules downstream of a job fire. There is no speech recognition, so the transcript is deterministic canned text keyed on a digest of the media URI || **Translate** | StartTextTranslationJob, DescribeTextTranslationJob, ListTextTranslationJobs, StopTextTranslationJob | Batch text translation jobs only; the synchronous `TranslateText` / `TranslateDocument` pair and the custom terminology / parallel data families are not implemented. All four operations verified against botocore `translate-2017-07-01`. Jobs walk `SUBMITTED` → `IN_PROGRESS` → `COMPLETED` over `TRANSLATE_JOB_RUN_SECONDS` (default 2, `0` completes immediately); every document under `InputDataConfig.S3Uri` is read from MiniStack S3 and written back to the rewritten output location AWS uses — `OutputDataConfig.S3Uri` is reported as `s3://<bucket>/<prefix><account-id>-TranslateText-<JobId>/` — as `<target-code>.<input name>`, with a `details/<code>.auxiliary-translation-details.json` summary per target language. `text/plain` is translated line by line, `text/html` keeps its markup and translates only text nodes, `application/x-xliff+xml` gets a populated `<target>` in every `<trans-unit>` plus `target-language` on every `<file>`, and the three Office ZIP types are copied through. A document that can't be read as its content type is counted in `JobDetails` and the job ends `COMPLETED_WITH_ERROR`; an empty or unreadable input location fails the job with a `Message` rather than erroring at `Start`. `ClientToken` is idempotent, `StopTextTranslationJob` reaches a running worker, and reaching a terminal state publishes a `Translate TextTranslationJob State Change` event, so EventBridge rules downstream of a job fire. There is no machine translation, so the output is deterministic canned text derived from the source || **MSK** | CreateCluster, ListClusters, DescribeCluster, DeleteCluster, GetBootstrapBrokers, ListNodes, CreateConfiguration, ListConfigurations, DescribeConfiguration, ListConfigurationRevisions, DescribeConfigurationRevision, BatchAssociateScramSecret, BatchDisassociateScramSecret, ListScramSecrets, TagResource, UntagResource, ListTagsForResource | Kafka control plane; `GetBootstrapBrokers` honors `MINISTACK_MSK_BOOTSTRAP` so clients route to a real broker you bring (Redpanda, Kafka, KRaft) — the Kafka wire protocol itself is not emulated || **WAF v2** | CreateWebACL, GetWebACL, UpdateWebACL, DeleteWebACL, ListWebACLs, AssociateWebACL, DisassociateWebACL, GetWebACLForResource, ListResourcesForWebACL, CreateIPSet, GetIPSet, UpdateIPSet, DeleteIPSet, ListIPSets, CreateRuleGroup, GetRuleGroup, UpdateRuleGroup, DeleteRuleGroup, ListRuleGroups, TagResource, UntagResource, ListTagsForResource, CheckCapacity, DescribeManagedRuleGroup | LockToken enforced on Update/Delete; resource associations tracked || **Step Functions** | CreateStateMachine, DeleteStateMachine, DescribeStateMachine, UpdateStateMachine, ListStateMachines, StartExecution, StartSyncExecution, StopExecution, DescribeExecution, DescribeStateMachineForExecution, ListExecutions, GetExecutionHistory, SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat, CreateActivity, DeleteActivity, DescribeActivity, ListActivities, GetActivityTask, TestState, TagResource, UntagResource, ListTagsForResource | Full ASL interpreter; Retry/Catch; waitForTaskToken; Activities (worker pattern); Pass/Task/Choice/Wait/Succeed/Fail/Map/Parallel; TestState API with mock and inspectionLevel support; SFN_MOCK_CONFIG for AWS SFN Local compatible mock testing; intrinsic functions (States.StringToJson, States.JsonToString, States.JsonMerge, States.Format); nested startExecution.sync |-| **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateRouteResponse, GetRouteResponse, GetRouteResponses, UpdateRouteResponse, DeleteRouteResponse, CreateIntegrationResponse, GetIntegrationResponse, GetIntegrationResponses, UpdateIntegrationResponse, DeleteIntegrationResponse, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, TagResource, UntagResource, GetTags, PostToConnection, GetConnection, DeleteConnection | **HTTP API** and **WebSocket API** (`protocolType=WEBSOCKET`); Lambda proxy (`AWS_PROXY`), HTTP proxy (`HTTP_PROXY`), and MOCK integrations; HTTP data plane via `{apiId}.execute-api.localhost` Host header or path-based `/_aws/execute-api/{apiId}/{stage}/{path}` (no DNS/Host override needed — works from browsers on macOS and strict clients); `$default` stage served from the URL root (no stage segment in the path); per-API `corsConfiguration` applied to preflights + dispatched responses; request parameter mapping for HTTP_PROXY (`append/overwrite/remove` for headers/querystring plus `overwrite:path`) with context variables including `$context.authorizer.jwt.claims`; JWT data-plane authorization for HTTP routes (issuer/audience/time/scope checks) and claim propagation to integrations; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; WebSocket data plane on the same two URL forms, with `$connect` / `$disconnect` / `$default` / custom-action routing, `$request.body.*` RouteSelectionExpression, `@connections` management API (PostToConnection / GetConnection / DeleteConnection), per-connection outbox for server-side push; `{param}` / `{proxy+}` matching; JWT/Lambda authorizer CRUD; pin `apiId` across runs with the `ms-custom-id` tag |+| **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateRouteResponse, GetRouteResponse, GetRouteResponses, UpdateRouteResponse, DeleteRouteResponse, CreateIntegrationResponse, GetIntegrationResponse, GetIntegrationResponses, UpdateIntegrationResponse, DeleteIntegrationResponse, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateDomainName, GetDomainName, GetDomainNames, UpdateDomainName, DeleteDomainName, CreateApiMapping, GetApiMapping, GetApiMappings, UpdateApiMapping, DeleteApiMapping, TagResource, UntagResource, GetTags, PostToConnection, GetConnection, DeleteConnection | **HTTP API** and **WebSocket API** (`protocolType=WEBSOCKET`); Lambda proxy (`AWS_PROXY`), HTTP proxy (`HTTP_PROXY`), and MOCK integrations; HTTP data plane via `{apiId}.execute-api.localhost` Host header or path-based `/_aws/execute-api/{apiId}/{stage}/{path}` (no DNS/Host override needed — works from browsers on macOS and strict clients); `$default` stage served from the URL root (no stage segment in the path); per-API `corsConfiguration` applied to preflights + dispatched responses; request parameter mapping for HTTP_PROXY (`append/overwrite/remove` for headers/querystring plus `overwrite:path`) with context variables including `$context.authorizer.jwt.claims`; JWT data-plane authorization for HTTP routes (issuer/audience/time/scope checks) and claim propagation to integrations; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; WebSocket data plane on the same two URL forms, with `$connect` / `$disconnect` / `$default` / custom-action routing, `$request.body.*` RouteSelectionExpression, `@connections` management API (PostToConnection / GetConnection / DeleteConnection), per-connection outbox for server-side push; `{param}` / `{proxy+}` matching; custom domain names and API mappings shared with API Gateway v1, routed by `Host`; JWT/Lambda authorizer CRUD; pin `apiId` across runs with the `ms-custom-id` tag || **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateDocumentationPart, GetDocumentationPart, GetDocumentationParts, UpdateDocumentationPart, DeleteDocumentationPart, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags, CreateRequestValidator, GetRequestValidators, GetRequestValidator, UpdateRequestValidator, DeleteRequestValidator | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), non-proxy Lambda (AWS — the handler's output is the response body, mapping templates not modeled), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost` Host header, path-based `/_aws/execute-api/{apiId}/{stage}/{path}`, or legacy `/restapis/{apiId}/{stage}/_user_request_/{path}`; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; resource tree with `{param}` and `{proxy+}` path matching; routing is on the resource+method pair, so a request the matched resource does not serve falls through to a `{proxy+}` elsewhere in the tree (a methodless intermediate, a CORS-preflight-only node, or any undeclared verb), as it does on AWS; TOKEN and REQUEST Lambda authorizers on the data plane, with the returned IAM policy evaluated against each request's own method ARN and `authorizerResultTtlInSeconds` caching the policy per stage and identity source; JSON Patch for all PATCH operations; state persistence; pin `id` across runs with the `ms-custom-id` tag || **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, SetSubnets, SetIpAddressType, SetSecurityGroups, RegisterTargets, DeregisterTargets, DescribeTargetHealth, AddTags, RemoveTags, DescribeTags | Control plane + data plane; ALB→Lambda live traffic routing; `path-pattern`, `host-header`, `http-method`, `query-string`, `http-header` rule conditions; `forward`, `redirect`, `fixed-response`, `authenticate-oidc` actions; data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix || **KMS** | CreateKey, ReplicateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateMac, VerifyMac, GenerateDataKey, GenerateDataKeyWithoutPlaintext, GenerateDataKeyPair, GenerateDataKeyPairWithoutPlaintext, GenerateRandom, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, UpdateKeyDescription, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags, GetParametersForImport, ImportKeyMaterial, DeleteImportedKeyMaterial, CreateGrant, ListGrants, RevokeGrant, RetireGrant | 41 actions; multi-Region keys: `CreateKey` with `MultiRegion` mints an `mrk-` key and `ReplicateKey` creates a same-id replica in another region sharing the key material (ciphertext from the primary decrypts against the replica; a primary with live replicas waits in `PendingReplicaDeletion`); CMK specs: RSA (2048/3072/4096), ECC (SECG_P256K1, NIST P-256/384/521), Edwards25519 (`ECC_NIST_EDWARDS25519` — pure Ed25519 via `ED25519_SHA_512` with `MessageType=RAW`; `ED25519_PH_SHA_512` advertised in `SigningAlgorithms` but returns `UnsupportedOperationException` until Ed25519ph lands), HMAC (`HMAC_224`/`HMAC_256`/`HMAC_384`/`HMAC_512` with `KeyUsage=GENERATE_VERIFY_MAC`), and symmetric keys; PKCS1v15, PSS, and ECDSA signing; real RFC 2104 HMAC via `GenerateMac`/`VerifyMac` (4096-byte message cap, `KMSInvalidMacException` on mismatch, `DryRun` supported); envelope encryption, incl. asymmetric data key pairs (`KeyPairSpec` adds RSA_3072); alias resolution; key rotation; key policies; tags; enable/disable/schedule deletion; grants (stored and listed, not evaluated for authorization); full Terraform `aws_kms_key` compatible; `cryptography` package included in Docker image |@@ -576,6 +576,8 @@ subnet = ec2.create_subnet(| `AWS::ApiGatewayV2::Stage` | Stage ID | StageName || `AWS::ApiGatewayV2::Integration` | Integration ID | IntegrationId || `AWS::ApiGatewayV2::Route` | Route ID | RouteId |+| `AWS::ApiGatewayV2::DomainName` | Domain name | DomainNameArn, RegionalDomainName, RegionalHostedZoneId |+| `AWS::ApiGatewayV2::ApiMapping` | API mapping ID | ApiMappingId || `AWS::IoT::ProvisioningTemplate` | Template name | TemplateArn, Arn || `AWS::SES::EmailIdentity` | Identity | EmailIdentity || `AWS::SES::ConfigurationSet` | Configuration set name | None |diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.pyindex 0a65089a..09097c72 100644--- a/ministack/services/apigateway.py+++ b/ministack/services/apigateway.py@@ -394,6 +394,35 @@ async def handle_request(method, path, headers, body, query_params):tag_keys = [tag_keys]return _untag_resource(resource_arn, tag_keys)+ if resource == "domainnames":+ name = urllib.parse.unquote(parts[2]) if len(parts) > 2 else None+ mapping_id = parts[4] if len(parts) > 4 else None+ if not name:+ if method == "POST":+ return _create_domain_name(data)+ if method == "GET":+ return _get_domain_names(query_params)+ elif len(parts) > 3 and parts[3] == "apimappings":+ if not mapping_id:+ if method == "POST":+ return _create_api_mapping(name, data)+ if method == "GET":+ return _get_api_mappings(name, query_params)+ else:+ if method == "GET":+ return _get_api_mapping(name, mapping_id)+ if method == "PATCH":+ return _update_api_mapping(name, mapping_id, data)+ if method == "DELETE":+ return _delete_api_mapping(name, mapping_id)+ elif len(parts) == 3:+ if method == "GET":+ return _get_domain_name(name)+ if method == "PATCH":+ return _update_domain_name(name, data)+ if method == "DELETE":+ return _delete_domain_name(name)+if resource == "apis":api_id = parts[2] if len(parts) > 2 else Nonesub = parts[3] if len(parts) > 3 else None@@ -2252,6 +2281,11 @@ def _validate_tag_resource_arn(resource_arn: str) -> tuple[str | None, tuple | Nsegments = spec.resource[1:].split("/")if not segments or any(segment == "" for segment in segments):return None, _invalid_tag_resource_arn(resource_arn)+ if len(segments) == 2 and segments[0] == "domainnames":+ from ministack.services import apigateway_v1 as v1+ if segments[1] not in v1._domain_names:+ return None, _tag_resource_not_found(resource_arn)+ return _domain_arn(segments[1]), Noneif len(segments) not in (2, 4) or segments[0] != "apis":return None, _invalid_tag_resource_arn(resource_arn)@@ -2277,11 +2311,19 @@ def _delete_api_tag_resources(api_id: str):_api_tags.pop(resource_arn, None)+def _tag_store(canonical_arn: str):+ """Domain name tags are shared with API Gateway v1."""+ if "::/domainnames/" in canonical_arn:+ from ministack.services import apigateway_v1 as v1+ return v1._v1_tags+ return _api_tags++def _get_tags(resource_arn: str):canonical_arn, err = _validate_tag_resource_arn(resource_arn)if err:return err- tags = _api_tags.get(canonical_arn, {})+ tags = _tag_store(canonical_arn).get(canonical_arn, {})return _apigw_response({"tags": tags})@@ -2290,7 +2332,7 @@ def _tag_resource(resource_arn: str, data: dict):if err:return errtags = data.get("tags", {})- _api_tags.setdefault(canonical_arn, {}).update(tags)+ _tag_store(canonical_arn).setdefault(canonical_arn, {}).update(tags)return 201, {}, b""@@ -2298,12 +2340,260 @@ def _untag_resource(resource_arn: str, tag_keys: list):canonical_arn, err = _validate_tag_resource_arn(resource_arn)if err:return err- existing = _api_tags.get(canonical_arn, {})+ existing = _tag_store(canonical_arn).get(canonical_arn, {})for key in tag_keys:existing.pop(key, None)return 204, {}, b""+# ---- Control plane: Domain names and API mappings ----+# One resource with v1 custom domains: records, base path mappings and tags live in apigateway_v1.++_ROUTING_V2_TO_V1 = {+ "API_MAPPING_ONLY": "BASE_PATH_MAPPING_ONLY",+ "ROUTING_RULE_ONLY": "ROUTING_RULE_ONLY",+ "ROUTING_RULE_THEN_API_MAPPING": "ROUTING_RULE_THEN_BASE_PATH_MAPPING",+}+_ROUTING_V1_TO_V2 = {v1: v2 for v2, v1 in _ROUTING_V2_TO_V1.items()}+++def _domain_arn(domain_name):+ return f"arn:aws:apigateway:{get_region()}::/domainnames/{domain_name}"+++def _domain_not_found():+ return _apigw_error("NotFoundException", "Invalid domain name identifier specified", 404)+++def _domain_view(record):+ from ministack.services import apigateway_v1 as v1+ endpoint = record.get("endpointConfiguration") or {}+ endpoint_type = (endpoint.get("types") or ["REGIONAL"])[0]+ regional = endpoint_type == "REGIONAL"+ config = {+ "apiGatewayDomainName": record["regionalDomainName" if regional else "distributionDomainName"],+ "certificateArn": record.get("regionalCertificateArn" if regional else "certificateArn") or None,+ "certificateName": record.get("regionalCertificateName" if regional else "certificateName") or None,+ "domainNameStatus": "AVAILABLE",+ "endpointType": endpoint_type,+ "hostedZoneId": record["regionalHostedZoneId" if regional else "distributionHostedZoneId"],+ "ipAddressType": endpoint.get("ipAddressType", "ipv4"),+ "securityPolicy": record.get("securityPolicy", "TLS_1_2"),+ "ownershipVerificationCertificateArn": record.get("ownershipVerificationCertificateArn") or None,+ }+ arn = _domain_arn(record["domainName"])+ return {+ "apiMappingSelectionExpression": "$request.basepath",+ "domainName": record["domainName"],+ "domainNameArn": arn,+ "domainNameConfigurations": [config],+ "mutualTlsAuthentication": record.get("mutualTlsAuthentication") or None,+ "routingMode": _ROUTING_V1_TO_V2.get(record.get("routingMode"), "API_MAPPING_ONLY"),+ "tags": dict(v1._v1_tags.get(arn) or record.get("tags") or {}),+ }+++def _apply_domain_configuration(record, configs):+ config = (configs or [{}])[0]+ endpoint_type = config.get("endpointType", "REGIONAL")+ record["endpointConfiguration"] = {"types": [endpoint_type],+ "ipAddressType": config.get("ipAddressType", "ipv4")}+ arn_key, name_key = (("regionalCertificateArn", "regionalCertificateName")+ if endpoint_type == "REGIONAL" else ("certificateArn", "certificateName"))+ record[arn_key] = config.get("certificateArn", "")+ record[name_key] = config.get("certificateName", "")+ record["securityPolicy"] = config.get("securityPolicy", "TLS_1_2")+ record["ownershipVerificationCertificateArn"] = config.get("ownershipVerificationCertificateArn", "")+++def _create_domain_name(data):+ from ministack.services import apigateway_v1 as v1+ name = data.get("domainName")+ if not name:+ return _apigw_error("BadRequestException", "Domain name is required", 400)+ if name in v1._domain_names:+ return _apigw_error("ConflictException", "The domain name you provided already exists.", 409)+ if data.get("routingMode", "API_MAPPING_ONLY") not in _ROUTING_V2_TO_V1:+ return _apigw_error("BadRequestException", f"Invalid routingMode: {data['routingMode']}", 400)+ record = {+ "domainName": name,+ "certificateName": "",+ "certificateArn": "",+ "regionalCertificateName": "",+ "regionalCertificateArn": "",+ "distributionDomainName": f"d{new_uuid().replace('-', '')[:13]}.cloudfront.net",+ "distributionHostedZoneId": "Z2FDTNDATAQYW2",+ "regionalDomainName": f"d-{new_uuid().replace('-', '')[:10]}.execute-api.{get_region()}.amazonaws.com",+ "regionalHostedZoneId": "Z1UJRXOUMOOFQ8",+ "mutualTlsAuthentication": data.get("mutualTlsAuthentication") or {},+ "routingMode": _ROUTING_V2_TO_V1[data.get("routingMode", "API_MAPPING_ONLY")],+ "tags": {},+ }+ _apply_domain_configuration(record, data.get("domainNameConfigurations"))+ v1._domain_names[name] = record+ v1._base_path_mappings[name] = {}+ if data.get("tags"):+ v1._v1_tags[_domain_arn(name)] = dict(data["tags"])+ return _apigw_response(_domain_view(record), 201)+++def _get_domain_name(name):+ from ministack.services import apigateway_v1 as v1+ record = v1._domain_names.get(name)+ return _apigw_response(_domain_view(record)) if record else _domain_not_found()+++def _page(items, query_params):+ """One page of items for maxResults/nextToken, or a BadRequestException response."""+ def value(key):+ v = (query_params or {}).get(key)+ return v[0] if isinstance(v, list) else v+ try:+ start = int(value("nextToken") or 0)+ limit = int(value("maxResults") or len(items) or 1)+ except ValueError:+ return _apigw_error("BadRequestException", "Invalid nextToken or maxResults", 400)+ page = {"items": items[start:start + limit]}+ if start + limit < len(items):+ page["nextToken"] = str(start + limit)+ return _apigw_response(page)+++def _get_domain_names(query_params):+ from ministack.services import apigateway_v1 as v1+ return _page([_domain_view(r) for r in v1._domain_names.values()], query_params)+++def _update_domain_name(name, data):+ from ministack.services import apigateway_v1 as v1+ record = v1._domain_names.get(name)+ if not record:+ return _domain_not_found()+ if "routingMode" in data and data["routingMode"] not in _ROUTING_V2_TO_V1:+ return _apigw_error("BadRequestException", f"Invalid routingMode: {data['routingMode']}", 400)+ if "domainNameConfigurations" in data:+ _apply_domain_configuration(record, data["domainNameConfigurations"])+ if "mutualTlsAuthentication" in data:+ record["mutualTlsAuthentication"] = data["mutualTlsAuthentication"] or {}+ if "routingMode" in data:+ record["routingMode"] = _ROUTING_V2_TO_V1[data["routingMode"]]+ return _apigw_response(_domain_view(record))+++def _delete_domain_name(name):+ from ministack.services import apigateway_v1 as v1+ if name not in v1._domain_names:+ return _domain_not_found()+ v1._domain_names.pop(name, None)+ v1._base_path_mappings.pop(name, None)+ v1._v1_tags.pop(_domain_arn(name), None)+ return 204, {}, b""+++def _mapping_view(base_path, mapping):+ return {+ "apiId": mapping["restApiId"],+ "apiMappingId": mapping.setdefault("_apiMappingId", new_uuid().replace("-", "")[:6]),+ "apiMappingKey": "" if base_path == "(none)" else base_path,+ "stage": mapping["stage"],+ }+++def _domain_mappings(name):+ """The domain's base path mappings, or a NotFoundException response."""+ from ministack.services import apigateway_v1 as v1+ if name not in v1._domain_names:+ return None, _domain_not_found()+ return v1._base_path_mappings.setdefault(name, {}), None+++def _find_mapping(mappings, mapping_id):+ for base_path, mapping in mappings.items():+ if _mapping_view(base_path, mapping)["apiMappingId"] == mapping_id:+ return base_path, mapping+ return None, None+++def _api_mapping_not_found():+ return _apigw_error("NotFoundException", "Invalid API mapping identifier specified", 404)+++def _check_mapping_target(api_id, stage):+ from ministack.services import apigateway_v1 as v1+ if api_id in _apis:+ stages = _stages.get(api_id, {})+ elif api_id in v1._rest_apis:+ stages = v1._stages_v1.get(api_id, {})+ else:+ return _apigw_error("NotFoundException", "Invalid API identifier specified", 404)+ if stage not in stages:+ return _apigw_error("BadRequestException", "Invalid stage identifier specified", 400)+ return None+++def _create_api_mapping(name, data):+ mappings, err = _domain_mappings(name)+ if err:+ return err+ api_id, stage = data.get("apiId"), data.get("stage")+ if not api_id or not stage:+ return _apigw_error("BadRequestException", "ApiId and Stage are required", 400)+ if err := _check_mapping_target(api_id, stage):+ return err+ base_path = data.get("apiMappingKey") or "(none)"+ if base_path in mappings:+ return _apigw_error("ConflictException", "ApiMapping key already exists for this domain name", 409)+ mappings[base_path] = {"basePath": base_path, "restApiId": api_id, "stage": stage}+ return _apigw_response(_mapping_view(base_path, mappings[base_path]), 201)+++def _get_api_mapping(name, mapping_id):+ mappings, err = _domain_mappings(name)+ if err:+ return err+ base_path, mapping = _find_mapping(mappings, mapping_id)+ return _apigw_response(_mapping_view(base_path, mapping)) if mapping else _api_mapping_not_found()+++def _get_api_mappings(name, query_params):+ mappings, err = _domain_mappings(name)+ if err:+ return err+ return _page([_mapping_view(k, m) for k, m in mappings.items()], query_params)+++def _update_api_mapping(name, mapping_id, data):+ mappings, err = _domain_mappings(name)+ if err:+ return err+ base_path, mapping = _find_mapping(mappings, mapping_id)+ if not mapping:+ return _api_mapping_not_found()+ api_id = data.get("apiId") or mapping["restApiId"]+ stage = data.get("stage") or mapping["stage"]+ if err := _check_mapping_target(api_id, stage):+ return err+ new_path = (data["apiMappingKey"] or "(none)") if "apiMappingKey" in data else base_path+ if new_path != base_path and new_path in mappings:+ return _apigw_error("ConflictException", "ApiMapping key already exists for this domain name", 409)+ mapping["restApiId"], mapping["stage"] = api_id, stage+ if new_path != base_path:+ mapping["basePath"] = new_path+ mappings[new_path] = mappings.pop(base_path)+ return _apigw_response(_mapping_view(new_path, mapping))+++def _delete_api_mapping(name, mapping_id):+ mappings, err = _domain_mappings(name)+ if err:+ return err+ base_path, mapping = _find_mapping(mappings, mapping_id)+ if not mapping:+ return _api_mapping_not_found()+ mappings.pop(base_path)+ return 204, {}, b""++# ---- Control plane: Authorizers ----def _create_authorizer(api_id, data):diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.pyindex b3bd106f..ac9592a5 100644--- a/ministack/services/apigateway_v1.py+++ b/ministack/services/apigateway_v1.py@@ -4558,17 +4558,23 @@ def _create_base_path_mapping(domain_name, data):return _v1_response(mapping, 201)+def _public_mapping(mapping):+ """A base path mapping without the API Gateway v2 mapping id."""+ return {k: v for k, v in mapping.items() if not k.startswith("_")}++def _get_base_path_mappings(domain_name, query_params):if domain_name not in _domain_names:return _v1_error("NotFoundException", "Invalid domain name identifier specified", 404)- return _v1_paginated_response(list(_base_path_mappings.get(domain_name, {}).values()), query_params)+ return _v1_paginated_response(+ [_public_mapping(m) for m in _base_path_mappings.get(domain_name, {}).values()], query_params)def _get_base_path_mapping(domain_name, base_path):mapping = _base_path_mappings.get(domain_name, {}).get(base_path)if not mapping:return _v1_error("NotFoundException", "Invalid base path mapping identifier specified", 404)- return _v1_response(mapping)+ return _v1_response(_public_mapping(mapping))def _delete_base_path_mapping(domain_name, base_path):diff --git a/ministack/services/bedrock_agentcore.py b/ministack/services/bedrock_agentcore.pyindex 4826b21e..4c96f484 100644--- a/ministack/services/bedrock_agentcore.py+++ b/ministack/services/bedrock_agentcore.py@@ -347,13 +347,6 @@ def _paginate_agentcore_results(items, query_params):return page, None-def _memory_id(identifier):- """Accept the memory ID or its ARN, as the AgentCore data plane does."""- if isinstance(identifier, str) and ":memory/" in identifier:- return identifier.rsplit(":memory/", 1)[1]- return identifier--def _memory_arn(memory_id):return (f"arn:aws:bedrock-agentcore:{get_region()}:{get_account_id()}:"f"memory/{memory_id}")@@ -364,6 +357,73 @@ def _memory_public_record(record):if not key.startswith("_")}+_MEMORY_ID_RE = re.compile(r"[a-zA-Z][a-zA-Z0-9-_]{0,99}-[a-zA-Z0-9]{10}")++# MemoryStrategyInput union member -> MemoryStrategyType.+_MEMORY_STRATEGY_TYPES = {+ "semanticMemoryStrategy": "SEMANTIC",+ "summaryMemoryStrategy": "SUMMARIZATION",+ "userPreferenceMemoryStrategy": "USER_PREFERENCE",+ "customMemoryStrategy": "CUSTOM",+ "episodicMemoryStrategy": "EPISODIC",+}+++def _memory_strategies(inputs, now):+ """MemoryStrategy records for a MemoryStrategyInputList, or an error response."""+ if not isinstance(inputs, list):+ return None, _validation("memoryStrategies must be a list")+ strategies = []+ for item in inputs:+ members = [key for key in item if key in _MEMORY_STRATEGY_TYPES] if isinstance(item, dict) else []+ if len(members) != 1 or len(item) != 1:+ return None, _validation("Each memory strategy must set exactly one strategy type")+ spec = item[members[0]]+ name = spec.get("name") if isinstance(spec, dict) else None+ if not isinstance(name, str) or not _NAME_RE.fullmatch(name):+ return None, _validation("Memory strategy name is invalid")+ strategy = {+ "strategyId": _resource_id(name),+ "name": name,+ "type": _MEMORY_STRATEGY_TYPES[members[0]],+ "namespaces": copy.deepcopy(spec.get("namespaces", [])),+ "namespaceTemplates": copy.deepcopy(spec.get("namespaceTemplates", [])),+ "status": "ACTIVE",+ "createdAt": now,+ "updatedAt": now,+ }+ for field in ("description", "memoryRecordSchema"):+ if field in spec:+ strategy[field] = copy.deepcopy(spec[field])+ strategies.append(strategy)+ return strategies, None+++def _modify_memory_strategies(record, changes, now):+ """Apply ModifyMemoryStrategies to a copy of the record's strategies."""+ if not isinstance(changes, dict):+ return None, _validation("memoryStrategies must be an object")+ strategies = copy.deepcopy(record.get("strategies", []))+ by_id = {strategy["strategyId"]: strategy for strategy in strategies}+ for item in changes.get("deleteMemoryStrategies") or []:+ strategy_id = (item or {}).get("memoryStrategyId")+ if strategy_id not in by_id:+ return None, _not_found(f"Memory strategy '{strategy_id}' not found")+ strategies.remove(by_id.pop(strategy_id))+ for item in changes.get("modifyMemoryStrategies") or []:+ strategy_id = (item or {}).get("memoryStrategyId")+ if strategy_id not in by_id:+ return None, _not_found(f"Memory strategy '{strategy_id}' not found")+ for field in ("description", "namespaces", "namespaceTemplates", "memoryRecordSchema"):+ if field in item:+ by_id[strategy_id][field] = copy.deepcopy(item[field])+ by_id[strategy_id]["updatedAt"] = now+ added, error = _memory_strategies(changes.get("addMemoryStrategies") or [], now)+ if error:+ return None, error+ return strategies + added, None++def _memory_page(items, data, default=20):query = {"maxResults": data.get("maxResults", default)}if "nextToken" in data:@@ -381,29 +441,29 @@ def _create_memory(body):return _conflict(f"A memory with name '{name}' already exists")if not isinstance(duration, int) or isinstance(duration, bool) or not 3 <= duration <= 365:return _validation("eventExpiryDuration must be an integer from 3 to 365")- if data.get("tags"):- return _validation("Tagging is not supported by MiniStack AgentCore Memory yet")- # MiniStack implements explicit record storage/retrieval. Built-in- # extraction strategies invoke managed model pipelines and are not emulated.- if data.get("memoryStrategies"):- return _validation("Memory strategies are not supported by MiniStack AgentCore Memory")+ tags = data.get("tags") or {}+ if not isinstance(tags, dict) or len(tags) > 50:+ return _validation("tags must be a map of at most 50 entries")+ now = int(time.time())+ # Strategies are recorded; no extraction runs behind them.+ strategies, error = _memory_strategies(data.get("memoryStrategies") or [], now)+ if error:+ return errormemory_id = _resource_id(name)- now = time.time()record = {"id": memory_id,"arn": _memory_arn(memory_id),"name": name,- "description": data.get("description", ""),"eventExpiryDuration": duration,"status": "ACTIVE","createdAt": now,"updatedAt": now,- "indexedKeys": copy.deepcopy(data.get("indexedKeys", [])),- "namespaceKeys": copy.deepcopy(data.get("namespaceKeys", [])),- "strategies": [],+ "strategies": strategies,+ "_tags": copy.deepcopy(tags),}- for field in ("encryptionKeyArn", "memoryExecutionRoleArn", "streamDeliveryResources"):+ for field in ("description", "encryptionKeyArn", "memoryExecutionRoleArn",+ "indexedKeys", "namespaceKeys", "streamDeliveryResources"):if field in data:record[field] = copy.deepcopy(data[field])_memories[memory_id] = record@@ -414,7 +474,7 @@ def _create_memory(body):def _get_memory(memory_id, query_params):- record = _memories.get(_memory_id(memory_id))+ record = _memories.get(memory_id)if record is None:return _not_found(f"Memory '{memory_id}' not found")view = _agentcore_query_value(query_params, "view", "full")@@ -438,17 +498,22 @@ def _list_memories(body):def _update_memory(memory_id, body):- record = _memories.get(_memory_id(memory_id))+ record = _memories.get(memory_id)if record is None:return _not_found(f"Memory '{memory_id}' not found")data = _parse_body(body)- if "memoryStrategies" in data and data["memoryStrategies"]:- return _validation("Memory strategies are not supported by MiniStack AgentCore Memory")+ now = int(time.time())if "eventExpiryDuration" in data:duration = data["eventExpiryDuration"]if not isinstance(duration, int) or isinstance(duration, bool) or not 3 <= duration <= 365:return _validation("eventExpiryDuration must be an integer from 3 to 365")- record["eventExpiryDuration"] = duration+ if "memoryStrategies" in data:+ strategies, error = _modify_memory_strategies(record, data["memoryStrategies"], now)+ if error:+ return error+ record["strategies"] = strategies+ if "eventExpiryDuration" in data:+ record["eventExpiryDuration"] = data["eventExpiryDuration"]if "description" in data:record["description"] = data["description"]for field in ("memoryExecutionRoleArn", "namespaceKeys", "streamDeliveryResources"):@@ -460,14 +525,13 @@ def _update_memory(memory_id, body):copy.deepcopy(item) for item in data["addIndexedKeys"]if item.get("key") not in existing)- record["updatedAt"] = time.time()+ record["updatedAt"] = nowresponse = _memory_public_record(record)response["status"] = "UPDATING"return json_response({"memory": response}, 202)def _delete_memory(memory_id):- memory_id = _memory_id(memory_id)record = _memories.pop(memory_id, None)if record is None:return _not_found(f"Memory '{memory_id}' not found")@@ -1204,13 +1268,17 @@ async def handle_request(method, path, headers, body, query_params):if inner == "memories/create" and method == "POST":return _create_memory(body)if inner.startswith("memories/"):- parts = [unquote(part) for part in inner.split("/") if part]- if len(parts) == 3 and parts[2] == "details" and method == "GET":- return _get_memory(parts[1], query_params)- if len(parts) == 3 and parts[2] == "update" and method == "PUT":- return _update_memory(parts[1], body)- if len(parts) == 3 and parts[2] == "delete" and method == "DELETE":- return _delete_memory(parts[1])+ memory_id, _, op = unquote(inner[len("memories/"):]).rpartition("/")+ handler = {("GET", "details"): lambda: _get_memory(memory_id, query_params),+ ("PUT", "update"): lambda: _update_memory(memory_id, body),+ ("DELETE", "delete"): lambda: _delete_memory(memory_id)}.get((method, op))+ if handler:+ if not _MEMORY_ID_RE.fullmatch(memory_id):+ return _validation(+ f"1 validation error detected: Value '{memory_id}' at 'memoryId' failed to "+ f"satisfy constraint: Member must satisfy regular expression pattern: "+ f"{_MEMORY_ID_RE.pattern}")+ return handler()if inner.startswith("resourcepolicy/"):resource_arn = unquote(inner[len("resourcepolicy/"):])if method == "PUT":diff --git a/ministack/services/cloudformation/engine.py b/ministack/services/cloudformation/engine.pyindex a66b8369..336e011e 100644--- a/ministack/services/cloudformation/engine.py+++ b/ministack/services/cloudformation/engine.py@@ -637,9 +637,7 @@ def _evaluate_conditions(template: dict, params: dict) -> dict:if isinstance(items, str):# A CommaDelimitedList parameter is one string here: "id,S,," becomes ["id", "S", "", ""]items = [s.strip() for s in items.split(",")]- if 0 <= index < len(items):- return items[index]- return ""+ return _select(index, items)return valfor name, defn in cond_defs.items():@@ -773,6 +771,13 @@ def _check_rules_section(template: dict) -> None:_check_rule_expression(assertion["Assert"], name)+def _select(index: int, items: list):+ """Fn::Select; an index outside the list fails the template, as on AWS."""+ if not 0 <= index < len(items):+ raise ValueError(f"Template error: Fn::Select cannot select nonexistent value at index {index}")+ return items[index]++def _rule_inner_type(ptype: str) -> tuple[str, bool]:"""The type a parameter's declared type wraps and whether it is a list:the SSM ``Value<...>`` wrapper is stripped first, then ``List<...>``@@ -1181,9 +1186,7 @@ def _resolve_refs(value, resources, params, conditions, mappings,mappings, stack_name, stack_id)if isinstance(items, str):items = [s.strip() for s in items.split(",")]- if 0 <= index < len(items):- return items[index]- return ""+ return _select(index, items)# --- Fn::Split ---if "Fn::Split" in value:diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.pyindex 13fbbca5..f82d8c85 100644--- a/ministack/services/cloudformation/handlers.py+++ b/ministack/services/cloudformation/handlers.py@@ -319,8 +319,8 @@ def _create_stack(params):except ValueError as exc:return _error("ValidationError", str(exc))- conditions = _evaluate_conditions(template, param_values)try:+ conditions = _evaluate_conditions(template, param_values)validate_template_support(template, conditions, params=param_values)except ValueError as exc:return _error("ValidationError", str(exc))diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 6f2a7a61..1775abb8 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -664,10 +664,6 @@ def _requires_replacement_pipes(old_props, new_props):# custom-named resource (you must rename it first), so MiniStack must fail the# update instead of silently executing the replacement and destroying data# (issue #1433).-# A replacement is a change to a property of the type's _REPLACING_PROPERTIES-# row, or one ``requires_replacement`` adds. A type with an ``exists`` message-# is not refused up front: AWS runs the create, which fails with that message-# because the predecessor still holds the name.# An ``exists`` entry is not refused up front: the replacement's create fails on the name._CUSTOM_NAME_REPLACEMENT = {"AWS::DynamoDB::Table": {@@ -921,14 +917,6 @@ def _delete_predecessor(delete_fn, *args, **kwargs):retaining set): the engine then records the DELETE_SKIPPED event and thepredecessor stays, as on AWS. Every update handler that creates thereplacement itself removes the old resource through this, so the policy- cannot be forgotten at one site, with five exceptions. Four have a- deterministic generated name (the DynamoDB table, the IoT thing type and- the ElastiCache cache cluster and replication group): the replacement- takes the name back, so there is nothing left to retain. The fifth is the- Lambda permission's degenerate ``Id`` branch,- which removes and re-puts one statement under a Sid that cannot change:- the physical id is kept, nothing is replaced, and the policy does not- apply.cannot be forgotten at one site."""if _RETAIN_REPLACED.get():@@ -1093,6 +1081,7 @@ _STACK_TAG_PROPERTY: dict[str, tuple[str, str]] = {"AWS::ApiGateway::UsagePlan": ("Tags", "list"),"AWS::ApiGatewayV2::Api": ("Tags", "map"),"AWS::ApiGatewayV2::Stage": ("Tags", "map"),+ "AWS::ApiGatewayV2::DomainName": ("Tags", "map"),"AWS::AppConfig::Application": ("Tags", "list"),"AWS::AppConfig::ConfigurationProfile": ("Tags", "list"),"AWS::AppConfig::Deployment": ("Tags", "list"),@@ -2213,10 +2202,6 @@ def _lambda_update(physical_id, old_props, new_props, stack_name, logical_id=Nonpublished versions, aliases, the resource policy, tags, event invokeconfigs. Going through the Lambda module's own update paths keeps them.- FunctionName, PackageType and TenancyConfig changes are replaced in- ``_update_resource`` before this runs. A DurableConfig change may require- replacement on AWS; under the same physical name the closest local- equivalent is the full re-provision the create fallback always did.FunctionName, PackageType and TenancyConfig are replaced in ``_update_resource``;a DurableConfig change re-provisions under the same name."""@@ -2718,10 +2703,6 @@ def _iam_ip_roles(props):def _iam_ip_create(logical_id, props, stack_name):name = props.get("InstanceProfileName") or _physical_name(stack_name, logical_id, max_len=128)path = props.get("Path", "/")- # A generated name belongs to this stack resource, so a profile left under- # it is taken over; a custom name goes through CreateInstanceProfile as it- # is, and its EntityAlreadyExists keeps one stack from writing over a- # profile another stack or the API owns.# A generated name is this stack's to take over; a custom one meets EntityAlreadyExists.if not props.get("InstanceProfileName"):_iam._instance_profiles.pop(name, None)@@ -2775,7 +2756,10 @@ def _iam_ip_delete(physical_id, props):_SSM_CFN_PARAMETER_TYPES = ("String", "StringList")-def _ssm_check_type(props):+def _ssm_check_type(props, logical_id):+ if isinstance(props.get("Value"), list):+ raise ValueError(f"Properties validation failed for resource {logical_id} with message: "+ "[#/Value: expected type: String, found: JSONArray]")ptype = props.get("Type", "String")if ptype not in _SSM_CFN_PARAMETER_TYPES:raise ValueError(@@ -2815,7 +2799,7 @@ def _ssm_create(logical_id, props, stack_name):# two doors into the same store behave alike: a create over an existing# parameter fails as real CloudFormation does (`ParameterAlreadyExists`), and# Version/history stay consistent with the API path.- _ssm_check_type(props)+ _ssm_check_type(props, logical_id)name = props.get("Name") or f"/{stack_name}/{logical_id}"data = _ssm_put_data(name, props)status, _headers, body = _ssm._put_parameter(data)@@ -2824,8 +2808,8 @@ def _ssm_create(logical_id, props, stack_name):return name, _ssm_attrs(name, data)-def _ssm_update(physical_id, old_props, new_props, stack_name):- _ssm_check_type(new_props)+def _ssm_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ _ssm_check_type(new_props, logical_id or physical_id)new_name = new_props.get("Name")if new_name and new_name != physical_id:# Name is Update requires: Replacement — create the new parameter and@@ -9316,19 +9300,11 @@ def _sd_instance_delete(physical_id, props):# ----------------------------------------------------------------------------# EFS (AWS::EFS::*)-#-# Every handler goes through efs.py's own functions, so a stack-created file-# system, mount target or access point is the record the EFS API writes. Ref,-# Fn::GetAtt and the replacement properties follow the CloudFormation Template-# Reference pages for the three types. A replacement property is listed in-# _REPLACING_PROPERTIES and replaced by the engine before these update handlers-# run, so the handlers only change what updates in place.+# EFS (AWS::EFS::*) — through efs.py; create-only properties are replaced by the engine.# ---------------------------------------------------------------------------def _efs_result(response, what, missing_ok=False):- """The parsed body of an efs call, or ValueError naming ``what``. With- ``missing_ok`` a 404 (resource already gone) returns None."""+ """The parsed body of an efs call; a 404 returns None when ``missing_ok``."""status, _, body = responseif status == 404 and missing_ok:return None@@ -9337,11 +9313,6 @@ def _efs_result(response, what, missing_ok=False):return json.loads(body) if body else {}-def _efs_file_system_id(value):- """A file system id from an id or a ``...:file-system/fs-...`` ARN."""- return str(value or "").rsplit("/", 1)[-1]--def _efs_policy_json(policy):return policy if isinstance(policy, str) else json.dumps(policy)@@ -9379,8 +9350,7 @@ def _efs_put_protection(fs_id, protection):def _efs_replication_destinations(configuration):- """The Destinations a ReplicationConfiguration property sends to the API:- Status and StatusMessage describe the destination, they do not configure it."""+ """The API Destinations, without the read-only Status and StatusMessage."""return [{k: v for k, v in destination.items() if k not in ("Status", "StatusMessage")}for destination in (configuration or {}).get("Destinations") or []@@ -9400,8 +9370,7 @@ def _efs_delete_replication(fs_id):def _efs_file_system_create(logical_id, props, stack_name):- # No CreationToken: efs.py returns the existing file system for a repeated- # token, which would turn a replacement into a no-op.+ # No CreationToken: a repeated one would return the predecessor on a replacement.body = {key: props[key]for key in ("PerformanceMode", "ThroughputMode", "KmsKeyId",@@ -9428,8 +9397,7 @@ def _efs_file_system_create(logical_id, props, stack_name):def _efs_file_system_update(physical_id, old_props, new_props, stack_name, logical_id=None):- """AvailabilityZoneName, Encrypted, KmsKeyId and PerformanceMode replace- the file system in the engine. Everything else changes in place."""+ """The in-place properties; the create-only ones are replaced by the engine."""fs = _efs._file_systems.get(physical_id)if fs is None:return _efs_file_system_create(logical_id or physical_id, new_props, stack_name)@@ -9466,16 +9434,14 @@ def _efs_file_system_update(physical_id, old_props, new_props, stack_name, logicdef _efs_file_system_delete(physical_id, props):- # A file system in a replication configuration cannot be deleted; the- # destination it created stays, as on AWS.+ # A replicating file system cannot be deleted; the destination stays, as on AWS._efs_delete_replication(physical_id)_efs_result(_efs._delete_file_system(physical_id),"AWS::EFS::FileSystem delete", missing_ok=True)def _efs_mount_target_attrs(mount_target):- # Id is the file system id, as the CloudFormation reference documents.- # An IPV6_ONLY mount target has no IPv4 address.+ # Id is the file system id (template reference); IPV6_ONLY has no IpAddress.attrs = {"Id": mount_target["FileSystemId"]}if "IpAddress" in mount_target:attrs["IpAddress"] = mount_target["IpAddress"]@@ -9484,7 +9450,7 @@ def _efs_mount_target_attrs(mount_target):def _efs_mount_target_create(logical_id, props, stack_name):body = {- "FileSystemId": _efs_file_system_id(props.get("FileSystemId")),+ "FileSystemId": _efs._fs_id_from(props.get("FileSystemId")),"SubnetId": props.get("SubnetId", ""),"SecurityGroups": list(props.get("SecurityGroups") or []),}@@ -9496,8 +9462,7 @@ def _efs_mount_target_create(logical_id, props, stack_name):def _efs_mount_target_update(physical_id, old_props, new_props, stack_name, logical_id=None):- """FileSystemId, SubnetId, IpAddress, IpAddressType and Ipv6Address replace- the mount target in the engine; SecurityGroups change in place."""+ """SecurityGroups change in place; the rest is replaced by the engine."""mount_target = _efs._mount_targets.get(physical_id)if mount_target is None:return _efs_mount_target_create(logical_id or physical_id, new_props, stack_name)@@ -9539,7 +9504,7 @@ def _efs_access_point_attrs(access_point):def _efs_access_point_create(logical_id, props, stack_name):- body = {"FileSystemId": _efs_file_system_id(props.get("FileSystemId"))}+ body = {"FileSystemId": _efs._fs_id_from(props.get("FileSystemId"))}if props.get("PosixUser"):body["PosixUser"] = _efs_posix_user(props["PosixUser"])if props.get("RootDirectory"):@@ -9553,8 +9518,7 @@ def _efs_access_point_create(logical_id, props, stack_name):def _efs_access_point_update(physical_id, old_props, new_props, stack_name, logical_id=None):- """FileSystemId, ClientToken, PosixUser and RootDirectory replace the access- point in the engine; AccessPointTags change in place."""+ """AccessPointTags change in place; the rest is replaced by the engine."""access_point = _efs._access_points.get(physical_id)if access_point is None:return _efs_access_point_create(logical_id or physical_id, new_props, stack_name)@@ -10077,6 +10041,84 @@ def _apigw_v2_stage_delete(physical_id, props):stages.pop(stage_name, None)+# ---------------------------------------------------------------------------+# ApiGatewayV2 DomainName and ApiMapping+# ---------------------------------------------------------------------------++def _apigw_v2_result(resp, what, missing_ok=False):+ if resp[0] == 404 and missing_ok:+ return None+ if resp[0] >= 400:+ raise ValueError(f"{what} failed: {resp[2]!r}")+ return json.loads(resp[2]) if resp[2] else {}+++def _apigw_v2_domain_body(props):+ return {+ "domainNameConfigurations": _pascal_to_camel(props.get("DomainNameConfigurations") or []),+ "mutualTlsAuthentication": _pascal_to_camel(props.get("MutualTlsAuthentication") or {}),+ "routingMode": props.get("RoutingMode", "API_MAPPING_ONLY"),+ }+++def _apigw_v2_domain_attrs(view):+ config = view["domainNameConfigurations"][0]+ return {"DomainNameArn": view["domainNameArn"],+ "RegionalDomainName": config["apiGatewayDomainName"],+ "RegionalHostedZoneId": config["hostedZoneId"]}+++def _apigw_v2_domain_create(logical_id, props, stack_name):+ body = {"domainName": props.get("DomainName", ""), "tags": dict(props.get("Tags") or {}),+ **_apigw_v2_domain_body(props)}+ view = _apigw_v2_result(_apigw_v2._create_domain_name(body), "AWS::ApiGatewayV2::DomainName create")+ return view["domainName"], _apigw_v2_domain_attrs(view)+++def _apigw_v2_domain_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ """DomainName is replaced by the engine; the rest updates in place."""+ import ministack.services.apigateway_v1 as _apigw_v1+ view = _apigw_v2_result(_apigw_v2._update_domain_name(physical_id, _apigw_v2_domain_body(new_props)),+ "AWS::ApiGatewayV2::DomainName update", missing_ok=True)+ if view is None:+ return _apigw_v2_domain_create(logical_id or physical_id, new_props, stack_name)+ _reconcile_tag_map(_apigw_v1._v1_tags.setdefault(view["domainNameArn"], {}), old_props, new_props)+ return physical_id, _apigw_v2_domain_attrs(view)+++def _apigw_v2_domain_delete(physical_id, props):+ _apigw_v2_result(_apigw_v2._delete_domain_name(physical_id),+ "AWS::ApiGatewayV2::DomainName delete", missing_ok=True)+++def _apigw_v2_mapping_body(props):+ return {"apiId": props.get("ApiId", ""), "stage": props.get("Stage", ""),+ "apiMappingKey": props.get("ApiMappingKey", "")}+++def _apigw_v2_mapping_create(logical_id, props, stack_name):+ mapping = _apigw_v2_result(+ _apigw_v2._create_api_mapping(props.get("DomainName", ""), _apigw_v2_mapping_body(props)),+ "AWS::ApiGatewayV2::ApiMapping create")+ return mapping["apiMappingId"], {"ApiMappingId": mapping["apiMappingId"]}+++def _apigw_v2_mapping_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ """DomainName is replaced by the engine; ApiId, ApiMappingKey and Stage update in place."""+ mapping = _apigw_v2_result(+ _apigw_v2._update_api_mapping(new_props.get("DomainName", ""), physical_id,+ _apigw_v2_mapping_body(new_props)),+ "AWS::ApiGatewayV2::ApiMapping update", missing_ok=True)+ if mapping is None:+ return _apigw_v2_mapping_create(logical_id or physical_id, new_props, stack_name)+ return physical_id, {"ApiMappingId": physical_id}+++def _apigw_v2_mapping_delete(physical_id, props):+ _apigw_v2_result(_apigw_v2._delete_api_mapping(props.get("DomainName", ""), physical_id),+ "AWS::ApiGatewayV2::ApiMapping delete", missing_ok=True)++# ---------------------------------------------------------------------------# ApiGatewayV2 Integration# ---------------------------------------------------------------------------@@ -13075,14 +13117,6 @@ def _location_tracker_delete(physical_id, props):_location._delete_tracker(physical_id)-# CloudFormation replacement rules, checked against DescribeType and change-# sets. A row lists the schema's createOnlyProperties (Always); the conditional-# table below lists its conditionalCreateOnlyProperties (Conditionally). Any-# other property of a listed type is in place (Never), as AWS reports it. A-# stack update replaces the resource when an Always property changes. Service-# API immutability is different: an update may fail without being reported as-# a replacement (for example Cognito sign-in attributes). Types without a row-# keep the conservative Conditionally answer and their handler's behavior.# Per type, the create-only properties (Always): a change replaces the resource._REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {"AWS::DynamoDB::Table": ("TableName", "ImportSourceSpecification"),@@ -13147,6 +13181,8 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {"AWS::Glue::Crawler": ("Name",),"AWS::Glue::Job": ("Name",),"AWS::Glue::Trigger": ("Name", "WorkflowName", "Type"),+ "AWS::ApiGatewayV2::DomainName": ("DomainName",),+ "AWS::ApiGatewayV2::ApiMapping": ("DomainName",),"AWS::EFS::FileSystem": ("AvailabilityZoneName", "Encrypted", "KmsKeyId", "PerformanceMode"),"AWS::EFS::MountTarget": ("FileSystemId", "IpAddress", "IpAddressType", "Ipv6Address", "SubnetId",@@ -13358,7 +13394,8 @@ _RESOURCE_HANDLERS = {"delete": _iam_ip_delete,},"AWS::SSM::Parameter": {- "create": _ssm_create, "update": _ssm_update, "delete": _ssm_delete, "import": _ssm_import,+ "create": _ssm_create, "update": _ssm_update, "update_with_logical_id": True,+ "delete": _ssm_delete, "import": _ssm_import,},"AWS::AppConfig::Application": {"create": _appconfig_application_create,@@ -13846,6 +13883,18 @@ _RESOURCE_HANDLERS = {"delete": _apigw_v2_route_delete,},"AWS::ApiGatewayV2::Authorizer": {"create": _apigw_v2_authorizer_create, "update": _apigw_v2_authorizer_update, "delete": _apigw_v2_authorizer_delete},+ "AWS::ApiGatewayV2::DomainName": {+ "create": _apigw_v2_domain_create,+ "update": _apigw_v2_domain_update,+ "update_with_logical_id": True,+ "delete": _apigw_v2_domain_delete,+ },+ "AWS::ApiGatewayV2::ApiMapping": {+ "create": _apigw_v2_mapping_create,+ "update": _apigw_v2_mapping_update,+ "update_with_logical_id": True,+ "delete": _apigw_v2_mapping_delete,+ },"AWS::SES::EmailIdentity": {"create": _ses_email_identity_create,"update": _ses_email_identity_update,diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.pyindex 2e895865..2d136a84 100644--- a/ministack/services/cloudformation/stacks.py+++ b/ministack/services/cloudformation/stacks.py@@ -89,7 +89,6 @@ def _runs_on_worker_thread(resource_type: str) -> bool:def _update_keeping_seed(*args):- """Return _update_resource's result and the name seed it left, which a worker thread would lose.""""""_update_resource's result and the name seed it left."""return _update_resource(*args), _NAME_SEED.get()diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex d6bf4017..9ee51280 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -5518,8 +5518,7 @@ def _oauth2_authorize_federation(query_params):"redirect_uri": redirect_uri,"state": state,"scope": scope,- # The app's nonce belongs in the ID token MiniStack issues to the app;- # it is not forwarded to the external IdP.+ # Echoed in the ID token issued to the app, not forwarded to the IdP."nonce": nonce,"provider_name": identity_provider,"created_at": time.time(),@@ -5705,8 +5704,7 @@ def _saml2_idp_response(body: bytes, query_params):logger.info("Cognito: PreSignUp Lambda rejected SAML federation sign-up for %s: %s",username, e)return error_response_json("UserLambdaValidationException", str(e), 400)- # The trigger may have linked this identity (AdminLinkProviderForUser);- # AWS completes the same sign-in as the linked profile.+ # A PreSignUp link (AdminLinkProviderForUser) signs in as the linked profile.linked_username = _linked_username_for_federation(pool, provider_name, name_id, user_attrs)if linked_username:@@ -5942,8 +5940,7 @@ def _oauth2_idp_response(method, body, query_params):logger.info("Cognito: PreSignUp Lambda rejected OIDC federation sign-up for %s: %s",username, e)return error_response_json("UserLambdaValidationException", str(e), 400)- # The trigger may have linked this identity (AdminLinkProviderForUser);- # AWS completes the same sign-in as the linked profile.+ # A PreSignUp link (AdminLinkProviderForUser) signs in as the linked profile.linked_username = _linked_username_for_federation(pool, provider_name, name_id, user_attrs)if linked_username:diff --git a/ministack/services/efs.py b/ministack/services/efs.pyindex 08a6d82a..cf22fb1d 100644--- a/ministack/services/efs.py+++ b/ministack/services/efs.py@@ -153,8 +153,7 @@ def _delete_file_system(fs_id):return _error(409, "FileSystemInUse",f"File system '{fs_id}' has mount targets and cannot be deleted.")if _replication_of(fs_id):- # "You cannot delete a file system that is part of an EFS replication- # configuration." The documentation names no error code for it.+ # Documented without an error code.return _error(409, "FileSystemInUse",f"File system '{fs_id}' is part of a replication configuration; ""delete the replication configuration first.")@@ -197,8 +196,7 @@ def _update_file_system_protection(fs_id, body):if _replication_of(fs_id):return _error(409, "ReplicationAlreadyExists",f"File system '{fs_id}' is already included in a replication configuration.")- # REPLICATING marks a destination and is set by replication only; the- # documentation does not say what a caller setting it gets back.+ # REPLICATING is set by replication only.if value not in ("ENABLED", "DISABLED"):return _error(400, "BadRequest","ReplicationOverwriteProtection must be ENABLED or DISABLED.")@@ -211,8 +209,7 @@ def _update_file_system_protection(fs_id, body):# ---------------------------------------------------------------------------def _replication_of(fs_id):- """The replication configuration that has the file system as its source or- destination, from any region of the account, else None."""+ """The account's replication configuration involving the file system, in any region."""account = get_account_id()for (acct, _region, _source), config in _replication_configs.all_items():if acct != account:@@ -231,8 +228,7 @@ def _create_replication_configuration(source_id, body):destinations = body.get("Destinations")if not isinstance(destinations, list) or len(destinations) != 1:return _error(400, "BadRequest", "Exactly one destination is supported.")- # "This file system cannot already be a source or destination file system in- # another replication configuration." The documentation names no error code.+ # Documented without an error code.if _replication_of(source_id):return _error(400, "BadRequest",f"File system '{source_id}' is already part of a replication configuration.")@@ -342,8 +338,7 @@ def _delete_replication_configuration(source_id, query):d["Region"] == get_region() for d in config["Destinations"]):return _error(400, "BadRequest","LOCAL_CONFIGURATION_ONLY is not valid for same-account, same-region replication.")- # "After a replication configuration is deleted, the destination file system- # becomes writeable and its replication overwrite protection is re-enabled."+ # The destination's overwrite protection is re-enabled.for destination in config["Destinations"]:with request_scope(get_account_id(), destination["Region"]):target = _file_systems.get(destination["FileSystemId"])@@ -358,9 +353,7 @@ def _delete_replication_configuration(source_id, query):# ---------------------------------------------------------------------------def _pick_address(cidr, used, requested, kind):- """The address a mount target takes in the subnet range: the requested one- when it lies in the range and is free, else the first free host after the- four addresses a subnet reserves at its start. Returns (address, error)."""+ """The requested free address, else the first free host past the 4 reserved; (address, error)."""network = ipaddress.ip_network(cidr, strict=False)if requested:try:@@ -382,8 +375,7 @@ def _pick_address(cidr, used, requested, kind):def _security_groups_in_vpc(security_groups, vpc_id):- """The security groups for a mount target: the ones given, which must exist- in the subnet's VPC, else the VPC's default group. Returns (ids, error)."""+ """The given groups, which must be in the VPC, else its default group; (ids, error)."""from ministack.services import ec2if not security_groups:@@ -791,11 +783,7 @@ def _describe_backup_policy(fs_id):def _policy_locks_out_caller(statements):- """Whether a statement denies PutFileSystemPolicy to every principal with no- condition: the lockout the safety check refuses. Allow statements never- lock out a same-account caller, and a conditional Deny cannot be evaluated- here, so only the unconditional Deny counts (inference: the documentation- describes the check by its purpose, not its rules)."""+ """Whether an unconditional Deny of PutFileSystemPolicy covers every principal."""for statement in statements:if statement.get("Effect") != "Deny" or statement.get("Condition"):continue@@ -836,8 +824,7 @@ def _put_file_system_policy(fs_id, body):return _error(400, "InvalidPolicyException","The policy would lock out the caller from PutFileSystemPolicy; ""set BypassPolicyLockoutSafetyCheck to override.")- # The documentation's example responses carry an Id, a Sid per statement and- # the file system ARN as Resource where the request left them out.+ # Id, Sid and Resource are filled in as the API reference examples show.policy["Statement"] = statementspolicy.setdefault("Id", "1")for statement in statements:diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.pyindex df78f2ef..c8aea99d 100644--- a/tests/test_apigatewayv2.py+++ b/tests/test_apigatewayv2.py@@ -4755,7 +4755,7 @@ def test_apigwv2_tag_arns_reject_invalid_or_nonlocal_resources_before_touching_t(f"arn:aws:execute-api:us-east-1::/apis/{api_id}", "BadRequestException"),(f"arn:aws:apigateway:us-west-2::/apis/{api_id}", "BadRequestException"),(f"arn:aws:apigateway:us-east-1:000000000000:/apis/{api_id}", "BadRequestException"),- ("arn:aws:apigateway:us-east-1::/domainnames/example.com", "BadRequestException"),+ ("arn:aws:apigateway:us-east-1::/domainnames/example.com", "NotFoundException"),(f"arn:aws:apigateway:us-east-1::/apis/{api_id}/routes", "BadRequestException"),(f"arn:aws:apigateway:us-east-1::/apis/{api_id}/routes/{route['routeId']}", "BadRequestException"),(@@ -4792,3 +4792,182 @@ def test_apigwv2_tag_arns_reject_invalid_or_nonlocal_resources_before_touching_tassert status == 404assert body["__type"] == "NotFoundException"assert _apigw._api_tags.get(stage_arn) is None+++# ---------------------------------------------------------------------------+# Custom domain names and API mappings+# ---------------------------------------------------------------------------++_CERT_ARN = "arn:aws:acm:us-east-1:000000000000:certificate/11111111-2222-3333-4444-555555555555"+++def _domain(apigw, name, **kwargs):+ return apigw.create_domain_name(+ DomainName=name,+ DomainNameConfigurations=[{"CertificateArn": _CERT_ARN, "EndpointType": "REGIONAL",+ "SecurityPolicy": "TLS_1_2"}],+ **kwargs,+ )+++def test_apigwv2_domain_name_crud_shared_with_v1(apigw, apigw_v1):+ name = f"api-{_uuid_mod.uuid4().hex[:8]}.example.com"+ created = _domain(apigw, name, Tags={"team": "a"})+ try:+ assert created["DomainName"] == name+ assert created["DomainNameArn"] == f"arn:aws:apigateway:us-east-1::/domainnames/{name}"+ assert created["ApiMappingSelectionExpression"] == "$request.basepath"+ assert created["RoutingMode"] == "API_MAPPING_ONLY"+ assert created["Tags"] == {"team": "a"}+ [config] = created["DomainNameConfigurations"]+ assert config["CertificateArn"] == _CERT_ARN+ assert config["EndpointType"] == "REGIONAL"+ assert config["DomainNameStatus"] == "AVAILABLE"+ assert config["ApiGatewayDomainName"].startswith("d-")++ assert apigw.get_domain_name(DomainName=name)["DomainNameConfigurations"] == [config]+ assert name in [d["DomainName"] for d in apigw.get_domain_names()["Items"]]+ # One resource with API Gateway v1, as on AWS.+ v1 = apigw_v1.get_domain_name(domainName=name)+ assert v1["regionalCertificateArn"] == _CERT_ARN+ assert v1["regionalDomainName"] == config["ApiGatewayDomainName"]++ updated = apigw.update_domain_name(+ DomainName=name,+ DomainNameConfigurations=[{"CertificateArn": _CERT_ARN.replace("1111", "9999"),+ "EndpointType": "REGIONAL"}],+ )+ assert updated["DomainNameConfigurations"][0]["CertificateArn"].endswith("99999999-2222-3333-4444-555555555555")++ with pytest.raises(ClientError) as exc:+ _domain(apigw, name)+ assert exc.value.response["Error"]["Code"] == "ConflictException"+ finally:+ apigw.delete_domain_name(DomainName=name)+ with pytest.raises(ClientError) as exc:+ apigw.get_domain_name(DomainName=name)+ assert exc.value.response["Error"]["Code"] == "NotFoundException"+ with pytest.raises(ClientError) as exc:+ apigw_v1.get_domain_name(domainName=name)+ assert exc.value.response["Error"]["Code"] == "NotFoundException"+++def test_apigwv2_domain_name_tags(apigw):+ name = f"tags-{_uuid_mod.uuid4().hex[:8]}.example.com"+ arn = _domain(apigw, name)["DomainNameArn"]+ try:+ apigw.tag_resource(ResourceArn=arn, Tags={"env": "dev"})+ assert apigw.get_tags(ResourceArn=arn)["Tags"] == {"env": "dev"}+ assert apigw.get_domain_name(DomainName=name)["Tags"] == {"env": "dev"}+ apigw.untag_resource(ResourceArn=arn, TagKeys=["env"])+ assert apigw.get_tags(ResourceArn=arn)["Tags"] == {}+ finally:+ apigw.delete_domain_name(DomainName=name)+++def test_apigwv2_api_mapping_crud(apigw, apigw_v1):+ name = f"map-{_uuid_mod.uuid4().hex[:8]}.example.com"+ api_id = apigw.create_api(Name=f"map-{_uuid_mod.uuid4().hex[:8]}", ProtocolType="HTTP")["ApiId"]+ apigw.create_stage(ApiId=api_id, StageName="prod")+ _domain(apigw, name)+ try:+ mapping = apigw.create_api_mapping(DomainName=name, ApiId=api_id, Stage="prod", ApiMappingKey="orders")+ mapping_id = mapping["ApiMappingId"]+ assert (mapping["ApiId"], mapping["Stage"], mapping["ApiMappingKey"]) == (api_id, "prod", "orders")+ assert apigw.get_api_mapping(DomainName=name, ApiMappingId=mapping_id)["ApiMappingKey"] == "orders"+ assert [m["ApiMappingId"] for m in apigw.get_api_mappings(DomainName=name)["Items"]] == [mapping_id]+ # The v1 view of the same mapping, without the v2 id.+ v1 = apigw_v1.get_base_path_mapping(domainName=name, basePath="orders")+ assert {k: v for k, v in v1.items() if k != "ResponseMetadata"} == {+ "basePath": "orders", "restApiId": api_id, "stage": "prod"}++ with pytest.raises(ClientError) as exc:+ apigw.create_api_mapping(DomainName=name, ApiId=api_id, Stage="prod", ApiMappingKey="orders")+ assert exc.value.response["Error"]["Code"] == "ConflictException"+ assert exc.value.response["Error"]["Message"] == "ApiMapping key already exists for this domain name"+ with pytest.raises(ClientError) as exc:+ apigw.create_api_mapping(DomainName=name, ApiId="nope123", Stage="prod")+ assert exc.value.response["Error"]["Code"] == "NotFoundException"++ updated = apigw.update_api_mapping(DomainName=name, ApiMappingId=mapping_id, ApiId=api_id,+ ApiMappingKey="v2/orders")+ assert updated["ApiMappingKey"] == "v2/orders"+ assert updated["ApiMappingId"] == mapping_id++ apigw.delete_api_mapping(DomainName=name, ApiMappingId=mapping_id)+ assert apigw.get_api_mappings(DomainName=name)["Items"] == []+ with pytest.raises(ClientError) as exc:+ apigw.get_api_mapping(DomainName=name, ApiMappingId=mapping_id)+ assert exc.value.response["Error"]["Code"] == "NotFoundException"+ finally:+ apigw.delete_domain_name(DomainName=name)+ apigw.delete_api(ApiId=api_id)+++def test_apigwv2_custom_domain_routes_to_http_api(apigw):+ server, _thread, captured = _start_echo_server()+ port = server.server_address[1]+ name = f"route-{_uuid_mod.uuid4().hex[:8]}.example.com"+ api_id = apigw.create_api(Name=f"route-{_uuid_mod.uuid4().hex[:8]}", ProtocolType="HTTP")["ApiId"]+ integration_id = apigw.create_integration(+ ApiId=api_id, IntegrationType="HTTP_PROXY", IntegrationMethod="GET",+ IntegrationUri=f"http://127.0.0.1:{port}/backend", PayloadFormatVersion="1.0",+ )["IntegrationId"]+ apigw.create_route(ApiId=api_id, RouteKey="GET /hello", Target=f"integrations/{integration_id}")+ apigw.create_stage(ApiId=api_id, StageName="$default", AutoDeploy=True)+ _domain(apigw, name)+ try:+ apigw.create_api_mapping(DomainName=name, ApiId=api_id, Stage="$default", ApiMappingKey="v1")+ req = urllib.request.Request(f"http://localhost:{_EXECUTE_PORT}/v1/hello", method="GET")+ req.add_header("Host", name)+ with urllib.request.urlopen(req, timeout=10) as resp:+ assert resp.status == 200+ # The mapping key is stripped; the API sees /hello.+ assert captured["path"].endswith("/hello") and "/v1" not in captured["path"]+ finally:+ apigw.delete_domain_name(DomainName=name)+ apigw.delete_api(ApiId=api_id)+ server.shutdown()+++def test_apigwv2_api_mapping_requires_an_existing_stage(apigw):+ name = f"stage-{_uuid_mod.uuid4().hex[:8]}.example.com"+ api_id = apigw.create_api(Name=f"stage-{_uuid_mod.uuid4().hex[:8]}", ProtocolType="HTTP")["ApiId"]+ _domain(apigw, name)+ try:+ with pytest.raises(ClientError) as exc:+ apigw.create_api_mapping(DomainName=name, ApiId=api_id, Stage="missing")+ assert exc.value.response["Error"]["Code"] == "BadRequestException"+ assert exc.value.response["Error"]["Message"] == "Invalid stage identifier specified"+ finally:+ apigw.delete_domain_name(DomainName=name)+ apigw.delete_api(ApiId=api_id)+++def test_apigwv2_domain_names_and_api_mappings_paginate(apigw):+ names = [f"page{i}-{_uuid_mod.uuid4().hex[:8]}.example.com" for i in range(3)]+ api_id = apigw.create_api(Name=f"page-{_uuid_mod.uuid4().hex[:8]}", ProtocolType="HTTP")["ApiId"]+ apigw.create_stage(ApiId=api_id, StageName="prod")+ for name in names:+ _domain(apigw, name)+ try:+ seen, token = [], None+ while True:+ page = apigw.get_domain_names(MaxResults="1", **({"NextToken": token} if token else {}))+ assert len(page["Items"]) <= 1+ seen += [d["DomainName"] for d in page["Items"]]+ token = page.get("NextToken")+ if not token:+ break+ assert set(names) <= set(seen)++ for key in ("a", "b"):+ apigw.create_api_mapping(DomainName=names[0], ApiId=api_id, Stage="prod", ApiMappingKey=key)+ first = apigw.get_api_mappings(DomainName=names[0], MaxResults="1")+ second = apigw.get_api_mappings(DomainName=names[0], MaxResults="1", NextToken=first["NextToken"])+ assert [m["ApiMappingKey"] for m in first["Items"] + second["Items"]] == ["a", "b"]+ assert "NextToken" not in second+ finally:+ for name in names:+ apigw.delete_domain_name(DomainName=name)+ apigw.delete_api(ApiId=api_id)diff --git a/tests/test_bedrock_agentcore.py b/tests/test_bedrock_agentcore.pyindex 21c0e417..da6a37ef 100644--- a/tests/test_bedrock_agentcore.py+++ b/tests/test_bedrock_agentcore.py@@ -4,8 +4,10 @@ Covers the v1 surface: agent-runtime CRUD, runtime-endpoint CRUD,InvokeAgentRuntime (deterministic echo), region isolation, and validation."""import asyncio+import datetimeimport jsonimport os+import reimport sysimport threadingimport types@@ -1032,16 +1034,10 @@ def test_agentcore_state_with_legacy_arns_moves_to_aws_arns():def test_agentcore_memory_lifecycle_and_pagination():control = _client("bedrock-agentcore-control")name = f"memory_{_uuid_mod.uuid4().hex[:8]}"- with pytest.raises(ClientError) as exc:- control.create_memory(- name=f"memory_{_uuid_mod.uuid4().hex[:8]}",- eventExpiryDuration=30,- tags={"purpose": "unsupported"},- )- assert exc.value.response["Error"]["Code"] == "ValidationException"-- created = control.create_memory(name=name, eventExpiryDuration=30)+ created = control.create_memory(name=name, eventExpiryDuration=30, tags={"team": "a"})memory_id = created["memory"]["id"]+ assert created["memory"]["status"] == "CREATING"+ assert isinstance(created["memory"]["createdAt"], datetime.datetime)second_memory_id = Nonetry:@@ -1074,14 +1070,52 @@ def test_agentcore_memory_lifecycle_and_pagination():memoryId=memory_id,eventExpiryDuration=90,memoryStrategies={- "deleteMemoryStrategies": [{"memoryStrategyId": "unsupported"}]+ "deleteMemoryStrategies": [{"memoryStrategyId": "missing_strategy-abcdefghij"}]},)- assert exc.value.response["Error"]["Code"] == "ValidationException"+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"assert control.get_memory(memoryId=memory_id)["memory"]["eventExpiryDuration"] == 60+ with pytest.raises(ClientError) as exc:+ control.get_memory(memoryId=created["memory"]["arn"])+ assert exc.value.response["Error"]["Code"] == "ValidationException"finally:control.delete_memory(memoryId=memory_id)if second_memory_id:control.delete_memory(memoryId=second_memory_id)+++def test_agentcore_memory_strategies_are_recorded():+ control = _client("bedrock-agentcore-control")+ memory = control.create_memory(+ name=f"memory_{_uuid_mod.uuid4().hex[:8]}",+ eventExpiryDuration=7,+ memoryStrategies=[{"semanticMemoryStrategy": {+ "name": "facts", "namespaces": ["/facts/{actorId}"],+ }}],+ )["memory"]+ try:+ [strategy] = memory["strategies"]+ assert strategy["type"] == "SEMANTIC"+ assert strategy["name"] == "facts"+ assert strategy["namespaces"] == ["/facts/{actorId}"]+ assert strategy["status"] == "ACTIVE"+ assert re.fullmatch(r"facts-[a-zA-Z0-9]{10}", strategy["strategyId"])++ updated = control.update_memory(memoryId=memory["id"], memoryStrategies={+ "modifyMemoryStrategies": [{+ "memoryStrategyId": strategy["strategyId"], "description": "changed",+ }],+ "addMemoryStrategies": [{"summaryMemoryStrategy": {"name": "summary"}}],+ })["memory"]+ assert [(s["type"], s.get("description")) for s in updated["strategies"]] == [+ ("SEMANTIC", "changed"), ("SUMMARIZATION", None)]++ control.update_memory(memoryId=memory["id"], memoryStrategies={+ "deleteMemoryStrategies": [{"memoryStrategyId": strategy["strategyId"]}],+ })+ remaining = control.get_memory(memoryId=memory["id"])["memory"]["strategies"]+ assert [s["type"] for s in remaining] == ["SUMMARIZATION"]+ finally:+ control.delete_memory(memoryId=memory["id"])diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 10d1ee27..c6a7fb34 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -2245,6 +2245,36 @@ def test_cfn_condition_selects_from_comma_delimited_list(cfn):_delete_cfn_test_stack(cfn, name)+def test_cfn_condition_select_out_of_range_is_a_template_error(cfn):+ template = {+ "Parameters": {"Spec": {"Type": "CommaDelimitedList", "Default": "a,b"}},+ "Conditions": {"C": {"Fn::Equals": [{"Fn::Select": [5, {"Ref": "Spec"}]}, ""]}},+ "Resources": {"T": {"Type": "AWS::SNS::Topic", "Condition": "C"}},+ }+ with pytest.raises(ClientError) as exc:+ cfn.create_stack(StackName=f"cfn-sel-oob-{_uuid_mod.uuid4().hex[:8]}",+ TemplateBody=json.dumps(template))+ assert exc.value.response["Error"]["Code"] == "ValidationError"+ assert exc.value.response["Error"]["Message"] == (+ "Template error: Fn::Select cannot select nonexistent value at index 5")+++def test_cfn_ssm_parameter_rejects_a_list_value(cfn):+ name = f"cfn-ssm-list-{_uuid_mod.uuid4().hex[:8]}"+ template = {+ "Parameters": {"Names": {"Type": "CommaDelimitedList", "Default": "a,b"}},+ "Resources": {"P": {"Type": "AWS::SSM::Parameter",+ "Properties": {"Type": "String", "Value": {"Ref": "Names"}}}},+ }+ try:+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(template))+ assert _wait_stack(cfn, name)["StackStatus"] == "ROLLBACK_COMPLETE"+ assert ("Properties validation failed for resource P with message: "+ "[#/Value: expected type: String, found: JSONArray]") in _stack_event_reasons(cfn, name)+ finally:+ _delete_cfn_test_stack(cfn, name)++def test_cfn_outputs_exports(cfn):template = {"AWSTemplateFormatVersion": "2010-09-09",@@ -6767,8 +6797,7 @@ def test_cfn_servicediscovery_cdk_ecs_shape(cfn, sd):# ----------------------------------------------------------------------------# AWS::EFS::* (#1873). Ref, Fn::GetAtt and replacement properties follow the-# CloudFormation Template Reference pages for the three types.+# AWS::EFS::*# ---------------------------------------------------------------------------_efs_physical_ids = _sd_physical_ids@@ -6973,8 +7002,7 @@ def test_cfn_efs_update_replacement(cfn, efs):assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"after = _efs_physical_ids(cfn, stack_name)- # PerformanceMode replaces the file system; the mount targets and the access- # point follow because their FileSystemId changed.+ # The mount targets and access point follow the replaced file system.for logical_id in ("Fs", "Mt1", "Mt2", "Ap"):assert after[logical_id] != before[logical_id]assert efs.describe_file_systems(FileSystemId=after["Fs"])["FileSystems"][0]["PerformanceMode"] == "maxIO"@@ -33304,3 +33332,56 @@ def test_cfn_elasticache_lambda_reaches_replication_group(cfn, lam):assert result.get("reply") == "+PONG", resultfinally:_delete_cfn_test_stack(cfn, stack)+++def _cfn_apigwv2_domain_template(domain, key):+ return json.dumps({+ "Resources": {+ "Api": {"Type": "AWS::ApiGatewayV2::Api", "Properties": {"Name": "dom-api", "ProtocolType": "HTTP"}},+ "Stage": {"Type": "AWS::ApiGatewayV2::Stage",+ "Properties": {"ApiId": {"Ref": "Api"}, "StageName": "prod"}},+ "Domain": {"Type": "AWS::ApiGatewayV2::DomainName", "Properties": {+ "DomainName": domain, "Tags": {"team": "a"},+ "DomainNameConfigurations": [{"EndpointType": "REGIONAL", "CertificateArn":+ "arn:aws:acm:us-east-1:000000000000:certificate/11111111-2222-3333-4444-555555555555"}]}},+ "Mapping": {"Type": "AWS::ApiGatewayV2::ApiMapping", "DependsOn": ["Stage"], "Properties": {+ "DomainName": {"Ref": "Domain"}, "ApiId": {"Ref": "Api"}, "Stage": "prod", "ApiMappingKey": key}},+ },+ "Outputs": {+ "Domain": {"Value": {"Ref": "Domain"}},+ "Regional": {"Value": {"Fn::GetAtt": ["Domain", "RegionalDomainName"]}},+ "Arn": {"Value": {"Fn::GetAtt": ["Domain", "DomainNameArn"]}},+ "Mapping": {"Value": {"Ref": "Mapping"}},+ "MappingId": {"Value": {"Fn::GetAtt": ["Mapping", "ApiMappingId"]}},+ },+ })+++def test_cfn_apigwv2_domain_name_and_api_mapping(cfn, apigw):+ stack_name = f"cfn-apigw-dom-{_uuid_mod.uuid4().hex[:8]}"+ domain = f"{stack_name}.example.com"+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_apigwv2_domain_template(domain, "v1"))+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", _stack_event_reasons(cfn, stack_name)+ assert _output(stack, "Domain") == domain+ assert _output(stack, "Arn") == f"arn:aws:apigateway:us-east-1::/domainnames/{domain}"+ got = apigw.get_domain_name(DomainName=domain)+ assert _output(stack, "Regional") == got["DomainNameConfigurations"][0]["ApiGatewayDomainName"]+ assert got["Tags"]["team"] == "a"+ assert got["Tags"]["aws:cloudformation:logical-id"] == "Domain"+ mapping_id = _output(stack, "Mapping")+ assert _output(stack, "MappingId") == mapping_id+ assert apigw.get_api_mapping(DomainName=domain, ApiMappingId=mapping_id)["ApiMappingKey"] == "v1"++ # ApiMappingKey updates in place.+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_apigwv2_domain_template(domain, "v2"))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", _stack_event_reasons(cfn, stack_name)+ assert _output(stack, "Mapping") == mapping_id+ assert apigw.get_api_mapping(DomainName=domain, ApiMappingId=mapping_id)["ApiMappingKey"] == "v2"+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ with pytest.raises(ClientError):+ apigw.get_domain_name(DomainName=domain)+diff --git a/tests/test_dsql.py b/tests/test_dsql.pyindex 4d2fefd9..5f9c71ad 100644--- a/tests/test_dsql.py+++ b/tests/test_dsql.py@@ -1659,8 +1659,7 @@ def _prepare_postgres_image(client, image):except ImageNotFound:pass- # The daemon wraps registry token connection resets in an Engine API 500.- # Retry that observed transport failure, not permission/image/runtime errors.+ # Retry only the Engine API 500 wrapping a registry connection reset.for attempt in range(1, 4):try:client.images.pull(image)@@ -1676,80 +1675,6 @@ def _prepare_postgres_image(client, image):time.sleep(attempt)-class TestPostgresImageSetup:- """Image preparation recovers from transient errors and preserves failures."""-- @pytest.fixture- def image_client(self):- from unittest.mock import Mock-- docker = pytest.importorskip("docker")- client = Mock()- client.images.get.side_effect = docker.errors.ImageNotFound("No such image")- return client-- @staticmethod- def _pull_error(message, status=500):- import docker- from requests import Response-- response = Response()- response.status_code = status- response.url = "http+docker://localhost/v1.48/images/create"- return docker.errors.APIError("Image pull failed", response=response, explanation=message)-- def test_cached_image_does_not_contact_registry(self, image_client):- image_client.images.get.side_effect = None- _prepare_postgres_image(image_client, "postgres:16-alpine")- image_client.images.get.assert_called_once_with("postgres:16-alpine")- image_client.images.pull.assert_not_called()-- def test_connection_reset_recovers(self, image_client, monkeypatch, caplog):- from unittest.mock import Mock, call-- sleep = Mock()- monkeypatch.setattr(time, "sleep", sleep)- error = self._pull_error('Get "https://auth.docker.io/token": read: connection reset by peer')- image_client.images.pull.side_effect = [error, error, None]- _prepare_postgres_image(image_client, "postgres:16-alpine")- assert image_client.images.pull.call_args_list == [call("postgres:16-alpine")] * 3- assert sleep.call_count == 2- assert all(args[0] > 0 for args, _ in sleep.call_args_list)- assert str(error) in caplog.text-- def test_persistent_reset_is_setup_failure_with_original_errors(self, image_client, monkeypatch, caplog):- from unittest.mock import Mock-- sleep = Mock()- monkeypatch.setattr(time, "sleep", sleep)- errors = [self._pull_error(f"connection reset by peer (failure {n})") for n in range(3)]- image_client.images.pull.side_effect = errors- with pytest.raises(RuntimeError, match="after 3 pull attempts") as caught:- _prepare_postgres_image(image_client, "postgres:16-alpine")- assert caught.value.__cause__ is errors[-1]- assert image_client.images.pull.call_count == 3- assert sleep.call_count == 2- for error in errors:- assert str(error) in caplog.text-- @pytest.mark.parametrize(- ("status", "message"),- [(401, "unauthorized"), (500, "daemon failure")],- )- def test_other_pull_errors_are_not_retried(self, image_client, monkeypatch, status, message):- from unittest.mock import Mock-- sleep = Mock()- monkeypatch.setattr(time, "sleep", sleep)- error = self._pull_error(message, status)- image_client.images.pull.side_effect = error- with pytest.raises(type(error)) as caught:- _prepare_postgres_image(image_client, "postgres:16-alpine")- assert caught.value is error- image_client.images.pull.assert_called_once_with("postgres:16-alpine")- sleep.assert_not_called()--@pytest.fixture(scope="module")def pg_image():docker = pytest.importorskip("docker")diff --git a/tests/test_efs.py b/tests/test_efs.pyindex 73c80fd5..702f2e15 100644--- a/tests/test_efs.py+++ b/tests/test_efs.py@@ -353,8 +353,7 @@ def test_efs_file_system_policy(efs):put = efs.put_file_system_policy(FileSystemId=fs_id, Policy=policy)assert put["FileSystemId"] == fs_id- # The documented example responses fill in an Id, a Sid per statement and- # the file system ARN as Resource.+ # Id, Sid and Resource are filled in as the API reference examples show.stored = json.loads(put["Policy"])arn = efs.describe_file_systems(FileSystemId=fs_id)["FileSystems"][0]["FileSystemArn"]assert stored["Id"] == "1"@@ -500,9 +499,7 @@ def test_efs_put_account_preferences(efs):# ----------------------------------------------------------------------------# File system policy validation, protection, replication and mount target-# validation. Behavior follows the EFS API reference pages (documentation, not a-# run against an AWS account).+# File system policy, protection, replication and mount target validation# ---------------------------------------------------------------------------_LOCKOUT_POLICY = json.dumps({diff --git a/tests/test_health.py b/tests/test_health.pyindex 6576beac..f3001dd9 100644--- a/tests/test_health.py+++ b/tests/test_health.py@@ -1,5 +1,13 @@import jsonimport os+import pathlib+import re+import subprocess+import sys+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++import pytestENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")@@ -20,3 +28,40 @@ def test_health_endpoint_ministack():assert resp.status == 200data = json.loads(resp.read())assert data["edition"] == "light"+++_ROOT = pathlib.Path(__file__).resolve().parent.parent+++def _healthcheck_code(dockerfile):+ match = re.search(r'^\s*CMD python -c "(.*)" \|\| exit 1$', (_ROOT / dockerfile).read_text(), re.M)+ assert match, f"no HEALTHCHECK command in {dockerfile}"+ return match.group(1)++[email protected]("dockerfile", ["Dockerfile", "Dockerfile.full"])[email protected]("port_var", ["GATEWAY_PORT", "EDGE_PORT"])+def test_image_healthcheck_probes_the_configured_port(dockerfile, port_var):+ paths = []++ class _Handler(BaseHTTPRequestHandler):+ def do_GET(self):+ paths.append(self.path)+ self.send_response(200)+ self.end_headers()++ def log_message(self, *args):+ pass++ server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ try:+ env = {port_var: str(server.server_address[1])}+ result = subprocess.run(+ [sys.executable, "-c", _healthcheck_code(dockerfile)], env=env, capture_output=True, timeout=10+ )+ finally:+ server.shutdown()+ server.server_close()+ assert result.returncode == 0, result.stderr.decode()+ assert paths == ["/_ministack/health"]diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex 4e7f7fc8..666a0efa 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -13,6 +13,8 @@ the MiniStack server and work with AUTH=false.import asyncioimport jsonimport time+import xml.etree.ElementTree as ET+from urllib.parse import urlencodeimport pytestfrom botocore.exceptions import ClientError@@ -3882,3 +3884,207 @@ def test_http_iam_routing_respects_auth_mode(monkeypatch, auth_enabled, ambiguoufinally:for account in accounts:iam_svc._access_keys.pop_scoped(account, None, key, None)+++# ---------------------------------------------------------------------------+# AssumeRole trust policy: matching denies and STS request conditions (AUTH=true)+# ---------------------------------------------------------------------------++ACCOUNT = "123456789012"+CALLER = f"arn:aws:iam::{ACCOUNT}:user/trust-deployer"+ROLE_NAME = "trust-deployment"+ROLE_ARN = f"arn:aws:iam::{ACCOUNT}:role/{ROLE_NAME}"+ALLOW = {"Effect": "Allow", "Principal": {"AWS": CALLER}, "Action": "sts:AssumeRole"}+REQUIRED = {+ "StringEquals": {"sts:ExternalId": "deployment-id"},+ "StringLike": {"sts:RoleSessionName": ["deploy-?*", "release-?*"]},+}+++def _document(*statements):+ return json.dumps({"Version": "2012-10-17", "Statement": list(statements)})++[email protected]("deny_first", [False, True])+def test_trust_explicit_deny_overrides_allow_without_context(deny_first):+ deny = dict(ALLOW, Effect="Deny")+ statements = [deny, ALLOW] if deny_first else [ALLOW, deny]+ assert not evaluate_trust_policy(_document(*statements), CALLER)+++def test_trust_required_external_id_without_context_is_denied():+ assert not evaluate_trust_policy(+ _document(dict(ALLOW, Condition={"StringEquals": {"sts:ExternalId": "deployment-id"}})),+ CALLER,+ )++[email protected](params=["query", "json"])+def trust_api(request, monkeypatch):+ from ministack import app as app_mod+ from ministack.core.responses import AccountScopedDict, set_request_account_id+ from ministack.services import iam, sts++ monkeypatch.setattr(app_mod, "AUTH", True)+ monkeypatch.setattr(sts, "_sessions", {})+ monkeypatch.setattr(iam, "_users", AccountScopedDict())+ monkeypatch.setattr(iam, "_roles", AccountScopedDict())+ monkeypatch.setattr(iam, "_access_keys", AccountScopedDict())+ set_request_account_id(ACCOUNT)+ protocol = request.param+ source_key = ""++ def call(service, action, **params):+ headers = {}+ if source_key and service == "sts":+ headers["authorization"] = (+ f"AWS4-HMAC-SHA256 Credential={source_key}/20260929/us-east-1/sts/aws4_request, "+ "SignedHeaders=host, Signature=unused"+ )+ if protocol == "json":+ target = "IAMService" if service == "iam" else "AWSSecurityTokenServiceV20110615"+ headers.update({"content-type": "application/x-amz-json-1.1", "x-amz-target": f"{target}.{action}"})+ body = json.dumps(params).encode()+ else:+ headers["content-type"] = "application/x-www-form-urlencoded"+ body = urlencode({"Action": action, **params}).encode()+ if service == "sts":+ return asyncio.run(app_mod._dispatch_service_request(+ "POST", "/", headers, body, {}, "trust-test-request",+ ))+ return asyncio.run(iam.handle_request("POST", "/", headers, body, {}))++ try:+ assert call("iam", "CreateUser", UserName="trust-deployer")[0] == 200+ status, _, body = call("iam", "CreateAccessKey", UserName="trust-deployer")+ assert status == 200+ source_key = ET.fromstring(body).findtext(".//{*}AccessKeyId")+ assert source_key+ assert call("iam", "PutUserPolicy", UserName="trust-deployer", PolicyName="assume",+ PolicyDocument=_document({+ "Effect": "Allow", "Action": "sts:AssumeRole", "Resource": ROLE_ARN,+ }))[0] == 200+ yield call, sts._sessions, protocol+ finally:+ call("iam", "DeleteRole", RoleName=ROLE_NAME)+ if source_key:+ call("iam", "DeleteAccessKey", UserName="trust-deployer", AccessKeyId=source_key)+ call("iam", "DeleteUserPolicy", UserName="trust-deployer", PolicyName="assume")+ call("iam", "DeleteUser", UserName="trust-deployer")+++def _assume(api, expected_status, **params):+ call, sessions, protocol = api+ before = dict(sessions)+ status, headers, body = call("sts", "AssumeRole", RoleArn=ROLE_ARN, **params)+ assert status == expected_status, body+ if status == 403:+ if protocol == "json":+ assert headers["Content-Type"].startswith("application/x-amz-json")+ assert headers["x-amzn-errortype"] == "AccessDenied"+ error = json.loads(body)+ assert error["__type"] == "AccessDenied"+ assert "sts:AssumeRole" in error["message"]+ else:+ assert "xml" in headers["Content-Type"]+ assert ET.fromstring(body).findtext(".//{*}Code") == "AccessDenied"+ assert b"Credentials" not in body+ assert sessions == before+ else:+ if protocol == "json":+ assert headers["Content-Type"].startswith("application/x-amz-json")+ access_key = json.loads(body)["Credentials"]["AccessKeyId"]+ else:+ access_key = ET.fromstring(body).findtext(".//{*}Credentials/{*}AccessKeyId")+ assert set(sessions) - set(before) == {access_key}+ assert sessions[access_key]["SourcePrincipalArn"] == CALLER+ assert sessions[access_key]["Arn"].endswith("/" + params["RoleSessionName"])+++def _install_policy(api, operation, policy):+ call, _, _ = api+ initial = policy if operation == "CreateRole" else _document(ALLOW)+ assert call("iam", "CreateRole", RoleName=ROLE_NAME, AssumeRolePolicyDocument=initial)[0] == 200+ if operation == "UpdateAssumeRolePolicy":+ _assume(api, 200, RoleSessionName="before-update")+ assert call("iam", operation, RoleName=ROLE_NAME, PolicyDocument=policy)[0] == 200++[email protected]("operation", ["CreateRole", "UpdateAssumeRolePolicy"])[email protected]("params, expected", [+ ({"ExternalId": "deployment-id", "RoleSessionName": "deploy-123"}, 200),+ ({"ExternalId": "deployment-id", "RoleSessionName": "release-123"}, 200),+ ({"ExternalId": "wrong", "RoleSessionName": "deploy-123"}, 403),+ ({"RoleSessionName": "deploy-123"}, 403),+ ({"ExternalId": "deployment-id", "RoleSessionName": "other-123"}, 403),+])+def test_trust_requires_external_id_and_session_name(trust_api, operation, params, expected):+ _install_policy(trust_api, operation, _document(dict(ALLOW, Condition=REQUIRED)))+ _assume(trust_api, expected, **params)++[email protected]("operation", ["CreateRole", "UpdateAssumeRolePolicy"])[email protected]("deny_first", [False, True])[email protected]("deny_changes, expected", [+ ({}, 403),+ ({"Principal": {"AWS": f"arn:aws:iam::{ACCOUNT}:user/other"}}, 200),+ ({"Action": "sts:AssumeRoleWithSAML"}, 200),+ ({"Condition": {"StringEquals": {"sts:ExternalId": "deployment-id"}}}, 403),+ ({"Condition": {"StringEquals": {"sts:ExternalId": "other-id"}}}, 200),+ ({"Condition": {"StringLike": {"sts:RoleSessionName": "deploy-*"}}}, 403),+])+def test_trust_only_matching_denies_override_allow(trust_api, operation, deny_first, deny_changes, expected):+ deny = dict(ALLOW, Effect="Deny", **deny_changes)+ statements = [deny, ALLOW] if deny_first else [ALLOW, deny]+ _install_policy(trust_api, operation, _document(*statements))+ _assume(trust_api, expected, ExternalId="deployment-id", RoleSessionName="deploy-123")+++def test_trust_update_replaces_conditions_and_deny(trust_api):+ call, _, _ = trust_api+ _install_policy(trust_api, "CreateRole", _document(dict(ALLOW, Condition=REQUIRED)))+ _assume(trust_api, 200, ExternalId="deployment-id", RoleSessionName="deploy-123")+ assert call("iam", "UpdateAssumeRolePolicy", RoleName=ROLE_NAME,+ PolicyDocument=_document(ALLOW, dict(ALLOW, Effect="Deny")))[0] == 200+ _assume(trust_api, 403, ExternalId="deployment-id", RoleSessionName="deploy-123")+ assert call("iam", "UpdateAssumeRolePolicy", RoleName=ROLE_NAME,+ PolicyDocument=_document(ALLOW))[0] == 200+ _assume(trust_api, 200, RoleSessionName="unrestricted")+++def test_trust_condition_key_presence(trust_api):+ # Missing request values must remain absent, rather than becoming "".+ _install_policy(trust_api, "CreateRole", _document(dict(+ ALLOW, Condition={"Null": {"sts:ExternalId": "true"}},+ )))+ _assume(trust_api, 200, RoleSessionName="without-id")+ _assume(trust_api, 403, ExternalId="deployment-id", RoleSessionName="with-id")++[email protected]("operation", ["CreateRole", "UpdateAssumeRolePolicy"])[email protected]("deny_first", [False, True])[email protected]("excluded, condition, expected", [+ ("sts:AssumeRoleWithSAML", {}, 403),+ (["sts:AssumeRoleWithSAML", "sts:AssumeRoleWithWebIdentity"], {}, 403),+ (["sts:AssumeRoleWithSAML", "STS:Assume*"], {}, 200),+ ("sts:AssumeRoleWithSAML", {"StringEquals": {"sts:ExternalId": "other-id"}}, 200),+])+def test_trust_not_action_denies(trust_api, operation, deny_first, excluded, condition, expected):+ deny = {"Effect": "Deny", "Principal": {"AWS": CALLER},+ "NotAction": excluded, "Condition": condition}+ statements = [deny, ALLOW] if deny_first else [ALLOW, deny]+ _install_policy(trust_api, operation, _document(*statements))+ _assume(trust_api, expected, ExternalId="deployment-id", RoleSessionName="deploy-123")++[email protected]("operation", ["CreateRole", "UpdateAssumeRolePolicy"])[email protected]("policy", [+ _document(ALLOW, dict(ALLOW, Effect="Deny")),+ _document(dict(ALLOW, Condition=REQUIRED)),+])+def test_trust_denies_and_conditions_remain_permissive_without_auth(trust_api, monkeypatch, operation, policy):+ from ministack import app as app_mod++ monkeypatch.setattr(app_mod, "AUTH", False)+ _install_policy(trust_api, operation, policy)+ _assume(trust_api, 200, RoleSessionName="unrestricted")diff --git a/tests/test_lambda_runtime_worker.py b/tests/test_lambda_runtime_worker.pyindex 80498285..82e345ae 100644--- a/tests/test_lambda_runtime_worker.py+++ b/tests/test_lambda_runtime_worker.py@@ -13,6 +13,7 @@ Python worker. No Docker or running Ministack instance is required.import ioimport json+import osimport shutilimport zipfilefrom unittest.mock import MagicMock, mock_open, patch@@ -419,4 +420,22 @@ def test_node_worker_cwd_is_code_dir():worker.kill()assert result["status"] == "ok", result+ # macOS resolves /var to /private/var in process.cwd().+ assert os.path.realpath(result["result"]["cwd"]) == os.path.realpath(result["result"]["root"])+++def test_python_worker_cwd_is_code_dir():+ """os.getcwd() must be the extracted code root, as on AWS (LAMBDA_TASK_ROOT)."""+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as archive:+ archive.writestr("index.py", "import os\n\ndef handler(event, context):\n"+ " return {'cwd': os.getcwd(), 'root': os.environ['LAMBDA_TASK_ROOT']}\n")+ worker = Worker("test-fn", _config(), buf.getvalue())+ try:+ result = worker.invoke({}, request_id="cwd-request-id")+ finally:+ worker.kill()++ assert result["status"] == "ok", result+ assert os.path.realpath(result["result"]["cwd"]) == os.path.realpath(result["result"]["root"])assert result["result"]["cwd"] == result["result"]["root"]diff --git a/tests/test_sts_trust.py b/tests/test_sts_trust.pydeleted file mode 100644index 23bdd25d..00000000--- a/tests/test_sts_trust.py+++ /dev/null@@ -1,209 +0,0 @@-"""Local role trust regressions using exact IAM user principals and role grants."""--import asyncio-import json-import xml.etree.ElementTree as ET-from urllib.parse import urlencode--import pytest--from ministack.core.iam_evaluator import evaluate_trust_policy--ACCOUNT = "123456789012"-CALLER = f"arn:aws:iam::{ACCOUNT}:user/trust-deployer"-ROLE_NAME = "trust-deployment"-ROLE_ARN = f"arn:aws:iam::{ACCOUNT}:role/{ROLE_NAME}"-ALLOW = {"Effect": "Allow", "Principal": {"AWS": CALLER}, "Action": "sts:AssumeRole"}-REQUIRED = {- "StringEquals": {"sts:ExternalId": "deployment-id"},- "StringLike": {"sts:RoleSessionName": ["deploy-?*", "release-?*"]},-}---def _document(*statements):- return json.dumps({"Version": "2012-10-17", "Statement": list(statements)})--[email protected]("deny_first", [False, True])-def test_trust_explicit_deny_overrides_allow_without_context(deny_first):- deny = dict(ALLOW, Effect="Deny")- statements = [deny, ALLOW] if deny_first else [ALLOW, deny]- assert not evaluate_trust_policy(_document(*statements), CALLER)---def test_trust_required_external_id_without_context_is_denied():- assert not evaluate_trust_policy(- _document(dict(ALLOW, Condition={"StringEquals": {"sts:ExternalId": "deployment-id"}})),- CALLER,- )--[email protected](params=["query", "json"])-def trust_api(request, monkeypatch):- from ministack import app as app_mod- from ministack.core.responses import AccountScopedDict, set_request_account_id- from ministack.services import iam, sts-- monkeypatch.setattr(app_mod, "AUTH", True)- monkeypatch.setattr(sts, "_sessions", {})- monkeypatch.setattr(iam, "_users", AccountScopedDict())- monkeypatch.setattr(iam, "_roles", AccountScopedDict())- monkeypatch.setattr(iam, "_access_keys", AccountScopedDict())- set_request_account_id(ACCOUNT)- protocol = request.param- source_key = ""-- def call(service, action, **params):- headers = {}- if source_key and service == "sts":- headers["authorization"] = (- f"AWS4-HMAC-SHA256 Credential={source_key}/20260929/us-east-1/sts/aws4_request, "- "SignedHeaders=host, Signature=unused"- )- if protocol == "json":- target = "IAMService" if service == "iam" else "AWSSecurityTokenServiceV20110615"- headers.update({"content-type": "application/x-amz-json-1.1", "x-amz-target": f"{target}.{action}"})- body = json.dumps(params).encode()- else:- headers["content-type"] = "application/x-www-form-urlencoded"- body = urlencode({"Action": action, **params}).encode()- if service == "sts":- return asyncio.run(app_mod._dispatch_service_request(- "POST", "/", headers, body, {}, "trust-test-request",- ))- return asyncio.run(iam.handle_request("POST", "/", headers, body, {}))-- try:- assert call("iam", "CreateUser", UserName="trust-deployer")[0] == 200- status, _, body = call("iam", "CreateAccessKey", UserName="trust-deployer")- assert status == 200- source_key = ET.fromstring(body).findtext(".//{*}AccessKeyId")- assert source_key- assert call("iam", "PutUserPolicy", UserName="trust-deployer", PolicyName="assume",- PolicyDocument=_document({- "Effect": "Allow", "Action": "sts:AssumeRole", "Resource": ROLE_ARN,- }))[0] == 200- yield call, sts._sessions, protocol- finally:- call("iam", "DeleteRole", RoleName=ROLE_NAME)- if source_key:- call("iam", "DeleteAccessKey", UserName="trust-deployer", AccessKeyId=source_key)- call("iam", "DeleteUserPolicy", UserName="trust-deployer", PolicyName="assume")- call("iam", "DeleteUser", UserName="trust-deployer")---def _assume(api, expected_status, **params):- call, sessions, protocol = api- before = dict(sessions)- status, headers, body = call("sts", "AssumeRole", RoleArn=ROLE_ARN, **params)- assert status == expected_status, body- if status == 403:- if protocol == "json":- assert headers["Content-Type"].startswith("application/x-amz-json")- assert headers["x-amzn-errortype"] == "AccessDenied"- error = json.loads(body)- assert error["__type"] == "AccessDenied"- assert "sts:AssumeRole" in error["message"]- else:- assert "xml" in headers["Content-Type"]- assert ET.fromstring(body).findtext(".//{*}Code") == "AccessDenied"- assert b"Credentials" not in body- assert sessions == before- else:- if protocol == "json":- assert headers["Content-Type"].startswith("application/x-amz-json")- access_key = json.loads(body)["Credentials"]["AccessKeyId"]- else:- access_key = ET.fromstring(body).findtext(".//{*}Credentials/{*}AccessKeyId")- assert set(sessions) - set(before) == {access_key}- assert sessions[access_key]["SourcePrincipalArn"] == CALLER- assert sessions[access_key]["Arn"].endswith("/" + params["RoleSessionName"])---def _install_policy(api, operation, policy):- call, _, _ = api- initial = policy if operation == "CreateRole" else _document(ALLOW)- assert call("iam", "CreateRole", RoleName=ROLE_NAME, AssumeRolePolicyDocument=initial)[0] == 200- if operation == "UpdateAssumeRolePolicy":- _assume(api, 200, RoleSessionName="before-update")- assert call("iam", operation, RoleName=ROLE_NAME, PolicyDocument=policy)[0] == 200--[email protected]("operation", ["CreateRole", "UpdateAssumeRolePolicy"])[email protected]("params, expected", [- ({"ExternalId": "deployment-id", "RoleSessionName": "deploy-123"}, 200),- ({"ExternalId": "deployment-id", "RoleSessionName": "release-123"}, 200),- ({"ExternalId": "wrong", "RoleSessionName": "deploy-123"}, 403),- ({"RoleSessionName": "deploy-123"}, 403),- ({"ExternalId": "deployment-id", "RoleSessionName": "other-123"}, 403),-])-def test_trust_requires_external_id_and_session_name(trust_api, operation, params, expected):- _install_policy(trust_api, operation, _document(dict(ALLOW, Condition=REQUIRED)))- _assume(trust_api, expected, **params)--[email protected]("operation", ["CreateRole", "UpdateAssumeRolePolicy"])[email protected]("deny_first", [False, True])[email protected]("deny_changes, expected", [- ({}, 403),- ({"Principal": {"AWS": f"arn:aws:iam::{ACCOUNT}:user/other"}}, 200),- ({"Action": "sts:AssumeRoleWithSAML"}, 200),- ({"Condition": {"StringEquals": {"sts:ExternalId": "deployment-id"}}}, 403),- ({"Condition": {"StringEquals": {"sts:ExternalId": "other-id"}}}, 200),- ({"Condition": {"StringLike": {"sts:RoleSessionName": "deploy-*"}}}, 403),-])-def test_trust_only_matching_denies_override_allow(trust_api, operation, deny_first, deny_changes, expected):- deny = dict(ALLOW, Effect="Deny", **deny_changes)- statements = [deny, ALLOW] if deny_first else [ALLOW, deny]- _install_policy(trust_api, operation, _document(*statements))- _assume(trust_api, expected, ExternalId="deployment-id", RoleSessionName="deploy-123")---def test_trust_update_replaces_conditions_and_deny(trust_api):- call, _, _ = trust_api- _install_policy(trust_api, "CreateRole", _document(dict(ALLOW, Condition=REQUIRED)))- _assume(trust_api, 200, ExternalId="deployment-id", RoleSessionName="deploy-123")- assert call("iam", "UpdateAssumeRolePolicy", RoleName=ROLE_NAME,- PolicyDocument=_document(ALLOW, dict(ALLOW, Effect="Deny")))[0] == 200- _assume(trust_api, 403, ExternalId="deployment-id", RoleSessionName="deploy-123")- assert call("iam", "UpdateAssumeRolePolicy", RoleName=ROLE_NAME,- PolicyDocument=_document(ALLOW))[0] == 200- _assume(trust_api, 200, RoleSessionName="unrestricted")---def test_trust_condition_key_presence(trust_api):- # Missing request values must remain absent, rather than becoming "".- _install_policy(trust_api, "CreateRole", _document(dict(- ALLOW, Condition={"Null": {"sts:ExternalId": "true"}},- )))- _assume(trust_api, 200, RoleSessionName="without-id")- _assume(trust_api, 403, ExternalId="deployment-id", RoleSessionName="with-id")--[email protected]("operation", ["CreateRole", "UpdateAssumeRolePolicy"])[email protected]("deny_first", [False, True])[email protected]("excluded, condition, expected", [- ("sts:AssumeRoleWithSAML", {}, 403),- (["sts:AssumeRoleWithSAML", "sts:AssumeRoleWithWebIdentity"], {}, 403),- (["sts:AssumeRoleWithSAML", "STS:Assume*"], {}, 200),- ("sts:AssumeRoleWithSAML", {"StringEquals": {"sts:ExternalId": "other-id"}}, 200),-])-def test_trust_not_action_denies(trust_api, operation, deny_first, excluded, condition, expected):- deny = {"Effect": "Deny", "Principal": {"AWS": CALLER},- "NotAction": excluded, "Condition": condition}- statements = [deny, ALLOW] if deny_first else [ALLOW, deny]- _install_policy(trust_api, operation, _document(*statements))- _assume(trust_api, expected, ExternalId="deployment-id", RoleSessionName="deploy-123")--[email protected]("operation", ["CreateRole", "UpdateAssumeRolePolicy"])[email protected]("policy", [- _document(ALLOW, dict(ALLOW, Effect="Deny")),- _document(dict(ALLOW, Condition=REQUIRED)),-])-def test_trust_denies_and_conditions_remain_permissive_without_auth(trust_api, monkeypatch, operation, policy):- from ministack import app as app_mod-- monkeypatch.setattr(app_mod, "AUTH", False)- _install_policy(trust_api, operation, policy)- _assume(trust_api, 200, RoleSessionName="unrestricted")