Skip to content

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

prerelease b (#2090)

Nahuel Nucerac358ae3fd977
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4d43e4e9..63312792 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,13 +9,15 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
-- **AppConfig — gradual rollout and alarm rollback** — deployments used to complete as soon as they started. They now move through `DEPLOYING`, `BAKING` and `COMPLETE` on the strategy's schedule, and `PercentageComplete`, `EventLog` and the environment `State` follow along. A CloudWatch alarm in the environment's `Monitors` that goes to `ALARM` before the bake ends rolls the deployment back. Starting a deployment while another is in progress, or with a stale `LatestDeploymentNumber`, returns `ConflictException`. Each configuration session switches to the new version once the rollout reaches it, so a fleet of AppConfig Agent sidecars picks it up gradually. `APPCONFIG_DEPLOYMENT_MINUTE_SECONDS` sets the real seconds per strategy minute; the default `0` keeps the old behavior. Contributed by @Jolley71717.
+- **API Gateway v1 — `AWS` integrations targeting SQS** — non-proxy integrations whose URI names `sqs:path/{account}/{queue}` now reach the queue: the matching `requestTemplates` entry is rendered with the `$input.body`, `$input.json('<json-path>')`, `$input.params('<name>')` and `$util.urlEncode(...)` subset (a request with no matching template passes its body through as the form-encoded Query call), the rendered `Action` dispatch runs against the queue's own account and region, and the backend reply or error flows through `integrationResponses` — `selectionPattern` matched against the backend status code, else the default response, else 500 `Internal server error` — including `responseTemplates` and `method.response.header.*` parameters. A `SendMessage` reply reaches the response template as SQS's JSON envelope (`SendMessageResponse.SendMessageResult`). Other `AWS` service URIs still take the Lambda path. Contributed by @pingedbrain.
+- **AppConfig — gradual rollout and alarm rollback** — deployments used to complete as soon as they started. They now move through `DEPLOYING`, `BAKING` and `COMPLETE` on the strategy's schedule, and `PercentageComplete`, `EventLog` and the environment `State` follow along. A CloudWatch alarm in the environment's `Monitors` that goes to `ALARM` before the bake ends rolls the deployment back. Starting a deployment while another is in progress, or with a stale `LatestDeploymentNumber`, returns `ConflictException`. Each configuration session switches to the new version once the rollout reaches it, so a fleet of AppConfig Agent sidecars picks it up gradually. Strategy minutes are real minutes, as on AWS; a strategy with no duration and no bake completes as it starts. Contributed by @Jolley71717.
### Fixed
+- **Container reaping — one unreadable container no longer stops the sweep** — the boot sweep and the periodic reaper now list containers without inspecting each one, so a container whose inspect fails is skipped instead of leaving every leftover running. Reported by @iot-rocket.
- **API Gateway — management IAM actions and resource paths** — with `AUTH=true`, REST and HTTP/WebSocket API management requests use `apigateway:GET`, `POST`, `PUT`, `PATCH` and `DELETE` instead of SDK operation names. Resource ARNs preserve stage names, nested resources and collection paths, and ignore trailing slashes as AWS does, so scoped grants and explicit stage denies apply to the requested resource.
- **AppConfig — `GetLatestConfiguration` returns an empty body when nothing changed** — it returned the full configuration on every poll. It now also returns `Version-Label` and uses `RequiredMinimumPollIntervalInSeconds` as the poll interval, and `CreateHostedConfigurationVersion` stores `VersionLabel`. Contributed by @Jolley71717.
-- **AppConfig — `StopDeployment` follows the documented states** — it marked any deployment `ROLLED_BACK`. It now rolls back an in-progress deployment, reverts a completed one only with `AllowRevert` and within 72 hours (`REVERTED`), and returns `BadRequestException` otherwise. Contributed by @Jolley71717.
+- **AppConfig — `StopDeployment` follows the documented states** — it marked any deployment `ROLLED_BACK`. It now rolls back a `DEPLOYING` deployment (a `BAKING` one only with `AllowRevert`), reverts a completed one only with `AllowRevert` and within 72 hours (`REVERTED`), and returns `BadRequestException` otherwise. Contributed by @Jolley71717.
- **API Gateway v1 — `AWS` integrations targeting SQS** — non-proxy integrations whose URI names `sqs:path/{account}/{queue}` now reach the queue: the matching `requestTemplates` entry is rendered with the `$input.body`, `$input.json('<json-path>')`, `$input.params('<name>')` and `$util.urlEncode(...)` subset (a request with no matching template passes its body through as the form-encoded Query call), the rendered `Action` dispatch runs against the queue's own account and region, and the backend reply or error flows through `integrationResponses` — `selectionPattern` matched against the backend status code or error body, else the default response — including `responseTemplates` and `method.response.header.*` parameters. Other `AWS` service URIs still take the Lambda path. Closes #2045. Contributed by @pingedbrain.
@@ -33,7 +35,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **IoT — `DescribeCertificate` reports `certificateMode`** — the field was missing from the description. It is now `SNI_ONLY` for a certificate registered with `RegisterCertificateWithoutCA` and `DEFAULT` for the others, as AWS reports it. Contributed by @iot-rocket.
### Fixed
-- **CloudWatch Logs — IAM tag conditions** — under `AUTH=true`, authorization now includes existing resource tags, incoming request tags, and the tag keys being added or removed. Ownership-based allows work and explicit denies can prevent removal of protected tags before state changes. ARN-based tagging APIs authorize the supplied resource ARN instead of `*` and share a validated, account- and region-scoped target lookup with the handlers. Foreign or malformed tagging ARNs, including log group ARNs ending in `:*`, fail with HTTP 400 `ValidationException` before policy evaluation, as observed on AWS. Authorization denials match live AWS's HTTP 400 JSON 1.1 envelope with a capitalized `Message` naming the resource. Contributed by @AdrianAcala.
+- **CloudWatch Logs — IAM tag conditions** — under `AUTH=true`, authorization now includes existing resource tags, incoming request tags, and the tag keys being added or removed. Ownership-based allows work and explicit denies can prevent removal of protected tags before state changes. ARN-based tagging APIs authorize the supplied resource ARN instead of `*` and share a validated, account- and region-scoped target lookup with the handlers. Foreign or malformed tagging ARNs fail with HTTP 400 `ValidationException` before policy evaluation. This includes a log group ARN ending in `:*`, the `arn` that `DescribeLogGroups` returns, which tagged on earlier versions: pass `logGroupArn` instead. Authorization denials match live AWS's HTTP 400 JSON 1.1 envelope with a capitalized `Message` naming the resource. Contributed by @AdrianAcala.
- **Step Functions — `$$.State.RetryCount`** — the Context Object's `State` carried only `Name` and `EnteredTime`, so `"x.$": "$$.State.RetryCount"` resolved to `null`, and a Task's `Parameters` were evaluated once, so a retry resent the first attempt's values. `State.RetryCount` (a number in the Context Object documentation) is now `0` when a state is entered and counts its retries (Task, Parallel and Map), and a Task's `Parameters` are evaluated for each attempt, as JSONata `Arguments` already were.
- **Step Functions — `StopExecution` keeps its `error` and `cause`** — they were recorded only in the `ExecutionAborted` history event, so `DescribeExecution` of the aborted execution returned neither. They are now kept on the execution and returned by `DescribeExecution`; AWS returns the `cause` of an execution stopped with one.
@@ -44,10 +46,10 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **IoT — `https://<endpointAddress>` verifies under `USE_SSL=1`** — `DescribeEndpoint` hands out `<prefix>-ats.iot.<region>.<MINISTACK_HOST>` and `<prefix>.credentials.iot.<region>.<MINISTACK_HOST>`, which SDKs dial over HTTPS as on AWS, but the generated gateway certificate did not name them, so the handshake failed hostname verification. The certificate now carries `*.iot.<region>.<MINISTACK_HOST>` and `*.credentials.iot.<region>.<MINISTACK_HOST>` for every region, and a cached certificate without them is regenerated. Contributed by @iot-rocket.
### Added
-- **SES — receipt-rule metadata** — Receipt rule sets can be created, activated, described, listed and deleted, and rules can be created in order, described and deleted through signed or unsigned Query requests. Resources are isolated by account and region and persisted. Names and recipients are validated; headers that cannot be represented in XML return AWS-shaped readback errors. Receipt actions are limited to AddHeader and Stop without an SNS topic; unsupported actions fail explicitly. Inbound email receiving is not emulated.
+- **SES — receipt-rule metadata** — Receipt rule sets can be created, activated, described, listed and deleted, and rules can be created in order, described and deleted through signed or unsigned Query requests. Resources are isolated by account and region and persisted. Names and recipients are validated; headers that cannot be represented in XML return AWS-shaped readback errors. Every receipt action type is stored and described; inbound email receiving is not emulated, so no action runs.
- **CloudFront — custom error responses on the data plane** — a distribution's `CustomErrorResponses` were stored but never applied, so an origin error reached the viewer unchanged. When the origin answers a configured `ErrorCode`, the data plane now fetches `ResponsePagePath` through the cache behavior that path matches and returns it with `ResponseCode`; a page that cannot be fetched is answered with the status its origin returned, as the Developer Guide describes. `ErrorCachingMinTTL` is stored only, since the data plane does not cache.
- **IoT — job templates and `AWS::IoT::JobTemplate`** — `CreateJobTemplate`, `DescribeJobTemplate`, `ListJobTemplates` and `DeleteJobTemplate` were missing, so a `jobTemplateArn` could not be created or used. Templates now store a document or a `documentSource` (not fetched, like `CreateJob`'s), every job configuration member, maintenance windows and tags, can be copied from a job through `jobArn`, list newest first with `maxResults` / `nextToken` paging, and answer AWS's errors and messages. `CreateJob` with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a member the request names replaces the template's. CloudFormation creates and deletes `AWS::IoT::JobTemplate` (Ref is the id, `Fn::GetAtt` `Arn`); every property is create-only, so an update under the same `JobTemplateId` fails with AWS's custom-name sentence and a new id replaces the template. Contributed by @iot-rocket.
-- **SES v2 — tenants and resource associations** — supports tenant creation, readback, listing, deletion, tags and suppression attributes (`PutTenantSuppressionAttributes`), with configuration-set, identity and template resource associations and readback in both directions. Tenants and associations are isolated by account and region and persisted; deleting an associated configuration set, template or identity through either API version requires removing tenant associations first. Associations recognize resources created through either API version, and foreign ARN partitions are accepted and normalized for storage, matching and readback.
+- **SES v2 — tenants and resource associations** — `CreateTenant`, `GetTenant`, `ListTenants`, `DeleteTenant`, `PutTenantSuppressionAttributes` and the tenant resource association operations, for configuration sets, identities and templates from either API version. A resource with tenant associations cannot be deleted until they are removed. Contributed by @AdrianAcala.
### Fixed
- **DynamoDB — transactions are authorized per item under `AUTH=true`** — `TransactWriteItems` and `TransactGetItems` were checked as `dynamodb:TransactWriteItems` / `dynamodb:TransactGetItems` on the first item's table, which are not IAM actions, so a policy granting the item actions was refused and one granting the transaction name was accepted. Each item is now checked as the action it performs (`dynamodb:PutItem`, `UpdateItem`, `DeleteItem`, `ConditionCheckItem`, `GetItem`) on its own table. Each item check carries `dynamodb:EnclosingOperation`, so policies that allow or deny only transactional calls evaluate as on AWS. Contributed by @drakeo338.
diff --git a/README.md b/README.md
index 5b1f6b70..f4fc4ea7 100644
--- a/README.md
+++ b/README.md
@@ -118,7 +118,6 @@ The config endpoint supports these keys:
| `athena.ATHENA_DATA_DIR` | Directory for Athena DuckDB data files |
| `stepfunctions._sfn_mock_config` | SFN mock config (AWS SFN Local compatible) |
| `stepfunctions._SFN_WAIT_SCALE` | Scale factor for Wait state durations and retry sleeps (`0` = skip all waits) |
-| `appconfig._DEPLOYMENT_MINUTE_SECONDS` | Real seconds per minute of an AppConfig deployment strategy (`0` = deployments complete as they start, `60` = AWS pace) |
To set region or account ID, use environment variables at startup:
@@ -425,7 +424,7 @@ subnet = ec2.create_subnet(
| **EventBridge** | CreateEventBus, UpdateEventBus, DeleteEventBus, ListEventBuses, DescribeEventBus, PutRule, DeleteRule, ListRules, DescribeRule, EnableRule, DisableRule, PutTargets, RemoveTargets, ListTargetsByRule, ListRuleNamesByTarget, PutEvents, TestEventPattern, TagResource, UntagResource, ListTagsForResource, CreateArchive, DeleteArchive, DescribeArchive, UpdateArchive, ListArchives, PutPermission, RemovePermission, CreateConnection, DescribeConnection, DeleteConnection, UpdateConnection, DeauthorizeConnection, ListConnections, CreateApiDestination, DescribeApiDestination, DeleteApiDestination, UpdateApiDestination, ListApiDestinations, StartReplay, DescribeReplay, ListReplays, CancelReplay, CreateEndpoint, DeleteEndpoint, DescribeEndpoint, ListEndpoints, UpdateEndpoint, ActivateEventSource, DeactivateEventSource, DescribeEventSource, CreatePartnerEventSource, DeletePartnerEventSource, DescribePartnerEventSource, ListPartnerEventSources, ListPartnerEventSourceAccounts, ListEventSources, PutPartnerEvents | Lambda target dispatch on PutEvents; S3 EventBridge notifications; archives capture matching events and `StartReplay` re-dispatches them to the destination bus in a background thread; API destination targets are **invoked over HTTP** on PutEvents — connection auth (Basic, API Key, OAuth client-credentials with token caching and 401/407 refresh), connection/target header/query/body parameter merging with connection precedence, `*` path parameters, dynamic JSON-path parameter values resolved from the untransformed event, and the AWS default headers (`User-Agent: Amazon/EventBridge/ApiDestinations`, default `Content-Type: application/json; charset=utf-8`), which connection and target parameters cannot override; redirects are not followed (a `3xx` is a non-retryable delivery failure), only `http(s)` invocation and OAuth authorization endpoints are accepted, `HttpMethod` and `AuthorizationType` are validated against their enums, and a connection that is not `AUTHORIZED` is not invoked (`DeauthorizeConnection` clears its stored credentials) — the 24h retry pipeline, rate limiting, and DLQs are not modeled; SaaS/partner APIs are otherwise control-plane stubs. Event patterns are **validated** — `PutRule`, `TestEventPattern`, `CreateArchive` and `UpdateArchive` reject a malformed pattern with `InvalidEventPatternException` carrying AWS's own reason text — and evaluate `prefix`/`suffix` (plain or case-insensitive via a nested `equals-ignore-case`), `wildcard` (AWS semantics — only `*` is special, `\` escapes — with catastrophic backtracking ruled out), `equals-ignore-case` (AWS's per-character case alternation), `exactly`, `cidr` (IPv4/IPv6, host bits floored, `/32` and `/128` refused as AWS refuses them), `numeric` (as the grammar it is: one comparison or a lower-then-upper bound), `exists` (leaf nodes only, so an object or an empty array does not exist), `anything-but` (a literal, a list, or a nested `prefix`/`suffix`/`wildcard`/`equals-ignore-case`, singly or as a list), and `$or` at any field position — expanded into flat alternatives at rule creation, so AWS's per-leaf last-write-wins collision rule and its 1000-combination cap both hold. All ten envelope fields are filterable, an unmodelled key is a path the event lacks rather than an error, `resources` is an intersection, array values are matched per element (with AWS's array-consistency rule), and values compare as JSON so a string never equals a number. An operand or key the matcher cannot evaluate never matches, rather than raising or matching everything. Not modeled: the 4096-character pattern limit, the wildcard-complexity refusal, and the 256-leaf rule-size cap |
| **Kinesis** | CreateStream, DeleteStream, DescribeStream, DescribeStreamSummary, ListStreams, ListShards, PutRecord, PutRecords, GetShardIterator, GetRecords, IncreaseStreamRetentionPeriod, DecreaseStreamRetentionPeriod, MergeShards, SplitShard, UpdateShardCount, StartStreamEncryption, StopStreamEncryption, EnableEnhancedMonitoring, DisableEnhancedMonitoring, RegisterStreamConsumer, DeregisterStreamConsumer, ListStreamConsumers, DescribeStreamConsumer, SubscribeToShard, AddTagsToStream, RemoveTagsFromStream, ListTagsForStream | Partition key → shard routing; AWS limits enforced (1 MB/record, 500 records/batch, 5 MB payload, 256-char partition key); SubscribeToShard pushes `SubscribeToShardEvent`s over HTTP/1.1 or HTTP/2 (h2c) for up to 5 minutes, JSON or CBOR |
| **CloudWatch Metrics** | PutMetricData, GetMetricStatistics, GetMetricData, ListMetrics, PutMetricAlarm, PutCompositeAlarm, DescribeAlarms, DescribeAlarmsForMetric, DescribeAlarmHistory, DeleteAlarms, SetAlarmState, EnableAlarmActions, DisableAlarmActions, TagResource, UntagResource, ListTagsForResource, PutDashboard, GetDashboard, DeleteDashboards, ListDashboards | CBOR and JSON protocol |
-| **SES** | SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail, VerifyEmailIdentity, VerifyEmailAddress, VerifyDomainIdentity, VerifyDomainDkim, ListIdentities, ListVerifiedEmailAddresses, GetIdentityVerificationAttributes, GetIdentityDkimAttributes, DeleteIdentity, GetSendQuota, GetSendStatistics, SetIdentityNotificationTopic, SetIdentityFeedbackForwardingEnabled, CreateConfigurationSet, DeleteConfigurationSet, DescribeConfigurationSet, ListConfigurationSets, CreateTemplate, GetTemplate, UpdateTemplate, DeleteTemplate, ListTemplates, CreateReceiptRuleSet, DescribeReceiptRuleSet, ListReceiptRuleSets, DeleteReceiptRuleSet, SetActiveReceiptRuleSet, DescribeActiveReceiptRuleSet, CreateReceiptRule, DescribeReceiptRule, DeleteReceiptRule | Emails stored in-memory, not sent; the sender must be a verified identity (`MessageRejected` otherwise), and a sandboxed account sends only to verified or `@simulator.amazonses.com` recipients; receipt rule metadata is stored and persisted, with ordered AddHeader and Stop actions (without SNS topics); inbound email receiving is not emulated |
+| **SES** | SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail, VerifyEmailIdentity, VerifyEmailAddress, VerifyDomainIdentity, VerifyDomainDkim, ListIdentities, ListVerifiedEmailAddresses, GetIdentityVerificationAttributes, GetIdentityDkimAttributes, DeleteIdentity, GetSendQuota, GetSendStatistics, SetIdentityNotificationTopic, SetIdentityFeedbackForwardingEnabled, CreateConfigurationSet, DeleteConfigurationSet, DescribeConfigurationSet, ListConfigurationSets, CreateTemplate, GetTemplate, UpdateTemplate, DeleteTemplate, ListTemplates, CreateReceiptRuleSet, DescribeReceiptRuleSet, ListReceiptRuleSets, DeleteReceiptRuleSet, SetActiveReceiptRuleSet, DescribeActiveReceiptRuleSet, CreateReceiptRule, DescribeReceiptRule, DeleteReceiptRule | Emails stored in-memory, not sent; the sender must be a verified identity (`MessageRejected` otherwise), and a sandboxed account sends only to verified or `@simulator.amazonses.com` recipients; receipt rule sets and ordered rules, with every action type, are stored and persisted; inbound email receiving is not emulated |
| **SES v2** | SendEmail, CreateEmailIdentity, GetEmailIdentity, DeleteEmailIdentity, ListEmailIdentities, CreateConfigurationSet, GetConfigurationSet, DeleteConfigurationSet, ListConfigurationSets, CreateEmailTemplate, GetEmailTemplate, UpdateEmailTemplate, DeleteEmailTemplate, ListEmailTemplates, GetAccount, PutAccountDetails, PutAccountSuppressionAttributes, ListSuppressedDestinations, TagResource, UntagResource, ListTagsForResource | REST API (`/v2/email/`); identities auto-verified; emails stored in-memory, not sent; `PutAccountDetails` with `ProductionAccessEnabled=false` puts the account in the sandbox; email templates share the v1 store, so `SendEmail` with `Content.Template` renders a template created through either API version |
| **ACM** | RequestCertificate, DescribeCertificate, ListCertificates, DeleteCertificate, GetCertificate, ImportCertificate, AddTagsToCertificate, RemoveTagsFromCertificate, ListTagsForCertificate, UpdateCertificateOptions, RenewCertificate, ResendValidationEmail | Certificates auto-issued; DNS validation records generated; supports SANs |
| **Backup** | CreateBackupVault, DescribeBackupVault, DeleteBackupVault, ListBackupVaults, CreateBackupPlan, GetBackupPlan, UpdateBackupPlan, DeleteBackupPlan, ListBackupPlans, ListBackupPlanVersions, CreateBackupSelection, GetBackupSelection, DeleteBackupSelection, ListBackupSelections, StartBackupJob, StopBackupJob, DescribeBackupJob, ListBackupJobs, TagResource, UntagResource, ListTags | In-memory; jobs complete immediately; vaults and plans participate in Resource Groups Tagging API |
@@ -642,7 +641,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i
| **S3 Files** | CreateFileSystem, GetFileSystem, ListFileSystems, DeleteFileSystem, CreateMountTarget, GetMountTarget, ListMountTargets, UpdateMountTarget, DeleteMountTarget, CreateAccessPoint, GetAccessPoint, ListAccessPoints, DeleteAccessPoint, GetFileSystemPolicy, PutFileSystemPolicy, DeleteFileSystemPolicy, GetSynchronizationConfiguration, PutSynchronizationConfiguration, TagResource, UntagResource, ListTagsForResource | 21 operations; control plane for the new S3 Files service (launched April 2026); file systems, mount targets, access points, policies |
| **AutoScaling** | CreateAutoScalingGroup, DescribeAutoScalingGroups, UpdateAutoScalingGroup, DeleteAutoScalingGroup, SetDesiredCapacity, DescribeAutoScalingInstances, CreateLaunchConfiguration, DescribeLaunchConfigurations, DeleteLaunchConfiguration, PutScalingPolicy, DescribePolicies, DeletePolicy, PutLifecycleHook, DescribeLifecycleHooks, DeleteLifecycleHook, CompleteLifecycleAction, RecordLifecycleActionHeartbeat, PutScheduledUpdateGroupAction, DescribeScheduledActions, DeleteScheduledAction, CreateOrUpdateTags, DescribeTags, DeleteTags | 24 actions; in-memory state — no real instances, but groups report `DesiredCapacity` in-service instances so Terraform's `aws_autoscaling_group` capacity waiter converges; full ASG lifecycle (launch configs, scaling policies, lifecycle hooks, scheduled actions, tags); CDK/Terraform compatible |
| **CodeBuild** | CreateProject, BatchGetProjects, ListProjects, UpdateProject, DeleteProject, StartBuild, BatchGetBuilds, StopBuild, ListBuilds, ListBuildsForProject, BatchDeleteBuilds | 11 actions; project and build metadata stored in-memory; builds complete immediately with SUCCEEDED status by default. Set `MINISTACK_CODEBUILD_EXECUTE=1` and mount the Docker socket to **really run them**: the project's inline buildspec goes to the official AWS CodeBuild local agent, which runs the phases in `environment.image`, and `BatchGetBuilds` reports live `phases` with a real `SUCCEEDED`/`FAILED` outcome. Execution needs the workspace shared with the host at the **same path** (`-v /tmp/ministack-codebuild:/tmp/ministack-codebuild`), because the agent bind-mounts it into the build container; a build gets `AWS_ENDPOINT_URL` pointing back at MiniStack, honours `timeoutInMinutes`, and is stopped by `StopBuild`. An executed build streams the agent output into its `logs.groupName` / `logs.streamName`, so `aws logs tail` reads the build log back |
-| **AppConfig** | CreateApplication, GetApplication, ListApplications, UpdateApplication, DeleteApplication, CreateEnvironment, GetEnvironment, ListEnvironments, UpdateEnvironment, DeleteEnvironment, CreateConfigurationProfile, GetConfigurationProfile, ListConfigurationProfiles, UpdateConfigurationProfile, DeleteConfigurationProfile, CreateHostedConfigurationVersion, GetHostedConfigurationVersion, ListHostedConfigurationVersions, DeleteHostedConfigurationVersion, CreateDeploymentStrategy, GetDeploymentStrategy, ListDeploymentStrategies, UpdateDeploymentStrategy, DeleteDeploymentStrategy, StartDeployment, GetDeployment, ListDeployments, StopDeployment, TagResource, UntagResource, ListTagsForResource, StartConfigurationSession, GetLatestConfiguration | 33 operations; control plane + data plane; hosted configuration versions; the AWS-predefined deployment strategies (4) are listed and immutable; deployments move through `DEPLOYING`, `BAKING` and `COMPLETE` on the strategy's schedule (`LINEAR` or `EXPONENTIAL` steps, then the bake time), with `PercentageComplete`, the event log and the environment `State` reported along the way; `APPCONFIG_DEPLOYMENT_MINUTE_SECONDS` sets the real seconds per strategy minute (default `0`, deployments complete immediately); a `Monitors` alarm that goes to `ALARM` before the bake ends rolls the deployment back; one deployment per environment at a time (`ConflictException`, also for a stale `LatestDeploymentNumber`); `StopDeployment` rolls back an in-progress deployment and, with `AllowRevert`, reverts a completed one within 72 hours; during a rollout a session gets the new version once the rollout reaches its fixed slot (MiniStack's choice, since AWS does not document how it picks targets); `GetLatestConfiguration` returns an empty body when the session already has the latest version, plus `Version-Label`, and uses `RequiredMinimumPollIntervalInSeconds` as the poll interval |
+| **AppConfig** | CreateApplication, GetApplication, ListApplications, UpdateApplication, DeleteApplication, CreateEnvironment, GetEnvironment, ListEnvironments, UpdateEnvironment, DeleteEnvironment, CreateConfigurationProfile, GetConfigurationProfile, ListConfigurationProfiles, UpdateConfigurationProfile, DeleteConfigurationProfile, CreateHostedConfigurationVersion, GetHostedConfigurationVersion, ListHostedConfigurationVersions, DeleteHostedConfigurationVersion, CreateDeploymentStrategy, GetDeploymentStrategy, ListDeploymentStrategies, UpdateDeploymentStrategy, DeleteDeploymentStrategy, StartDeployment, GetDeployment, ListDeployments, StopDeployment, TagResource, UntagResource, ListTagsForResource, StartConfigurationSession, GetLatestConfiguration | 33 operations; control plane + data plane; hosted configuration versions; the AWS-predefined deployment strategies (4) are listed and immutable; deployments move through `DEPLOYING`, `BAKING` and `COMPLETE` on the strategy's schedule (`LINEAR` or `EXPONENTIAL` steps, then the bake time), with `PercentageComplete`, the event log and the environment `State` reported along the way; a `Monitors` alarm that goes to `ALARM` before the bake ends rolls the deployment back; one deployment per environment at a time (`ConflictException`, also for a stale `LatestDeploymentNumber`); `StopDeployment` rolls back a `DEPLOYING` deployment, and with `AllowRevert` also a `BAKING` one, or reverts a completed one within 72 hours; during a rollout a session gets the new version once the rollout reaches its fixed slot (MiniStack's choice, since AWS does not document how it picks targets); `GetLatestConfiguration` returns an empty body when the session already has the latest version, plus `Version-Label`, and uses `RequiredMinimumPollIntervalInSeconds` as the poll interval |
| **Transfer Family** | CreateServer, DescribeServer, DeleteServer, ListServers, StartServer, StopServer, CreateUser, DescribeUser, DeleteUser, ListUsers, ImportSshPublicKey, DeleteSshPublicKey | 12 operations; **real SFTP listener** on `:2222` (override with `SFTP_PORT`) backed by S3 — `ls`, `put`, `get`, `mkdir`, `rename` work end-to-end against the local S3 emulator; `SFTP_PORT_PER_SERVER=1` allocates one port per `CreateServer` from `SFTP_BASE_PORT` (default 2300); SSH key auth scans every user across every server and account; `LOGICAL` and `PATH` home-directory mappings; host key persists across restarts when `PERSIST_STATE=1` |
| **IoT Jobs** | Control plane (`iot`): CreateJob, DescribeJob, ListJobs, GetJobDocument, CancelJob, DeleteJob, ListJobExecutionsForThing, DescribeJobExecution, CancelJobExecution, CreateJobTemplate, DescribeJobTemplate, ListJobTemplates, DeleteJobTemplate; data plane (`iot-jobs-data`): GetPendingJobExecutions, StartNextPendingJobExecution, DescribeJobExecution (incl. the `$next` sentinel), UpdateJobExecution | 13 control-plane + 4 device data-plane operations sharing one store. A job created with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a request member replaces the template's. Executions walk `QUEUED → IN_PROGRESS → {SUCCEEDED, FAILED, REJECTED, CANCELED, TIMED_OUT}`; an execution past its `timeoutConfig.inProgressTimeoutInMinutes`, or past the `stepTimeoutInMinutes` the device reported, becomes `TIMED_OUT`, and the device plane reports `approximateSecondsBeforeTimedOut` while it runs. `REMOVED` is modeled and counted in `jobProcessDetails` but nothing sets it: deleting a thing DELETES its executions (freeing a job that was only waiting on that thing) rather than marking them `REMOVED`. `versionNumber` gives optimistic concurrency: every transition bumps it and a stale `expectedVersion` is rejected with a 409 whose message carries the current version — coded `VersionConflictException` on the control plane and `InvalidStateTransitionException` on the device plane, each as its own service model declares. `executionNumber` is write-once (always 1: an execution is never re-queued). Devices may only report `IN_PROGRESS` / `SUCCEEDED` / `FAILED` / `REJECTED` via `UpdateJobExecution`; targets are thing or thing-group ARNs — `SNAPSHOT` jobs resolve group membership once at creation, `CONTINUOUS` jobs also pick up things added to a target group later, and a target must name a thing or thing group in the caller's own account and region (anything else is `ResourceNotFoundException`, since it would resolve to no devices at all); a non-continuous job auto-`COMPLETED`s (with `jobProcessDetails` counts) once every execution is terminal. **`documentSource` is not fetched**: a job created with an S3 `documentSource` serves a `{"documentSource": "<url>"}` placeholder as its document rather than the object's content, so the lifecycle still runs — pass `document` when the content matters; a job template with a `documentSource` stores the same placeholder. **Timestamps are epoch seconds on every plane, as AWS documents**: control-plane responses use `timestamp` shapes (boto3 parses them to datetimes) while `iot-jobs-data` responses carry whole-second integer `long`s. **Jobs over MQTT**: the reserved `$aws/things/<thing>/jobs/#` request topics (`get`, `start-next`, `<jobId>/get` incl. `$next`, `<jobId>/update`) answer on their `accepted`/`rejected` topics from the same store as the HTTP plane (`jobDocument` as a JSON object over MQTT, a string over HTTP, as on AWS; rejections carry the string `ErrorCode` values and the execution's state on version and state-transition conflicts); `notify` fires when the pending set changes and `notify-next` when the queue front changes; `stepTimeoutInMinutes` and `executionNumber` are accepted but ignored. Job state persists with the IoT store when `PERSIST_STATE=1` |
| **IoT Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, ListThingGroupsForThing, CreateKeysAndCertificate, RegisterCertificate, RegisterCertificateWithoutCA, UpdateCertificate, DeleteCertificate, GetRegistrationCode, DeleteRegistrationCode, RegisterCACertificate, DescribeCACertificate, UpdateCACertificate, ListCACertificates, DeleteCACertificate, ListCertificatesByCA, CreateProvisioningTemplate, DescribeProvisioningTemplate, ListProvisioningTemplates, UpdateProvisioningTemplate, DeleteProvisioningTemplate, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, AttachPrincipalPolicy, DetachPrincipalPolicy, ListPrincipalPolicies, ListPolicyPrincipals, CreateTopicRule, GetTopicRule, ReplaceTopicRule, DeleteTopicRule, ListTopicRules, UpdateIndexingConfiguration, GetIndexingConfiguration, DescribeIndex, ListIndices, SearchIndex, DescribeEndpoint, Publish (HTTP), MQTT-over-WebSocket pub/sub, DescribeEventConfigurations, UpdateEventConfigurations | 57 operations + **MQTT 3.1.1 and 5.0 over WebSocket** (negotiated per connection) on the gateway port — clients use the address returned by `DescribeEndpoint`; local CA signs `CreateKeysAndCertificate` certificates (CA persists across restarts when `PERSIST_STATE=1`); multi-tenancy via transparent topic prefixing (same pattern as Transfer Family's shared SFTP listener); no plain TCP 1883 (real AWS IoT requires TLS or SigV4 on every connection), but a **native mTLS MQTT listener on 8883** serves device SDK binaries by default — the client certificate is optional (no certificate means the default account, like an unsigned WebSocket upgrade) and, when presented, must be registered `ACTIVE` in exactly one account, which then serves the session; unknown, inactive or doubly-registered certificates get a "not authorized" CONNACK (see `IOT_MTLS_PORT` in the environment table); local CA cert available at `GET /_ministack/iot/ca.pem` for SDK trust configuration; IoT policies are stored but **not enforced** on the data plane; **fleet indexing** works the way it does on AWS — `UpdateIndexingConfiguration` turns the `AWS_Things` index on (Terraform `aws_iot_indexing_configuration`), and searching while `thingIndexingMode` is `OFF` answers `ResourceNotFoundException`; `SearchIndex` then queries the live registry + classic shadows with `AND`-separated `thingName` / `thingTypeName` / `thingGroupNames` / `attributes.*` / `shadow.reported.*` / `shadow.desired.*` terms (`*` / `?` wildcards, `maxResults` / `nextToken` paging) — there is no projection to build, so hits are always current; the deprecated principal-policy family (`AttachPrincipalPolicy` / `DetachPrincipalPolicy` / `ListPrincipalPolicies` / `ListPolicyPrincipals`) maps 1:1 onto the modern policy-target store; **topic rules fire on matching publishes** (incl. Basic Ingest `$aws/rules/<name>`) with SQL SELECT projection (`topic()`, `timestamp()`, `encode()`, `newuuid()`, `replace()`, `clientid()`, `isUndefined()`), **WHERE-clause evaluation** (comparisons, `IN`, `LIKE`, `BETWEEN`, `IS NULL`, `regexp_matches`, bare boolean attributes, composed with `AND` / `OR` and parenthesised grouping; missing attributes fail closed as on AWS; unparseable SQL → `SqlParseException`), and `lambda` / `republish` / `dynamoDBv2` / `sns` / `sqs` actions dispatched in-process with the rule's `errorAction` on failure; **device shadows over MQTT** — the `$aws/things/<thing>/shadow[/name/<name>]/{get,update,delete}` reserved topics drive the shadow store and reply on `accepted` / `rejected` (with `delta` and `documents` on update); a **CA-certificate registry** (`RegisterCACertificate` and friends) with the just-in-time-registration `registered` event on `$aws/events/certificates/registered/{caCertificateId}`; a **provisioning-template registry** (`CreateProvisioningTemplate` and friends) — storage + CRUD only, so `provisioningRoleArn` is presence-checked but not resolved and the fleet-provisioning MQTT workflow (`$aws/provisioning-templates/...`) is not implemented; and `SearchIndex` answers `connectivity.connected` / `connectivity.timestamp` / `connectivity.disconnectReason` when `thingConnectivityIndexingMode` is `STATUS`, deriving `connected` from the live session registry; the broker publishes the presence and subscription lifecycle events (`$aws/events/presence/connected\|disconnected/{clientId}`, `$aws/events/subscriptions/subscribed\|unsubscribed/{clientId}`) |
@@ -931,7 +930,6 @@ come from `repositoryCredentials.credentialsParameter` (a Secrets Manager secret
| `MINISTACK_MSK_BOOTSTRAP_TLS` | _(unset)_ | TLS bootstrap string (`BootstrapBrokerStringTls`) |
| `MINISTACK_MSK_BOOTSTRAP_SASL_SCRAM` | _(unset)_ | SASL/SCRAM bootstrap string (`BootstrapBrokerStringSaslScram`) |
| `MINISTACK_MSK_BOOTSTRAP_SASL_IAM` | _(unset)_ | SASL/IAM bootstrap string (`BootstrapBrokerStringSaslIam`) |
-| `APPCONFIG_DEPLOYMENT_MINUTE_SECONDS` | `0` | Real seconds that stand in for one minute of an AppConfig deployment strategy's `DeploymentDurationInMinutes` and `FinalBakeTimeInMinutes`. `0` completes every deployment as it starts; `60` runs at AWS's pace; `1` runs a 30-minute strategy in 30 seconds. Also settable without a restart by posting `{"appconfig._DEPLOYMENT_MINUTE_SECONDS": 1}` to `/_ministack/config` |
| `TRANSLATE_JOB_RUN_SECONDS` | `2` | Wall-clock time a Translate batch job spends between `SUBMITTED` and `COMPLETED`. Set `0` to complete immediately, or raise it when a test needs to observe `IN_PROGRESS` or stop a running job. Also settable without a restart by posting `{"translate._JOB_RUN_SECONDS": 10}` to `/_ministack/config` |
### API Gateway HTTP proxy execution model
diff --git a/ministack/app.py b/ministack/app.py
index d951c8b4..538b16bb 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -1367,7 +1367,6 @@ async def _handle_admin_config_request(path: str, method: str, body: bytes):
"stepfunctions._SFN_WAIT_SCALE",
"translate._JOB_RUN_SECONDS",
"transcribe._JOB_RUN_SECONDS",
- "appconfig._DEPLOYMENT_MINUTE_SECONDS",
"lambda_svc.LAMBDA_EXECUTOR",
"cloudtrail._recording_enabled",
"alb.TARGET_CONNECT_TIMEOUT",
@@ -1393,7 +1392,6 @@ async def _handle_admin_config_request(path: str, method: str, body: bytes):
"stepfunctions._SFN_WAIT_SCALE",
"translate._JOB_RUN_SECONDS",
"transcribe._JOB_RUN_SECONDS",
- "appconfig._DEPLOYMENT_MINUTE_SECONDS",
):
try:
float_value = float(value)
@@ -2530,12 +2528,6 @@ async def _dispatch_service_request(
service_context = logs_service_context(
iam_action.split(":", 1)[1], body, resource_arn, region, get_account_id()
)
- denied = enforce(
- access_key, iam_action, service, region,
- resource_arn=resource_arn, service_context=service_context,
- )
- if service == "logs" and logs_validation_error is not None and not isinstance(denied, AuthError):
- return logs_validation_error
# A DynamoDB transaction is not itself an IAM action: each item is
# authorized as the single-item action it performs, on its table.
transaction_checks = (
@@ -2559,6 +2551,9 @@ async def _dispatch_service_request(
access_key, iam_action, service, region,
resource_arn=resource_arn, service_context=service_context,
)
+ # A malformed Logs tagging ARN fails validation ahead of a policy denial.
+ if service == "logs" and logs_validation_error is not None and not isinstance(denied, AuthError):
+ return logs_validation_error
# A copy also reads its source, a batch delete is one check per
# key, an attributes call is a pair, a governance bypass its own action.
if service == "s3" and not denied:
diff --git a/ministack/core/container_reaper.py b/ministack/core/container_reaper.py
index 08334368..2b9981f6 100644
--- a/ministack/core/container_reaper.py
+++ b/ministack/core/container_reaper.py
@@ -109,6 +109,17 @@ def _live_ids() -> tuple[set, set]:
return live, known
+def _labels(container) -> dict:
+ """Labels of a listed container; a sparse listing carries them top-level."""
+ attrs = getattr(container, "attrs", None) or {}
+ if "Labels" in attrs:
+ return attrs.get("Labels") or {}
+ try:
+ return container.labels or {}
+ except Exception:
+ return {}
+
+
def reap_abandoned(docker_client) -> int:
"""Remove abandoned containers. Returns how many were reclaimed."""
if docker_client is None:
@@ -121,16 +132,18 @@ def reap_abandoned(docker_client) -> int:
# containers are not merely skipped later — they are never listed, so no
# amount of downstream logic can reclaim them. Containers predating the
# labels are likewise invisible here; the boot sweep still gets them.
- containers = docker_client.containers.list(all=True, filters={"label": [
+ # Sparse: a full listing inspects every container and fails whole on one bad inspect.
+ containers = docker_client.containers.list(all=True, sparse=True, filters={"label": [
f"{INSTANCE_LABEL}={instance_id()}",
f"{BOOT_LABEL}={_boot_nonce}",
]})
except Exception as exc:
- logger.debug("reaper: listing containers failed: %s", exc)
+ logger.warning("reaper: listing containers failed: %s", exc)
return 0
for c in containers:
try:
+ c.reload() # this container's state; a failure skips only it
label = (c.labels or {}).get("ministack", "")
status = c.status
if status not in ("created", "dead", "exited"):
@@ -235,9 +248,10 @@ def reap_all(docker_client, stop_timeout: int = 2, include_unlabelled: bool = Fa
def _collect(selector, accept):
try:
- found = docker_client.containers.list(all=True, filters={"label": selector})
+ # Sparse: one container whose inspect fails must not cost the whole sweep.
+ found = docker_client.containers.list(all=True, sparse=True, filters={"label": selector})
except Exception as exc:
- logger.debug("reap_all: listing %s failed: %s", selector, exc)
+ logger.warning("reap_all: listing %s failed: %s", selector, exc)
return
for c in found:
if c.id in seen or not accept(c):
@@ -250,7 +264,7 @@ def reap_all(docker_client, stop_timeout: int = 2, include_unlabelled: bool = Fa
for service_label in SERVICE_LABELS:
# Only ownerless leftovers. A container carrying someone else's
# instance label is off limits however it was found.
- _collect([service_label], lambda c: not (c.labels or {}).get(INSTANCE_LABEL))
+ _collect([service_label], lambda c: not _labels(c).get(INSTANCE_LABEL))
return drop_containers(targets, stop_timeout=stop_timeout)
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index 1c2120b4..07b7ade7 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -12,7 +12,7 @@ import json
import logging
import os
import re
-from urllib.parse import unquote
+from urllib.parse import quote, unquote
from defusedxml.ElementTree import ParseError, fromstring
@@ -1556,6 +1556,9 @@ def extract_resource_arn(service: str, method: str, path: str,
# AWS ignores trailing slashes when authorizing management resources,
# as our control-plane handlers do when resolving the target resource.
resource_path = unquote(path[3:] if path.startswith("/v2/") else path).rstrip("/")
+ if resource_path.startswith("/tags/"):
+ # Tags: ::/tags/{url-encoded-resource-arn} (API Gateway ARN reference).
+ resource_path = "/tags/" + quote(resource_path[len("/tags/"):], safe="")
return f"arn:aws:apigateway:{region}::{resource_path}"
# --- Bedrock (REST path-based, multiple sub-services) ---
@@ -1673,6 +1676,13 @@ def eventbridge_resource_arns(body: bytes, region: str, account_id: str) -> list
return arns
+def _dynamodb_table_arn(table: str, region: str, account_id: str) -> str:
+ """TableName also accepts the table's ARN."""
+ if table.startswith("arn:"):
+ return table
+ return f"arn:aws:dynamodb:{region}:{account_id}:table/{table}"
+
+
def dynamodb_resource_arns(body: bytes, region: str, account_id: str) -> list[str]:
"""Return every table ARN addressed by a DynamoDB JSON request."""
try:
@@ -1683,14 +1693,12 @@ def dynamodb_resource_arns(body: bytes, region: str, account_id: str) -> list[st
if isinstance(table, str) and table:
index = data.get("IndexName")
suffix = f"/index/{index}" if isinstance(index, str) and index else ""
- return [
- f"arn:aws:dynamodb:{region}:{account_id}:table/{table}{suffix}"
- ]
+ return [_dynamodb_table_arn(table, region, account_id) + suffix]
else:
request_items = data.get("RequestItems") if isinstance(data, dict) else None
tables = list(request_items) if isinstance(request_items, dict) else []
return [
- f"arn:aws:dynamodb:{region}:{account_id}:table/{name}"
+ _dynamodb_table_arn(name, region, account_id)
for name in tables
if isinstance(name, str) and name
]
@@ -1776,7 +1784,7 @@ def dynamodb_transaction_checks(
detail = item.get(member)
table = detail.get("TableName") if isinstance(detail, dict) else None
if isinstance(table, str) and table:
- checks.append((action, f"arn:aws:dynamodb:{region}:{account_id}:table/{table}"))
+ checks.append((action, _dynamodb_table_arn(table, region, account_id)))
return checks
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 49450e33..600f7cad 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -3023,13 +3023,11 @@ def _render_request_template_v1(template: str, body_str: str,
return "".join(out)
-def _select_service_integration_response(integration, backend_status: int,
- backend_text: str):
+def _select_service_integration_response(integration, backend_status: int):
"""Pick the integration response for a non-proxy service call.
- ``selectionPattern`` entries match on the backend HTTP status
- (``fullmatch`` on the numeric code) or on the backend body (``search``);
- the entry with no pattern is the default and takes whatever remains.
+ For AWS back ends other than Lambda, ``selectionPattern`` matches the HTTP
+ status code; the entry with no pattern is the default.
"""
responses = integration.get("integrationResponses") or {}
for resp in responses.values():
@@ -3037,8 +3035,7 @@ def _select_service_integration_response(integration, backend_status: int,
if not pattern:
continue
try:
- if (re.fullmatch(pattern, str(backend_status))
- or re.search(pattern, backend_text)):
+ if re.fullmatch(pattern, str(backend_status)):
return resp
except re.error:
continue
@@ -3049,15 +3046,11 @@ def _select_service_integration_response(integration, backend_status: int,
def _service_integration_response(integration, backend_status: int,
- backend_ct: str, backend_text: str,
- accept: str):
+ backend_text: str, accept: str,
+ request_params: dict):
"""Map a backend service result through the integration responses."""
- responses = integration.get("integrationResponses") or {}
- if not responses:
- # No integration responses configured: pass the backend reply through.
- return backend_status, {"Content-Type": backend_ct}, backend_text.encode()
- selected = _select_service_integration_response(
- integration, backend_status, backend_text)
+ # No match and no default answers 500, configured responses or not.
+ selected = _select_service_integration_response(integration, backend_status)
if selected is None:
return (500, {"Content-Type": "application/json"},
json.dumps({"message": "Internal server error"}).encode())
@@ -3079,9 +3072,7 @@ def _service_integration_response(integration, backend_status: int,
if template is None and templates:
template = next(iter(templates.values()))
if template is not None:
- body_out = _render_request_template_v1(
- template, backend_text,
- {k: v for k, v in resp_headers.items()})
+ body_out = _render_request_template_v1(template, backend_text, request_params)
return status, resp_headers, body_out.encode()
return status, resp_headers, backend_text.encode()
@@ -3163,8 +3154,7 @@ async def _invoke_sqs_v1(
"MissingAction", "Missing Action parameter", 400)
backend_text = xbody.decode("utf-8", errors="replace")
return _service_integration_response(
- integration, backend_status, "application/xml", backend_text,
- accept)
+ integration, backend_status, backend_text, accept, params_map)
qurl = (_sqs_svc._queue_name_to_url.get_scoped(account, region, queue_name)
or _sqs_svc._queue_url_for_account(account, queue_name))
@@ -3173,18 +3163,31 @@ async def _invoke_sqs_v1(
try:
with request_scope(account, region):
result = await _sqs_svc._dispatch(action, data, qurl)
- backend_status, _h, xbody = _sqs_svc._to_xml(action, result)
- backend_ct = "application/xml"
+ if action == "SendMessage":
+ # API Gateway receives SQS's Query reply as JSON.
+ backend_status = 200
+ backend_text = json.dumps({"SendMessageResponse": {
+ "ResponseMetadata": {"RequestId": new_uuid()},
+ "SendMessageResult": {
+ "MD5OfMessageAttributes": result.get("MD5OfMessageAttributes"),
+ "MD5OfMessageBody": result.get("MD5OfMessageBody"),
+ "MD5OfMessageSystemAttributes": result.get("MD5OfMessageSystemAttributes"),
+ "MessageId": result.get("MessageId"),
+ "SequenceNumber": result.get("SequenceNumber"),
+ },
+ }})
+ else:
+ backend_status, _h, xbody = _sqs_svc._to_xml(action, result)
+ backend_text = xbody.decode("utf-8", errors="replace")
except _sqs_svc._Err as e:
backend_status, _h, xbody = _sqs_svc._xml_err_resp(
e.code, e.message, e.status)
- backend_ct = "application/xml"
+ backend_text = xbody.decode("utf-8", errors="replace")
except Exception:
return (504, {"Content-Type": "application/json"},
json.dumps({"message": "Internal server error"}).encode())
return _service_integration_response(
- integration, backend_status, backend_ct,
- xbody.decode("utf-8", errors="replace"), accept)
+ integration, backend_status, backend_text, accept, params_map)
async def _invoke_http_proxy_v1(integration, path, method, headers, body, query_params, path_params=None):
diff --git a/ministack/services/appconfig.py b/ministack/services/appconfig.py
index af8605c9..b8d915ed 100644
--- a/ministack/services/appconfig.py
+++ b/ministack/services/appconfig.py
@@ -43,11 +43,8 @@ logger = logging.getLogger("appconfig")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
-# APPCONFIG_DEPLOYMENT_MINUTE_SECONDS: real seconds that stand in for one minute of a
-# deployment strategy's DeploymentDurationInMinutes and FinalBakeTimeInMinutes. 0 (the
-# default) runs every deployment to COMPLETE as it starts; 60 keeps AWS's pace. Also
-# settable at runtime through /_ministack/config, so a test can pin the pace.
-_DEPLOYMENT_MINUTE_SECONDS = float(os.environ.get("APPCONFIG_DEPLOYMENT_MINUTE_SECONDS", "0"))
+# A strategy minute is a real minute, as on AWS.
+_DEPLOYMENT_MINUTE_SECONDS = 60.0
# Next-Poll-Interval-In-Seconds for a session that set no RequiredMinimumPollIntervalInSeconds.
_DEFAULT_POLL_INTERVAL_SECONDS = 30
@@ -830,7 +827,8 @@ def _stop_deployment(app_id, env_id, deploy_num, allow_revert=False):
return _error(404, "ResourceNotFoundException", f"Deployment {deploy_num} not found")
now = time.time()
state = record["State"]
- if state in _IN_PROGRESS_STATES:
+ # Only DEPLOYING stops without AllowRevert; with it, BAKING rolls back too.
+ if state == "DEPLOYING" or (state == "BAKING" and allow_revert):
_roll_back(record, "USER", get_account_id(), now)
elif state == "COMPLETE" and allow_revert:
completed = record.get("_CompletedEpoch")
diff --git a/ministack/services/ses.py b/ministack/services/ses.py
index 7724398f..2eace3d1 100644
--- a/ministack/services/ses.py
+++ b/ministack/services/ses.py
@@ -365,14 +365,7 @@ def _receipt_rule_error(rule):
if len(action) != 1:
return _receipt_error("InvalidParameterValue", (
"Exactly one action type must be specified for each ReceiptAction"))
- action_type = next(iter(action))
- if action_type not in ("AddHeaderAction", "StopAction"):
- return _receipt_error("InvalidAction", (
- f"Receipt action {action_type} is not implemented"))
if "StopAction" in action:
- if "TopicArn" in action["StopAction"]:
- return _receipt_error("InvalidAction", (
- "Receipt action StopAction with TopicArn is not implemented"))
if action["StopAction"].get("Scope") != "RuleSet":
return _receipt_error("ValidationError", (
f"1 validation error detected: Value at 'rule.actions.{i}.member.stopAction.scope' "
@@ -1099,24 +1092,28 @@ def _message_rejection(sender, recipients=()) -> str | None:
f"in region {get_region().upper()}: {', '.join(failed)}")
-# Mailbox simulator: local part -> notification type. success@ and ooto@ are
-# delivered; bounce@ is a hard bounce; complaint@ is reported as spam.
-_SIMULATOR_OUTCOMES = {"bounce": "Bounce", "complaint": "Complaint"}
+# Mailbox simulator local part -> (notificationType, bounceSubType) it produces;
+# any other address (success@, ooto@) is delivered.
+_SIMULATOR_OUTCOMES = {
+ "bounce": (("Bounce", "General"),),
+ "suppressionlist": (("Bounce", "Suppressed"),),
+ # Accepted and delivered, then marked as spam.
+ "complaint": (("Delivery", None), ("Complaint", None)),
+}
-def _notification_identity(source: str) -> dict | None:
- """The identity whose notification topics apply to a sender: the address
- identity if verified, else the nearest verified parent domain."""
+def _notification_identity(source: str) -> tuple[str, dict] | None:
+ """The (name, record) of the identity whose notification topics apply to a
+ sender: the address identity if verified, else the nearest verified parent domain."""
addr = parseaddr(source or "")[1]
if not addr:
return None
if addr in _identities:
- return _identities[addr]
- domains = {k.lower(): r for k, r in _identities.items() if "@" not in k}
+ return addr, _identities[addr]
+ domains = {k.lower(): (k, r) for k, r in _identities.items() if "@" not in k}
for d in _domain_and_parents(addr.rpartition("@")[2].lower()):
- rec = domains.get(d)
- if rec is not None:
- return rec
+ if d in domains:
+ return domains[d]
return None
@@ -1130,12 +1127,18 @@ def _publish_notification(topic_arn: str, payload: dict) -> None:
logger.warning("SES notification publish to %s failed", topic_arn, exc_info=True)
-def _notification_detail(kind: str, rcpt: str, ts: str) -> dict:
+def _notification_detail(kind: str, rcpt: str, ts: str, bounce_subtype: str | None = None) -> dict:
if kind == "Delivery":
return {"delivery": {
"timestamp": ts, "processingTimeMillis": 0, "recipients": [rcpt],
"smtpResponse": "250 2.6.0 Message received",
"reportingMTA": "a0-0.smtp-out.amazonses.com"}}
+ if kind == "Bounce" and bounce_subtype == "Suppressed":
+ # SES suppressed the send, so no remote MTA returned a DSN.
+ return {"bounce": {
+ "bounceType": "Permanent", "bounceSubType": "Suppressed",
+ "bouncedRecipients": [{"emailAddress": rcpt}],
+ "timestamp": ts, "feedbackId": new_uuid()}}
if kind == "Bounce":
return {"bounce": {
"bounceType": "Permanent", "bounceSubType": "General",
@@ -1154,9 +1157,10 @@ def _notification_detail(kind: str, rcpt: str, ts: str) -> dict:
def _send_notifications(msg_id, source, recipients):
"""Publish the Delivery / Bounce / Complaint notification of each recipient
to the SNS topic set on the sender's identity (SetIdentityNotificationTopic)."""
- identity = _notification_identity(source)
- if not identity:
+ found = _notification_identity(source)
+ if not found:
return
+ identity_name, identity = found
topics = identity.get("NotificationTopics", {})
if not any(topics.values()):
return
@@ -1165,25 +1169,24 @@ def _send_notifications(msg_id, source, recipients):
ts = now.strftime("%Y-%m-%dT%H:%M:%S.") + f"{now.microsecond // 1000:03d}Z"
mail = {
"timestamp": ts,
- "source": source,
+ # The envelope MAIL FROM address and the identity used to send.
+ "source": parseaddr(source)[1],
+ "sourceArn": f"arn:aws:ses:{get_region()}:{get_account_id()}:identity/{identity_name}",
"sendingAccountId": get_account_id(),
"messageId": msg_id,
"destination": recipients,
}
- src_addr = parseaddr(source or "")[1]
- if src_addr:
- mail["sourceArn"] = (f"arn:aws:ses:{get_region()}:{get_account_id()}:"
- f"identity/{src_addr}")
for rcpt in recipients:
local, _, domain = rcpt.partition("@")
- kind = "Delivery"
+ outcomes = (("Delivery", None),)
if domain.lower() == _SIMULATOR_DOMAIN:
- kind = _SIMULATOR_OUTCOMES.get(local.lower().split("+")[0], "Delivery")
- topic = topics.get(kind)
- if not topic:
- continue
- detail = _notification_detail(kind, rcpt, ts)
- _publish_notification(topic, {"notificationType": kind, "mail": mail, **detail})
+ outcomes = _SIMULATOR_OUTCOMES.get(local.lower().split("+")[0], outcomes)
+ for kind, bounce_subtype in outcomes:
+ topic = topics.get(kind)
+ if not topic:
+ continue
+ detail = _notification_detail(kind, rcpt, ts, bounce_subtype)
+ _publish_notification(topic, {"notificationType": kind, "mail": mail, **detail})
def _make_identity(identity, identity_type):
diff --git a/ministack/services/ses_v2.py b/ministack/services/ses_v2.py
index f5004d03..30681aa7 100644
--- a/ministack/services/ses_v2.py
+++ b/ministack/services/ses_v2.py
@@ -294,12 +294,13 @@ def _local_ses_v2_resource_arn(arn):
return None, _invalid_resource_arn(arn)
if (
- spec.service != "ses"
+ spec.partition != "aws"
+ or spec.service != "ses"
or spec.account_id != get_account_id()
or spec.region != get_region()
):
return None, _invalid_resource_arn(arn)
- canonical = f"arn:aws:{spec.service}:{spec.region}:{spec.account_id}:{spec.resource}"
+ canonical = str(spec)
kind, sep, name = spec.resource.partition("/")
if sep != "/" or not name or ("/" in name and kind != "tenant"):
@@ -335,6 +336,12 @@ def _local_ses_v2_resource_arn(arn):
return canonical, None
+# The ResourceType enum of a tenant's associated resources, by ARN resource kind.
+_TENANT_RESOURCE_TYPES = {
+ "identity": "EMAIL_IDENTITY", "configuration-set": "CONFIGURATION_SET", "template": "EMAIL_TEMPLATE",
+}
+
+
def _missing_tenant(name):
return _json_err("NotFoundException", f"The requested tenant <{name}> does not exist.", 404)
@@ -508,7 +515,7 @@ def _tenant_request(method, sub, data):
"TenantName": name,
"TenantId": tenant_id,
"TenantArn": arn,
- "CreatedTimestamp": time.time(),
+ "CreatedTimestamp": int(time.time()),
"Tags": copy.deepcopy(data.get("Tags", [])),
"SendingStatus": "ENABLED",
}
@@ -561,7 +568,8 @@ def _tenant_request(method, sub, data):
return json_response({})
resources = _tenant_resources[name]
if sub == "/tenants/resources/list":
- items = [{"ResourceType": parse_arn(arn).resource.split("/")[0], "ResourceArn": arn} for arn in resources]
+ items = [{"ResourceType": _TENANT_RESOURCE_TYPES[parse_arn(arn).resource.split("/")[0]], "ResourceArn": arn}
+ for arn in resources]
filters = data.get("Filter") or {}
if filters.keys() - {"RESOURCE_TYPE"}:
return _json_err(
@@ -569,7 +577,7 @@ def _tenant_request(method, sub, data):
"1 validation error detected: Value at 'filter' failed to satisfy constraint: Map keys must satisfy constraint: [Member must satisfy enum value set: [RESOURCE_TYPE]]",
)
resource_type = filters.get("RESOURCE_TYPE")
- if resource_type is not None and resource_type not in ("configuration-set", "identity", "template"):
+ if resource_type is not None and resource_type not in _TENANT_RESOURCE_TYPES.values():
return _json_err("BadRequestException", f"Invalid resource type {resource_type} specified.")
items = sorted(
(
@@ -592,7 +600,7 @@ def _tenant_request(method, sub, data):
return _json_err(
"AlreadyExistsException", f"Resources {arn} has already been associated with tenant {name}"
)
- resources[canonical] = time.time()
+ resources[canonical] = int(time.time())
return json_response({})
diff --git a/tests/conftest.py b/tests/conftest.py
index ac9d0d80..e4a4c2be 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -875,7 +875,7 @@ class _FakeContainers:
return c
raise RuntimeError(f"no such container: {key}")
- def list(self, all=False, filters=None):
+ def list(self, all=False, filters=None, sparse=False):
want = (filters or {}).get("label") or []
want = [want] if isinstance(want, str) else want
out = []
diff --git a/tests/test_apigateway_iam.py b/tests/test_apigateway_iam.py
deleted file mode 100644
index 26fdf6c7..00000000
--- a/tests/test_apigateway_iam.py
+++ /dev/null
@@ -1,103 +0,0 @@
-# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
-# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).
-"""API Gateway management authorization through request dispatch and IAM policies."""
-
-import asyncio
-import json
-
-import pytest
-
-from ministack.core.iam_actions import extract_iam_action, extract_resource_arn
-from ministack.core.iam_evaluator import EvalContext, evaluate, parse_policy_document
-
-
[email protected]("path", ["/restapis/api/stages/prod", "/v2/apis/api/stages/prod"])
[email protected]("method", ["GET", "POST", "PUT", "PATCH", "DELETE"])
-def test_management_actions_use_http_verbs(path, method):
- # Neither query-protocol parameters nor JSON-protocol headers may override
- # the action of this REST-only service.
- assert extract_iam_action(
- "apigateway", method, path,
- {"x-amz-target": "ApiGateway.GetStage"}, b"", {"Action": "GetStage"},
- ) == f"apigateway:{method}"
-
-
[email protected]("path, resource", [
- ("/restapis", "/restapis"),
- ("/restapis/api", "/restapis/api"),
- ("/restapis/api/stages", "/restapis/api/stages"),
- ("/restapis/api/stages/prod", "/restapis/api/stages/prod"),
- ("/restapis/api/stages/prod/", "/restapis/api/stages/prod"),
- ("/restapis/api/stages/", "/restapis/api/stages"),
- ("/restapis/api/resources/root/methods/GET/integration", "/restapis/api/resources/root/methods/GET/integration"),
- ("/v2/apis", "/apis"),
- ("/v2/apis/api", "/apis/api"),
- ("/v2/apis/api/stages", "/apis/api/stages"),
- ("/v2/apis/api/stages/", "/apis/api/stages"),
- ("/v2/apis/api/stages/prod/", "/apis/api/stages/prod"),
- ("/v2/apis/api/stages/%24default", "/apis/api/stages/$default"),
- ("/v2/apis/api/stages/%24default/", "/apis/api/stages/$default"),
- ("/v2/apis/api/routes/route", "/apis/api/routes/route"),
- ("/domainnames/example.com/basepathmappings", "/domainnames/example.com/basepathmappings"),
- ("/v2/domainnames/example.com/apimappings", "/domainnames/example.com/apimappings"),
- ("/account", "/account"),
-])
-def test_management_resource_preserves_path(path, resource):
- assert extract_resource_arn(
- "apigateway", "GET", path, {}, b"", {}, "us-east-2", "000000000000",
- ) == f"arn:aws:apigateway:us-east-2::{resource}"
-
-
[email protected]("prefix", ["/restapis/api", "/v2/apis/api"])
[email protected]("suffix", ["", "/"])
[email protected]("case, method, stage, expected", [
- ("stage-grant", "GET", "prod", 200),
- ("stage-grant", "PATCH", "prod", 200),
- ("stage-grant", "GET", "dev", 403),
- ("parent-grant", "GET", "prod", 403),
- ("operation-grant", "GET", "prod", 403),
- ("stage-deny", "GET", "prod", 403),
- ("stage-deny", "GET", "dev", 200),
-])
-def test_stage_policy_is_enforced_on_dispatch(monkeypatch, prefix, suffix, case, method, stage, expected):
- import ministack.app as app
- from ministack.core import iam_evaluator
-
- parent = f"arn:aws:apigateway:us-east-2::{prefix.removeprefix('/v2')}"
- grants = {
- "stage-grant": [{"Effect": "Allow", "Action": ["apigateway:GET", "apigateway:PATCH"],
- "Resource": f"{parent}/stages/prod"}],
- "parent-grant": [{"Effect": "Allow", "Action": "apigateway:GET", "Resource": parent}],
- "operation-grant": [{"Effect": "Allow", "Action": "apigateway:GetStage", "Resource": "*"}],
- "stage-deny": [
- {"Effect": "Allow", "Action": "apigateway:*", "Resource": f"{parent}/*"},
- {"Effect": "Deny", "Action": "apigateway:GET", "Resource": f"{parent}/stages/prod"},
- ],
- }
- statements = parse_policy_document({"Statement": grants[case]})
- dispatched = []
-
- def enforce_policy(access_key, action, service, region, resource_arn="*", service_context=None):
- result = evaluate(EvalContext(
- principal_arn="arn:aws:iam::000000000000:user/caller",
- principal_type="User", principal_account="000000000000",
- action=action, resource_arn=resource_arn, region=region,
- ), [statements])
- return None if result.decision == "Allow" else result
-
- async def handler(*args):
- dispatched.append(args)
- return 200, {}, b"{}"
-
- monkeypatch.setattr(app, "AUTH", True)
- monkeypatch.setattr(iam_evaluator, "enforce", enforce_policy)
- monkeypatch.setattr(iam_evaluator, "pin_request_caller", lambda *args: None)
- monkeypatch.setitem(app.SERVICE_HANDLERS, "apigateway", handler)
- headers = {"authorization": "AWS4-HMAC-SHA256 Credential=test/20261006/us-east-2/apigateway/aws4_request"}
- status, _, body = asyncio.run(app._dispatch_service_request(
- method, f"{prefix}/stages/{stage}{suffix}", headers, b"", {}, "request-stage",
- ))
- assert status == expected
- assert bool(dispatched) == (expected == 200)
- if expected == 403:
- assert f"apigateway:{method}" in json.loads(body)["message"]
diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.py
index 64980603..7eedb7df 100644
--- a/tests/test_apigatewayv1.py
+++ b/tests/test_apigatewayv1.py
@@ -5442,8 +5442,8 @@ def test_apigwv1_execute_sqs_integration_passthrough(apigw_v1, sqs):
def test_apigwv1_execute_sqs_integration_backend_errors_map(apigw_v1, sqs):
- """An SQS-side failure selects on selectionPattern against the backend
- error body; unmatched errors land on the default (patternless) response."""
+ """selectionPattern matches the backend status code; unmatched statuses
+ land on the default (patternless) response."""
missing = f"missing-q-{_uuid_mod.uuid4().hex[:8]}"
api_id = _sqs_api(
apigw_v1, missing,
@@ -5452,7 +5452,7 @@ def test_apigwv1_execute_sqs_integration_backend_errors_map(apigw_v1, sqs):
"Action=SendMessage&MessageBody=$util.urlEncode($input.body)"},
integration_responses={
"200": {"responseTemplates": {"application/json": '{"ok":true}'}},
- "502": {"selectionPattern": ".*NonExistentQueue.*",
+ "502": {"selectionPattern": "400",
"responseTemplates": {"application/json": '{"ok":false}'}}})
try:
status, text = _stage_call(
@@ -5463,7 +5463,7 @@ def test_apigwv1_execute_sqs_integration_backend_errors_map(apigw_v1, sqs):
finally:
apigw_v1.delete_rest_api(restApiId=api_id)
- # No pattern matches a MissingAction: the default response absorbs it.
+ # No pattern matches the MissingAction 400: the default response absorbs it.
api_id = _sqs_api(
apigw_v1, missing,
request_templates={"application/json": "Action=&MessageBody=x"},
@@ -5477,3 +5477,40 @@ def test_apigwv1_execute_sqs_integration_backend_errors_map(apigw_v1, sqs):
assert json.loads(text) == {"ok": True}
finally:
apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_execute_sqs_integration_send_message_reply_is_json(apigw_v1, sqs):
+ """The SendMessage reply reaches the response template as SQS's JSON envelope."""
+ queue_name = f"apigw-q-{_uuid_mod.uuid4().hex[:8]}"
+ qurl = sqs.create_queue(QueueName=queue_name)["QueueUrl"]
+ api_id = _sqs_api(
+ apigw_v1, queue_name,
+ request_templates={"application/json": "Action=SendMessage&MessageBody=$util.urlEncode($input.body)"},
+ integration_responses={"200": {"responseTemplates": {
+ "application/json": "$input.path('$.SendMessageResponse.SendMessageResult.MessageId')"}}})
+ try:
+ status, text = _stage_call(api_id, "/send", method="POST", body='{"a":1}',
+ headers=[("Content-Type", "application/json")])
+ assert status == 200
+ msgs = sqs.receive_message(QueueUrl=qurl, WaitTimeSeconds=1)["Messages"]
+ assert text == msgs[0]["MessageId"]
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ sqs.delete_queue(QueueUrl=qurl)
+
+
+def test_apigwv1_execute_sqs_integration_without_integration_responses_is_500(apigw_v1, sqs):
+ """No integration response to map the reply: AWS answers 500 Internal server error."""
+ queue_name = f"apigw-q-{_uuid_mod.uuid4().hex[:8]}"
+ qurl = sqs.create_queue(QueueName=queue_name)["QueueUrl"]
+ api_id = _sqs_api(
+ apigw_v1, queue_name,
+ request_templates={"application/json": "Action=SendMessage&MessageBody=x"})
+ try:
+ status, text = _stage_call(api_id, "/send", method="POST", body="{}",
+ headers=[("Content-Type", "application/json")])
+ assert status == 500
+ assert json.loads(text) == {"message": "Internal server error"}
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ sqs.delete_queue(QueueUrl=qurl)
diff --git a/tests/test_appconfig.py b/tests/test_appconfig.py
index a75ec790..55f930cb 100644
--- a/tests/test_appconfig.py
+++ b/tests/test_appconfig.py
@@ -1,12 +1,16 @@
+import asyncio
import json
import os
+import time
import boto3
import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
+from ministack.core.responses import get_account_id
from ministack.services import appconfig as appconfig_service
+from ministack.services import cloudwatch as cloudwatch_service
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
@@ -1126,3 +1130,446 @@ def test_appconfig_feature_flags_without_values_are_served_verbatim(
appconfig_client, appconfigdata_client, "AWS.AppConfig.FeatureFlags",
document, "noval",
) == document
+
+
+# ---------------------------------------------------------------------------
+# Gradual rollout
+# ---------------------------------------------------------------------------
+
+MINUTE = 60.0
+START = 1_800_000_000.0
+
+
+def clock(monkeypatch):
+ now = [START]
+ monkeypatch.setattr(time, "time", lambda: now[0])
+ appconfig_service.reset()
+ cloudwatch_service.reset()
+ yield now
+ appconfig_service.reset()
+ cloudwatch_service.reset()
+
+
+def _appconfig(method, path, body=None, headers=None, query=None):
+ raw = json.dumps(body).encode() if isinstance(body, dict) else (body or b"")
+ status, resp_headers, resp_body = asyncio.run(appconfig_service.handle_request(
+ method, path, {k.lower(): v for k, v in (headers or {}).items()}, raw, query or {}))
+ return status, resp_headers, resp_body
+
+
+def _appconfig_json(method, path, body=None, headers=None):
+ status, _, resp_body = _appconfig(method, path, body, headers)
+ return status, json.loads(resp_body) if resp_body else {}
+
+
+def _cloudwatch(action, body):
+ headers = {"x-amz-target": f"GraniteServiceVersion20100801.{action}",
+ "content-type": "application/x-amz-json-1.0"}
+ status, _, _ = asyncio.run(cloudwatch_service.handle_request(
+ "POST", "/", headers, json.dumps(body).encode(), {}))
+ assert status == 200
+
+
+def _alarm(name):
+ _cloudwatch("PutMetricAlarm", {
+ "AlarmName": name, "Namespace": "Orders", "MetricName": "Errors",
+ "Statistic": "Sum", "Period": 60, "EvaluationPeriods": 1,
+ "Threshold": 1.0, "ComparisonOperator": "GreaterThanOrEqualToThreshold",
+ })
+ return f"arn:aws:cloudwatch:us-east-1:{get_account_id()}:alarm:{name}"
+
+
+def _set_alarm(name, state):
+ _cloudwatch("SetAlarmState", {"AlarmName": name, "StateValue": state, "StateReason": "test"})
+
+
+class Target:
+ """An application, environment and hosted profile holding versions 1 and 2."""
+
+ def __init__(self, monitors=None):
+ _, app = _appconfig_json("POST", "/applications", {"Name": "orders"})
+ _, env = _appconfig_json("POST", f"/applications/{app['Id']}/environments",
+ {"Name": "prod", "Monitors": monitors or []})
+ _, profile = _appconfig_json("POST", f"/applications/{app['Id']}/configurationprofiles",
+ {"Name": "settings", "LocationUri": "hosted"})
+ self.app, self.env, self.profile = app["Id"], env["Id"], profile["Id"]
+ for version in (1, 2):
+ status, _, _ = _appconfig(
+ "POST",
+ f"/applications/{self.app}/configurationprofiles/{self.profile}/hostedconfigurationversions",
+ json.dumps({"version": version}).encode(),
+ {"Content-Type": "application/json", "VersionLabel": f"v{version}"},
+ )
+ assert status == 201
+
+ @property
+ def deployments_path(self):
+ return f"/applications/{self.app}/environments/{self.env}/deployments"
+
+ def deploy(self, version, strategy="AppConfig.Linear20PercentEvery6Minutes", **extra):
+ return _appconfig_json("POST", self.deployments_path, {
+ "DeploymentStrategyId": strategy, "ConfigurationProfileId": self.profile,
+ "ConfigurationVersion": str(version), **extra,
+ })
+
+ def deployment(self, number):
+ status, body = _appconfig_json("GET", f"{self.deployments_path}/{number}")
+ assert status == 200
+ return body
+
+ def stop(self, number, allow_revert=False):
+ headers = {"Allow-Revert": "true"} if allow_revert else {}
+ return _appconfig_json("DELETE", f"{self.deployments_path}/{number}", headers=headers)
+
+ def environment_state(self):
+ return _appconfig_json("GET", f"/applications/{self.app}/environments/{self.env}")[1]["State"]
+
+ def session(self, **extra):
+ status, body = _appconfig_json("POST", "/configurationsessions", {
+ "ApplicationIdentifier": self.app, "EnvironmentIdentifier": self.env,
+ "ConfigurationProfileIdentifier": self.profile, **extra,
+ })
+ assert status == 201
+ return Client(body["InitialConfigurationToken"])
+
+
+class Client:
+ """One configuration session, polling with the token it was last handed."""
+
+ def __init__(self, token):
+ self.session_id = token
+ self.token = token
+
+ def poll(self):
+ status, headers, body = _appconfig("GET", "/configuration", query={"configuration_token": self.token})
+ assert status == 200
+ self.token = headers["Next-Poll-Configuration-Token"]
+ return headers, json.loads(body) if body else None
+
+
+def _event_types(deployment):
+ return [event["EventType"] for event in deployment["EventLog"]]
+
+
+def test_rollout_steps_follow_the_growth_type():
+ assert appconfig_service._rollout_steps("LINEAR", 20.0) == [20.0, 40.0, 60.0, 80.0, 100.0]
+ assert appconfig_service._rollout_steps("LINEAR", 100.0) == [100.0]
+ # G*(2^N) from the CreateDeploymentStrategy docs.
+ assert appconfig_service._rollout_steps("EXPONENTIAL", 10.0) == [10.0, 20.0, 40.0, 80.0, 100.0]
+ assert appconfig_service._rollout_steps("EXPONENTIAL", 2.0) == [2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 100.0]
+ # Below the model's 1.0 minimum (stored unvalidated) still terminates.
+ assert appconfig_service._rollout_steps("LINEAR", -5.0)[-1] == 100.0
+
+
+def test_linear_deployment_steps_bakes_and_completes(clock):
+ target = Target()
+ status, deployment = target.deploy(1)
+ assert status == 201
+ assert deployment["State"] == "DEPLOYING"
+ assert deployment["PercentageComplete"] == 0.0
+ assert _event_types(deployment) == ["DEPLOYMENT_STARTED"]
+ assert target.environment_state() == "DEPLOYING"
+
+ # Linear20PercentEvery6Minutes: five 20% steps over 30 minutes, then a 30-minute bake.
+ clock[0] = START + 6 * MINUTE
+ assert target.deployment(1)["PercentageComplete"] == 20.0
+ clock[0] = START + 12 * MINUTE - 1
+ assert target.deployment(1)["PercentageComplete"] == 20.0
+ clock[0] = START + 12 * MINUTE
+ assert target.deployment(1)["PercentageComplete"] == 40.0
+
+ clock[0] = START + 30 * MINUTE
+ deployment = target.deployment(1)
+ assert (deployment["State"], deployment["PercentageComplete"]) == ("BAKING", 100.0)
+ assert target.environment_state() == "DEPLOYING"
+
+ clock[0] = START + 60 * MINUTE
+ deployment = target.deployment(1)
+ assert deployment["State"] == "COMPLETE"
+ assert deployment["CompletedAt"] == appconfig_service._iso(START + 60 * MINUTE)
+ assert target.environment_state() == "READY_FOR_DEPLOYMENT"
+ # Most recent first.
+ assert _event_types(deployment) == [
+ "DEPLOYMENT_COMPLETED", "BAKE_TIME_STARTED",
+ *["PERCENTAGE_UPDATED"] * 5,
+ "DEPLOYMENT_STARTED",
+ ]
+ first_step = deployment["EventLog"][-2]
+ assert first_step["OccurredAt"] == appconfig_service._iso(START + 6 * MINUTE)
+ assert first_step["TriggeredBy"] == "APPCONFIG"
+
+
+def test_list_deployments_reports_rollout_progress(clock):
+ target = Target()
+ target.deploy(1, strategy="AppConfig.Canary10Percent20Minutes")
+ clock[0] = START + 4 * MINUTE
+ status, body = _appconfig_json("GET", target.deployments_path)
+ assert status == 200
+ [summary] = body["Items"]
+ assert (summary["State"], summary["PercentageComplete"]) == ("DEPLOYING", 10.0)
+ assert summary["VersionLabel"] == "v1"
+ assert "CompletedAt" not in summary
+
+
+def test_start_deployment_conflicts_with_one_in_progress(clock):
+ target = Target()
+ target.deploy(1)
+ status, body = target.deploy(2)
+ assert status == 409
+ assert body["__type"] == "ConflictException"
+
+ # Still in progress while baking.
+ clock[0] = START + 30 * MINUTE
+ assert target.deploy(2)[0] == 409
+
+ clock[0] = START + 60 * MINUTE
+ status, body = target.deploy(2)
+ assert status == 201
+ assert body["DeploymentNumber"] == 2
+
+
+def test_start_deployment_checks_latest_deployment_number(clock):
+ target = Target()
+ assert target.deploy(1, strategy="AppConfig.AllAtOnce", LatestDeploymentNumber=0)[0] == 201
+ clock[0] = START + 10 * MINUTE
+ status, body = target.deploy(2, strategy="AppConfig.AllAtOnce", LatestDeploymentNumber=0)
+ assert status == 409
+ assert body["__type"] == "ConflictException"
+ assert target.deploy(2, strategy="AppConfig.AllAtOnce", LatestDeploymentNumber=1)[0] == 201
+
+
+def test_stop_rolls_back_an_in_progress_deployment(clock):
+ target = Target()
+ target.deploy(1, strategy="AppConfig.AllAtOnce")
+ clock[0] = START + 10 * MINUTE
+ client = target.session()
+ assert client.poll()[1] == {"version": 1}
+
+ target.deploy(2)
+ clock[0] = START + 40 * MINUTE # 100%, baking
+ assert client.poll()[1] == {"version": 2}
+
+ # Baking stops only with AllowRevert ("works only on deployments that have a status of DEPLOYING").
+ assert target.stop(2)[0] == 400
+ status, deployment = target.stop(2, allow_revert=True)
+ assert status == 202
+ assert deployment["State"] == "ROLLED_BACK"
+ assert _event_types(deployment)[:2] == ["ROLLBACK_COMPLETED", "ROLLBACK_STARTED"]
+ assert deployment["EventLog"][0]["TriggeredBy"] == "USER"
+ assert target.environment_state() == "ROLLED_BACK"
+ assert client.poll()[1] == {"version": 1}
+
+ # A stopped deployment cannot be stopped again, and the environment takes a new one.
+ assert target.stop(2)[0] == 400
+ assert target.deploy(2)[0] == 201
+
+
+def test_revert_requires_allow_revert_and_the_72_hour_window(clock):
+ target = Target()
+ target.deploy(1, strategy="AppConfig.AllAtOnce")
+ clock[0] = START + 10 * MINUTE
+ target.deploy(2, strategy="AppConfig.AllAtOnce")
+ clock[0] = START + 20 * MINUTE
+ assert target.deployment(2)["State"] == "COMPLETE"
+
+ status, body = target.stop(2)
+ assert status == 400
+ assert body["__type"] == "BadRequestException"
+
+ clock[0] = START + 20 * MINUTE + 72 * 3600 + 1
+ assert target.stop(2, allow_revert=True)[0] == 400
+
+ clock[0] = START + 20 * MINUTE + 72 * 3600
+ status, deployment = target.stop(2, allow_revert=True)
+ assert status == 202
+ assert deployment["State"] == "REVERTED"
+ assert target.environment_state() == "REVERTED"
+ assert target.session().poll()[1] == {"version": 1}
+
+
+def test_monitor_alarm_rolls_back_at_the_moment_it_fires(clock):
+ alarm_arn = _alarm("orders-errors")
+ target = Target(monitors=[{"AlarmArn": alarm_arn}])
+ target.deploy(1, strategy="AppConfig.AllAtOnce")
+ clock[0] = START + 10 * MINUTE
+ target.deploy(2)
+ deploy_start = clock[0]
+
+ clock[0] = deploy_start + 7 * MINUTE
+ _cloudwatch("PutMetricData", {"Namespace": "Orders", "MetricData": [{"MetricName": "Errors", "Value": 5}]})
+ clock[0] = deploy_start + 20 * MINUTE
+
+ deployment = target.deployment(2)
+ assert deployment["State"] == "ROLLED_BACK"
+ assert deployment["PercentageComplete"] == 20.0 # the 12-minute step never came
+ rollback_started = deployment["EventLog"][1]
+ assert rollback_started["EventType"] == "ROLLBACK_STARTED"
+ assert rollback_started["TriggeredBy"] == "CLOUDWATCH_ALARM"
+ assert alarm_arn in rollback_started["Description"]
+ assert rollback_started["OccurredAt"] == appconfig_service._iso(deploy_start + 7 * MINUTE)
+ assert target.environment_state() == "ROLLED_BACK"
+ assert target.session().poll()[1] == {"version": 1}
+
+
+def test_alarm_that_recovers_during_the_bake_still_rolls_back(clock):
+ target = Target(monitors=[{"AlarmArn": _alarm("orders-errors")}])
+ target.deploy(1)
+ clock[0] = START + 35 * MINUTE
+ _set_alarm("orders-errors", "ALARM")
+ clock[0] = START + 36 * MINUTE
+ _set_alarm("orders-errors", "OK")
+
+ clock[0] = START + 90 * MINUTE
+ deployment = target.deployment(1)
+ assert deployment["State"] == "ROLLED_BACK"
+ assert deployment["PercentageComplete"] == 100.0
+ assert "BAKE_TIME_STARTED" in _event_types(deployment)
+
+
+def test_alarm_after_completion_does_not_roll_back(clock):
+ target = Target(monitors=[{"AlarmArn": _alarm("orders-errors")}])
+ target.deploy(1)
+ clock[0] = START + 61 * MINUTE
+ _set_alarm("orders-errors", "ALARM")
+ clock[0] = START + 62 * MINUTE
+ assert target.deployment(1)["State"] == "COMPLETE"
+
+
+def test_alarm_already_firing_rolls_back_before_any_step(clock):
+ target = Target(monitors=[{"AlarmArn": _alarm("orders-errors")}])
+ _set_alarm("orders-errors", "ALARM")
+ status, deployment = target.deploy(1, strategy="AppConfig.AllAtOnce")
+ assert status == 201
+ assert deployment["State"] == "ROLLED_BACK"
+ assert deployment["PercentageComplete"] == 0.0
+
+
+def test_monitor_on_an_unknown_alarm_is_ignored(clock):
+ target = Target(monitors=[{"AlarmArn": "arn:aws:cloudwatch:us-east-1:000000000000:alarm:missing"}])
+ target.deploy(1, strategy="AppConfig.AllAtOnce")
+ clock[0] = START + 10 * MINUTE
+ assert target.deployment(1)["State"] == "COMPLETE"
+
+
+def test_gradual_rollout_reaches_each_client_once_its_slot_is_covered(clock):
+ target = Target()
+ target.deploy(1, strategy="AppConfig.AllAtOnce")
+ clock[0] = START + 10 * MINUTE
+ clients = [target.session() for _ in range(60)]
+ for client in clients:
+ assert client.poll()[1] == {"version": 1}
+
+ target.deploy(2)
+ deploy_start = clock[0]
+ clock[0] = deploy_start + 12 * MINUTE # 40%
+ reached = set()
+ for client in clients:
+ served = client.poll()[1]
+ if appconfig_service._rollout_bucket(client.session_id) < 40:
+ assert served == {"version": 2}
+ reached.add(client.session_id)
+ else:
+ assert served is None # still on version 1, which it already has
+ assert 0 < len(reached) < len(clients)
+
+ clock[0] = deploy_start + 30 * MINUTE # 100%
+ for client in clients:
+ served = client.poll()[1]
+ assert served == (None if client.session_id in reached else {"version": 2})
+
+
+def test_poll_returns_empty_configuration_until_it_changes(clock):
+ target = Target()
+ client = target.session()
+ headers, served = client.poll()
+ assert served is None # nothing deployed yet
+
+ target.deploy(1, strategy="AppConfig.AllAtOnce")
+ headers, served = client.poll()
+ assert served == {"version": 1}
+ assert headers["Version-Label"] == "v1"
+ headers, served = client.poll()
+ assert served is None
+ assert headers["Version-Label"] == "v1"
+
+
+def test_session_poll_interval(clock):
+ target = Target()
+ assert target.session().poll()[0]["Next-Poll-Interval-In-Seconds"] == "30"
+ assert target.session(RequiredMinimumPollIntervalInSeconds=90).poll()[0]["Next-Poll-Interval-In-Seconds"] == "90"
+ status, body = _appconfig_json("POST", "/configurationsessions", {
+ "ApplicationIdentifier": target.app, "EnvironmentIdentifier": target.env,
+ "ConfigurationProfileIdentifier": target.profile, "RequiredMinimumPollIntervalInSeconds": 5,
+ })
+ assert status == 400
+ assert body["__type"] == "BadRequestException"
+
+
+# ---------------------------------------------------------------------------
+# boto3 against the shared server
+# ---------------------------------------------------------------------------
+
+
+def _live_target(appconfig_client, name, monitors=None):
+ app = appconfig_client.create_application(Name=name)
+ env = appconfig_client.create_environment(ApplicationId=app["Id"], Name="prod", Monitors=monitors or [])
+ profile = appconfig_client.create_configuration_profile(
+ ApplicationId=app["Id"], Name="settings", LocationUri="hosted")
+ appconfig_client.create_hosted_configuration_version(
+ ApplicationId=app["Id"], ConfigurationProfileId=profile["Id"],
+ Content=b'{"version": 1}', ContentType="application/json", VersionLabel="v1")
+ return app["Id"], env["Id"], profile["Id"]
+
+
+def test_live_alarm_in_alarm_rolls_back_deployment(appconfig_client, cw):
+ alarm_name = "appconfig-rollout-live-errors"
+ cw.put_metric_alarm(
+ AlarmName=alarm_name, Namespace="Orders", MetricName="Errors", Statistic="Sum",
+ Period=60, EvaluationPeriods=1, Threshold=1.0, ComparisonOperator="GreaterThanOrEqualToThreshold")
+ alarm_arn = cw.describe_alarms(AlarmNames=[alarm_name])["MetricAlarms"][0]["AlarmArn"]
+ cw.set_alarm_state(AlarmName=alarm_name, StateValue="ALARM", StateReason="test")
+ try:
+ app_id, env_id, profile_id = _live_target(
+ appconfig_client, "rollout-live-alarm", monitors=[{"AlarmArn": alarm_arn}])
+ deployment = appconfig_client.start_deployment(
+ ApplicationId=app_id, EnvironmentId=env_id, DeploymentStrategyId="AppConfig.AllAtOnce",
+ ConfigurationProfileId=profile_id, ConfigurationVersion="1")
+ assert deployment["State"] == "ROLLED_BACK"
+ assert deployment["EventLog"][0]["TriggeredBy"] == "CLOUDWATCH_ALARM"
+ environment = appconfig_client.get_environment(ApplicationId=app_id, EnvironmentId=env_id)
+ assert environment["State"] == "ROLLED_BACK"
+ finally:
+ cw.delete_alarms(AlarmNames=[alarm_name])
+
+
+def test_live_data_plane_version_label_and_unchanged_poll(appconfig_client, appconfigdata_client):
+ app_id, env_id, profile_id = _live_target(appconfig_client, "rollout-live-poll")
+ appconfig_client.start_deployment(
+ ApplicationId=app_id, EnvironmentId=env_id, DeploymentStrategyId="AppConfig.AllAtOnce",
+ ConfigurationProfileId=profile_id, ConfigurationVersion="1")
+ token = appconfigdata_client.start_configuration_session(
+ ApplicationIdentifier=app_id, EnvironmentIdentifier=env_id,
+ ConfigurationProfileIdentifier=profile_id, RequiredMinimumPollIntervalInSeconds=45,
+ )["InitialConfigurationToken"]
+
+ first = appconfigdata_client.get_latest_configuration(ConfigurationToken=token)
+ assert json.loads(first["Configuration"].read()) == {"version": 1}
+ assert first["VersionLabel"] == "v1"
+ assert first["NextPollIntervalInSeconds"] == 45
+
+ second = appconfigdata_client.get_latest_configuration(
+ ConfigurationToken=first["NextPollConfigurationToken"])
+ assert second["Configuration"].read() == b""
+
+
+def test_live_concurrent_deployment_conflicts(appconfig_client):
+ app_id, env_id, profile_id = _live_target(appconfig_client, "rollout-live-conflict")
+ appconfig_client.start_deployment(
+ ApplicationId=app_id, EnvironmentId=env_id, DeploymentStrategyId="AppConfig.AllAtOnce",
+ ConfigurationProfileId=profile_id, ConfigurationVersion="1")
+ with pytest.raises(ClientError) as exc:
+ appconfig_client.start_deployment(
+ ApplicationId=app_id, EnvironmentId=env_id, DeploymentStrategyId="AppConfig.AllAtOnce",
+ ConfigurationProfileId=profile_id, ConfigurationVersion="1", LatestDeploymentNumber=0)
+ assert exc.value.response["Error"]["Code"] == "ConflictException"
diff --git a/tests/test_appconfig_rollout.py b/tests/test_appconfig_rollout.py
deleted file mode 100644
index 7c218589..00000000
--- a/tests/test_appconfig_rollout.py
+++ /dev/null
@@ -1,460 +0,0 @@
-"""
-AppConfig gradual rollout: deployments walk DEPLOYING -> BAKING -> COMPLETE
-over their strategy, environment monitors roll them back, and the data plane
-serves each client the version the rollout has reached.
-
-Most tests drive the handlers in-process against a fake clock with one
-strategy minute lasting 60 real seconds (AWS's pace), so a 30-minute strategy
-can be stepped through without sleeping. The boto3 tests at the end run
-against the shared server at its default pace, where deployments finish as
-they start.
-"""
-
-import asyncio
-import json
-import time
-
-import pytest
-from botocore.exceptions import ClientError
-
-from ministack.core.responses import get_account_id
-from ministack.services import appconfig as appconfig_service
-from ministack.services import cloudwatch as cloudwatch_service
-
-MINUTE = 60.0
-START = 1_800_000_000.0
-
-
-def clock(monkeypatch):
- now = [START]
- monkeypatch.setattr(time, "time", lambda: now[0])
- monkeypatch.setattr(appconfig_service, "_DEPLOYMENT_MINUTE_SECONDS", MINUTE)
- appconfig_service.reset()
- cloudwatch_service.reset()
- yield now
- appconfig_service.reset()
- cloudwatch_service.reset()
-
-
-def _appconfig(method, path, body=None, headers=None, query=None):
- raw = json.dumps(body).encode() if isinstance(body, dict) else (body or b"")
- status, resp_headers, resp_body = asyncio.run(appconfig_service.handle_request(
- method, path, {k.lower(): v for k, v in (headers or {}).items()}, raw, query or {}))
- return status, resp_headers, resp_body
-
-
-def _appconfig_json(method, path, body=None, headers=None):
- status, _, resp_body = _appconfig(method, path, body, headers)
- return status, json.loads(resp_body) if resp_body else {}
-
-
-def _cloudwatch(action, body):
- headers = {"x-amz-target": f"GraniteServiceVersion20100801.{action}",
- "content-type": "application/x-amz-json-1.0"}
- status, _, _ = asyncio.run(cloudwatch_service.handle_request(
- "POST", "/", headers, json.dumps(body).encode(), {}))
- assert status == 200
-
-
-def _alarm(name):
- _cloudwatch("PutMetricAlarm", {
- "AlarmName": name, "Namespace": "Orders", "MetricName": "Errors",
- "Statistic": "Sum", "Period": 60, "EvaluationPeriods": 1,
- "Threshold": 1.0, "ComparisonOperator": "GreaterThanOrEqualToThreshold",
- })
- return f"arn:aws:cloudwatch:us-east-1:{get_account_id()}:alarm:{name}"
-
-
-def _set_alarm(name, state):
- _cloudwatch("SetAlarmState", {"AlarmName": name, "StateValue": state, "StateReason": "test"})
-
-
-class Target:
- """An application, environment and hosted profile holding versions 1 and 2."""
-
- def __init__(self, monitors=None):
- _, app = _appconfig_json("POST", "/applications", {"Name": "orders"})
- _, env = _appconfig_json("POST", f"/applications/{app['Id']}/environments",
- {"Name": "prod", "Monitors": monitors or []})
- _, profile = _appconfig_json("POST", f"/applications/{app['Id']}/configurationprofiles",
- {"Name": "settings", "LocationUri": "hosted"})
- self.app, self.env, self.profile = app["Id"], env["Id"], profile["Id"]
- for version in (1, 2):
- status, _, _ = _appconfig(
- "POST",
- f"/applications/{self.app}/configurationprofiles/{self.profile}/hostedconfigurationversions",
- json.dumps({"version": version}).encode(),
- {"Content-Type": "application/json", "VersionLabel": f"v{version}"},
- )
- assert status == 201
-
- @property
- def deployments_path(self):
- return f"/applications/{self.app}/environments/{self.env}/deployments"
-
- def deploy(self, version, strategy="AppConfig.Linear20PercentEvery6Minutes", **extra):
- return _appconfig_json("POST", self.deployments_path, {
- "DeploymentStrategyId": strategy, "ConfigurationProfileId": self.profile,
- "ConfigurationVersion": str(version), **extra,
- })
-
- def deployment(self, number):
- status, body = _appconfig_json("GET", f"{self.deployments_path}/{number}")
- assert status == 200
- return body
-
- def stop(self, number, allow_revert=False):
- headers = {"Allow-Revert": "true"} if allow_revert else {}
- return _appconfig_json("DELETE", f"{self.deployments_path}/{number}", headers=headers)
-
- def environment_state(self):
- return _appconfig_json("GET", f"/applications/{self.app}/environments/{self.env}")[1]["State"]
-
- def session(self, **extra):
- status, body = _appconfig_json("POST", "/configurationsessions", {
- "ApplicationIdentifier": self.app, "EnvironmentIdentifier": self.env,
- "ConfigurationProfileIdentifier": self.profile, **extra,
- })
- assert status == 201
- return Client(body["InitialConfigurationToken"])
-
-
-class Client:
- """One configuration session, polling with the token it was last handed."""
-
- def __init__(self, token):
- self.session_id = token
- self.token = token
-
- def poll(self):
- status, headers, body = _appconfig("GET", "/configuration", query={"configuration_token": self.token})
- assert status == 200
- self.token = headers["Next-Poll-Configuration-Token"]
- return headers, json.loads(body) if body else None
-
-
-def _event_types(deployment):
- return [event["EventType"] for event in deployment["EventLog"]]
-
-
-def test_rollout_steps_follow_the_growth_type():
- assert appconfig_service._rollout_steps("LINEAR", 20.0) == [20.0, 40.0, 60.0, 80.0, 100.0]
- assert appconfig_service._rollout_steps("LINEAR", 100.0) == [100.0]
- # G*(2^N) from the CreateDeploymentStrategy docs.
- assert appconfig_service._rollout_steps("EXPONENTIAL", 10.0) == [10.0, 20.0, 40.0, 80.0, 100.0]
- assert appconfig_service._rollout_steps("EXPONENTIAL", 2.0) == [2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 100.0]
- # Below the model's 1.0 minimum (stored unvalidated) still terminates.
- assert appconfig_service._rollout_steps("LINEAR", -5.0)[-1] == 100.0
-
-
-def test_linear_deployment_steps_bakes_and_completes(clock):
- target = Target()
- status, deployment = target.deploy(1)
- assert status == 201
- assert deployment["State"] == "DEPLOYING"
- assert deployment["PercentageComplete"] == 0.0
- assert _event_types(deployment) == ["DEPLOYMENT_STARTED"]
- assert target.environment_state() == "DEPLOYING"
-
- # Linear20PercentEvery6Minutes: five 20% steps over 30 minutes, then a 30-minute bake.
- clock[0] = START + 6 * MINUTE
- assert target.deployment(1)["PercentageComplete"] == 20.0
- clock[0] = START + 12 * MINUTE - 1
- assert target.deployment(1)["PercentageComplete"] == 20.0
- clock[0] = START + 12 * MINUTE
- assert target.deployment(1)["PercentageComplete"] == 40.0
-
- clock[0] = START + 30 * MINUTE
- deployment = target.deployment(1)
- assert (deployment["State"], deployment["PercentageComplete"]) == ("BAKING", 100.0)
- assert target.environment_state() == "DEPLOYING"
-
- clock[0] = START + 60 * MINUTE
- deployment = target.deployment(1)
- assert deployment["State"] == "COMPLETE"
- assert deployment["CompletedAt"] == appconfig_service._iso(START + 60 * MINUTE)
- assert target.environment_state() == "READY_FOR_DEPLOYMENT"
- # Most recent first.
- assert _event_types(deployment) == [
- "DEPLOYMENT_COMPLETED", "BAKE_TIME_STARTED",
- *["PERCENTAGE_UPDATED"] * 5,
- "DEPLOYMENT_STARTED",
- ]
- first_step = deployment["EventLog"][-2]
- assert first_step["OccurredAt"] == appconfig_service._iso(START + 6 * MINUTE)
- assert first_step["TriggeredBy"] == "APPCONFIG"
-
-
-def test_list_deployments_reports_rollout_progress(clock):
- target = Target()
- target.deploy(1, strategy="AppConfig.Canary10Percent20Minutes")
- clock[0] = START + 4 * MINUTE
- status, body = _appconfig_json("GET", target.deployments_path)
- assert status == 200
- [summary] = body["Items"]
- assert (summary["State"], summary["PercentageComplete"]) == ("DEPLOYING", 10.0)
- assert summary["VersionLabel"] == "v1"
- assert "CompletedAt" not in summary
-
-
-def test_start_deployment_conflicts_with_one_in_progress(clock):
- target = Target()
- target.deploy(1)
- status, body = target.deploy(2)
- assert status == 409
- assert body["__type"] == "ConflictException"
-
- # Still in progress while baking.
- clock[0] = START + 30 * MINUTE
- assert target.deploy(2)[0] == 409
-
- clock[0] = START + 60 * MINUTE
- status, body = target.deploy(2)
- assert status == 201
- assert body["DeploymentNumber"] == 2
-
-
-def test_start_deployment_checks_latest_deployment_number(clock):
- target = Target()
- assert target.deploy(1, strategy="AppConfig.AllAtOnce", LatestDeploymentNumber=0)[0] == 201
- clock[0] = START + 10 * MINUTE
- status, body = target.deploy(2, strategy="AppConfig.AllAtOnce", LatestDeploymentNumber=0)
- assert status == 409
- assert body["__type"] == "ConflictException"
- assert target.deploy(2, strategy="AppConfig.AllAtOnce", LatestDeploymentNumber=1)[0] == 201
-
-
-def test_stop_rolls_back_an_in_progress_deployment(clock):
- target = Target()
- target.deploy(1, strategy="AppConfig.AllAtOnce")
- clock[0] = START + 10 * MINUTE
- client = target.session()
- assert client.poll()[1] == {"version": 1}
-
- target.deploy(2)
- clock[0] = START + 40 * MINUTE # 100%, baking
- assert client.poll()[1] == {"version": 2}
-
- status, deployment = target.stop(2)
- assert status == 202
- assert deployment["State"] == "ROLLED_BACK"
- assert _event_types(deployment)[:2] == ["ROLLBACK_COMPLETED", "ROLLBACK_STARTED"]
- assert deployment["EventLog"][0]["TriggeredBy"] == "USER"
- assert target.environment_state() == "ROLLED_BACK"
- assert client.poll()[1] == {"version": 1}
-
- # A stopped deployment cannot be stopped again, and the environment takes a new one.
- assert target.stop(2)[0] == 400
- assert target.deploy(2)[0] == 201
-
-
-def test_revert_requires_allow_revert_and_the_72_hour_window(clock):
- target = Target()
- target.deploy(1, strategy="AppConfig.AllAtOnce")
- clock[0] = START + 10 * MINUTE
- target.deploy(2, strategy="AppConfig.AllAtOnce")
- clock[0] = START + 20 * MINUTE
- assert target.deployment(2)["State"] == "COMPLETE"
-
- status, body = target.stop(2)
- assert status == 400
- assert body["__type"] == "BadRequestException"
-
- clock[0] = START + 20 * MINUTE + 72 * 3600 + 1
- assert target.stop(2, allow_revert=True)[0] == 400
-
- clock[0] = START + 20 * MINUTE + 72 * 3600
- status, deployment = target.stop(2, allow_revert=True)
- assert status == 202
- assert deployment["State"] == "REVERTED"
- assert target.environment_state() == "REVERTED"
- assert target.session().poll()[1] == {"version": 1}
-
-
-def test_monitor_alarm_rolls_back_at_the_moment_it_fires(clock):
- alarm_arn = _alarm("orders-errors")
- target = Target(monitors=[{"AlarmArn": alarm_arn}])
- target.deploy(1, strategy="AppConfig.AllAtOnce")
- clock[0] = START + 10 * MINUTE
- target.deploy(2)
- deploy_start = clock[0]
-
- clock[0] = deploy_start + 7 * MINUTE
- _cloudwatch("PutMetricData", {"Namespace": "Orders", "MetricData": [{"MetricName": "Errors", "Value": 5}]})
- clock[0] = deploy_start + 20 * MINUTE
-
- deployment = target.deployment(2)
- assert deployment["State"] == "ROLLED_BACK"
- assert deployment["PercentageComplete"] == 20.0 # the 12-minute step never came
- rollback_started = deployment["EventLog"][1]
- assert rollback_started["EventType"] == "ROLLBACK_STARTED"
- assert rollback_started["TriggeredBy"] == "CLOUDWATCH_ALARM"
- assert alarm_arn in rollback_started["Description"]
- assert rollback_started["OccurredAt"] == appconfig_service._iso(deploy_start + 7 * MINUTE)
- assert target.environment_state() == "ROLLED_BACK"
- assert target.session().poll()[1] == {"version": 1}
-
-
-def test_alarm_that_recovers_during_the_bake_still_rolls_back(clock):
- target = Target(monitors=[{"AlarmArn": _alarm("orders-errors")}])
- target.deploy(1)
- clock[0] = START + 35 * MINUTE
- _set_alarm("orders-errors", "ALARM")
- clock[0] = START + 36 * MINUTE
- _set_alarm("orders-errors", "OK")
-
- clock[0] = START + 90 * MINUTE
- deployment = target.deployment(1)
- assert deployment["State"] == "ROLLED_BACK"
- assert deployment["PercentageComplete"] == 100.0
- assert "BAKE_TIME_STARTED" in _event_types(deployment)
-
-
-def test_alarm_after_completion_does_not_roll_back(clock):
- target = Target(monitors=[{"AlarmArn": _alarm("orders-errors")}])
- target.deploy(1)
- clock[0] = START + 61 * MINUTE
- _set_alarm("orders-errors", "ALARM")
- clock[0] = START + 62 * MINUTE
- assert target.deployment(1)["State"] == "COMPLETE"
-
-
-def test_alarm_already_firing_rolls_back_before_any_step(clock, monkeypatch):
- monkeypatch.setattr(appconfig_service, "_DEPLOYMENT_MINUTE_SECONDS", 0.0)
- target = Target(monitors=[{"AlarmArn": _alarm("orders-errors")}])
- _set_alarm("orders-errors", "ALARM")
- status, deployment = target.deploy(1, strategy="AppConfig.AllAtOnce")
- assert status == 201
- assert deployment["State"] == "ROLLED_BACK"
- assert deployment["PercentageComplete"] == 0.0
-
-
-def test_monitor_on_an_unknown_alarm_is_ignored(clock):
- target = Target(monitors=[{"AlarmArn": "arn:aws:cloudwatch:us-east-1:000000000000:alarm:missing"}])
- target.deploy(1, strategy="AppConfig.AllAtOnce")
- clock[0] = START + 10 * MINUTE
- assert target.deployment(1)["State"] == "COMPLETE"
-
-
-def test_gradual_rollout_reaches_each_client_once_its_slot_is_covered(clock):
- target = Target()
- target.deploy(1, strategy="AppConfig.AllAtOnce")
- clock[0] = START + 10 * MINUTE
- clients = [target.session() for _ in range(60)]
- for client in clients:
- assert client.poll()[1] == {"version": 1}
-
- target.deploy(2)
- deploy_start = clock[0]
- clock[0] = deploy_start + 12 * MINUTE # 40%
- reached = set()
- for client in clients:
- served = client.poll()[1]
- if appconfig_service._rollout_bucket(client.session_id) < 40:
- assert served == {"version": 2}
- reached.add(client.session_id)
- else:
- assert served is None # still on version 1, which it already has
- assert 0 < len(reached) < len(clients)
-
- clock[0] = deploy_start + 30 * MINUTE # 100%
- for client in clients:
- served = client.poll()[1]
- assert served == (None if client.session_id in reached else {"version": 2})
-
-
-def test_poll_returns_empty_configuration_until_it_changes(clock):
- target = Target()
- client = target.session()
- headers, served = client.poll()
- assert served is None # nothing deployed yet
-
- target.deploy(1, strategy="AppConfig.AllAtOnce")
- headers, served = client.poll()
- assert served == {"version": 1}
- assert headers["Version-Label"] == "v1"
- headers, served = client.poll()
- assert served is None
- assert headers["Version-Label"] == "v1"
-
-
-def test_session_poll_interval(clock):
- target = Target()
- assert target.session().poll()[0]["Next-Poll-Interval-In-Seconds"] == "30"
- assert target.session(RequiredMinimumPollIntervalInSeconds=90).poll()[0]["Next-Poll-Interval-In-Seconds"] == "90"
- status, body = _appconfig_json("POST", "/configurationsessions", {
- "ApplicationIdentifier": target.app, "EnvironmentIdentifier": target.env,
- "ConfigurationProfileIdentifier": target.profile, "RequiredMinimumPollIntervalInSeconds": 5,
- })
- assert status == 400
- assert body["__type"] == "BadRequestException"
-
-
-# ---------------------------------------------------------------------------
-# boto3 against the shared server (deployments finish as they start)
-# ---------------------------------------------------------------------------
-
-
-def _live_target(appconfig_client, name, monitors=None):
- app = appconfig_client.create_application(Name=name)
- env = appconfig_client.create_environment(ApplicationId=app["Id"], Name="prod", Monitors=monitors or [])
- profile = appconfig_client.create_configuration_profile(
- ApplicationId=app["Id"], Name="settings", LocationUri="hosted")
- appconfig_client.create_hosted_configuration_version(
- ApplicationId=app["Id"], ConfigurationProfileId=profile["Id"],
- Content=b'{"version": 1}', ContentType="application/json", VersionLabel="v1")
- return app["Id"], env["Id"], profile["Id"]
-
-
-def test_live_alarm_in_alarm_rolls_back_deployment(appconfig_client, cw):
- alarm_name = "appconfig-rollout-live-errors"
- cw.put_metric_alarm(
- AlarmName=alarm_name, Namespace="Orders", MetricName="Errors", Statistic="Sum",
- Period=60, EvaluationPeriods=1, Threshold=1.0, ComparisonOperator="GreaterThanOrEqualToThreshold")
- alarm_arn = cw.describe_alarms(AlarmNames=[alarm_name])["MetricAlarms"][0]["AlarmArn"]
- cw.set_alarm_state(AlarmName=alarm_name, StateValue="ALARM", StateReason="test")
- try:
- app_id, env_id, profile_id = _live_target(
- appconfig_client, "rollout-live-alarm", monitors=[{"AlarmArn": alarm_arn}])
- deployment = appconfig_client.start_deployment(
- ApplicationId=app_id, EnvironmentId=env_id, DeploymentStrategyId="AppConfig.AllAtOnce",
- ConfigurationProfileId=profile_id, ConfigurationVersion="1")
- assert deployment["State"] == "ROLLED_BACK"
- assert deployment["EventLog"][0]["TriggeredBy"] == "CLOUDWATCH_ALARM"
- environment = appconfig_client.get_environment(ApplicationId=app_id, EnvironmentId=env_id)
- assert environment["State"] == "ROLLED_BACK"
- finally:
- cw.delete_alarms(AlarmNames=[alarm_name])
-
-
-def test_live_data_plane_version_label_and_unchanged_poll(appconfig_client, appconfigdata_client):
- app_id, env_id, profile_id = _live_target(appconfig_client, "rollout-live-poll")
- appconfig_client.start_deployment(
- ApplicationId=app_id, EnvironmentId=env_id, DeploymentStrategyId="AppConfig.AllAtOnce",
- ConfigurationProfileId=profile_id, ConfigurationVersion="1")
- token = appconfigdata_client.start_configuration_session(
- ApplicationIdentifier=app_id, EnvironmentIdentifier=env_id,
- ConfigurationProfileIdentifier=profile_id, RequiredMinimumPollIntervalInSeconds=45,
- )["InitialConfigurationToken"]
-
- first = appconfigdata_client.get_latest_configuration(ConfigurationToken=token)
- assert json.loads(first["Configuration"].read()) == {"version": 1}
- assert first["VersionLabel"] == "v1"
- assert first["NextPollIntervalInSeconds"] == 45
-
- second = appconfigdata_client.get_latest_configuration(
- ConfigurationToken=first["NextPollConfigurationToken"])
- assert second["Configuration"].read() == b""
-
-
-def test_live_concurrent_deployment_conflicts(appconfig_client):
- app_id, env_id, profile_id = _live_target(appconfig_client, "rollout-live-conflict")
- appconfig_client.start_deployment(
- ApplicationId=app_id, EnvironmentId=env_id, DeploymentStrategyId="AppConfig.AllAtOnce",
- ConfigurationProfileId=profile_id, ConfigurationVersion="1")
- with pytest.raises(ClientError) as exc:
- appconfig_client.start_deployment(
- ApplicationId=app_id, EnvironmentId=env_id, DeploymentStrategyId="AppConfig.AllAtOnce",
- ConfigurationProfileId=profile_id, ConfigurationVersion="1", LatestDeploymentNumber=0)
- assert exc.value.response["Error"]["Code"] == "ConflictException"
diff --git a/tests/test_cloudwatch_logs.py b/tests/test_cloudwatch_logs.py
index 0fb95711..3fa37a57 100644
--- a/tests/test_cloudwatch_logs.py
+++ b/tests/test_cloudwatch_logs.py
@@ -1,3 +1,4 @@
+import asyncio
import json
import os
import time
@@ -8,6 +9,10 @@ import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
+from ministack import app as _app_mod
+from ministack.services import cloudwatch_logs as _logs_svc
+from ministack.services import iam as _iam_svc
+
_endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
@@ -2081,3 +2086,307 @@ def test_logs_subscription_filter_delivers_for_non_default_account():
msgs = sqs_c.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=2)
got = msgs.get("Messages", [])
assert got, "subscription-filter → Lambda delivery never arrived for a non-default account"
+
+
+# ── IAM tag conditions ──
+
+
+def logs_auth(monkeypatch):
+ monkeypatch.setattr(_app_mod, "AUTH", True)
+ account, region = "123456789012", "us-east-1"
+ user, key = "logs-tag-context", "AKIALOGSTAGCONTEXT"
+ _iam_svc._users.set_scoped(account, None, user, {"UserName": user, "AttachedPolicies": []})
+ _iam_svc._access_keys.set_scoped(account, None, key, {
+ "AccessKeyId": key, "SecretAccessKey": "test", "Status": "Active", "UserName": user,
+ })
+ created = []
+
+ def call(action, *, root=False, request_region=region, with_headers=False, raw_body=None, **payload):
+ body = json.dumps(payload).encode() if raw_body is None else raw_body
+ sent = []
+
+ async def receive():
+ return {"type": "http.request", "body": body, "more_body": False}
+
+ async def send(message):
+ sent.append(message)
+
+ scope = {
+ "type": "http", "method": "POST", "path": "/", "query_string": b"",
+ "headers": [
+ (b"host", f"_logs_svc.{request_region}.amazonaws.com".encode()),
+ (b"x-amz-target", f"Logs_20140328.{action}".encode()),
+ (b"content-type", b"application/x-amz-json-1.1"),
+ (b"authorization", (
+ f"AWS4-HMAC-SHA256 Credential={account if root else key}"
+ f"/20261006/{request_region}/logs/aws4_request"
+ ).encode()),
+ ],
+ }
+ asyncio.run(_app_mod.app(scope, receive, send))
+ response = sent[0]["status"], json.loads(sent[1]["body"])
+ if with_headers:
+ return *response, {name.lower(): value for name, value in sent[0]["headers"]}
+ return response
+
+ def create(name, tags=None, request_region=region):
+ assert call("CreateLogGroup", root=True, request_region=request_region,
+ logGroupName=name, tags=tags or {})[0] == 200
+ created.append((request_region, name))
+ return f"arn:aws:logs:{request_region}:{account}:log-group:{name}"
+
+ def policy(*statements):
+ _iam_svc._user_inline_policies.set_scoped(account, None, user, {
+ "context": {"Version": "2012-10-17", "Statement": list(statements)},
+ })
+
+ try:
+ yield call, create, policy, account, region
+ finally:
+ _iam_svc._user_inline_policies.pop_scoped(account, None, user, None)
+ _iam_svc._access_keys.pop_scoped(account, None, key, None)
+ _iam_svc._users.pop_scoped(account, None, user, None)
+ for request_region, name in created:
+ _logs_svc._log_groups.pop_scoped(account, request_region, name, None)
+ _logs_svc._log_groups.pop_scoped(account, region, "logs-context-create", None)
+
+
+def assert_denied(response, *, explicit=False):
+ status, body = response
+ assert status == 400 and body["__type"] == "AccessDeniedException"
+ if explicit:
+ assert "explicit deny" in body["Message"]
+
+
[email protected]("explicit", [False, True])
+def test_authorization_denial_matches_live_logs_error_envelope(logs_auth, explicit):
+ call, create, policy, _, _ = logs_auth
+ arn = create("logs-context-denial-envelope", {"protect": "true"})
+ if explicit:
+ policy(
+ {"Effect": "Allow", "Action": "logs:UntagResource", "Resource": arn},
+ {"Effect": "Deny", "Action": "logs:UntagResource", "Resource": arn},
+ )
+ else:
+ policy()
+ status, body, headers = call("UntagResource", resourceArn=arn, tagKeys=["protect"], with_headers=True)
+ assert_denied((status, body), explicit=explicit)
+ assert f"on resource: {arn}" in body["Message"]
+ if not explicit:
+ assert "because no identity-based policy allows the logs:UntagResource action" in body["Message"]
+ assert headers[b"content-type"] == b"application/x-amz-json-1.1"
+ assert b"x-amzn-errortype" not in headers
+ assert "message" not in body
+
+
[email protected]("action", ["PutRetentionPolicy", "ListTagsLogGroup", "ListTagsForResource"])
+def test_owner_tag_allows_only_matching_existing_group(logs_auth, action):
+ call, create, policy, _, _ = logs_auth
+ for owner in ("team-a", "team-b", None):
+ name = f"logs-context-owner-{owner}"
+ arn = create(name, {"owner": owner} if owner else {})
+ policy({"Effect": "Allow", "Action": f"logs:{action}", "Resource": arn + "*",
+ "Condition": {"StringEquals": {"aws:ResourceTag/owner": "team-a"}}})
+ params = {"resourceArn": arn} if action == "ListTagsForResource" else {"logGroupName": name}
+ if action == "PutRetentionPolicy":
+ params["retentionInDays"] = 7
+ response = call(action, **params)
+ if owner == "team-a":
+ assert response[0] == 200
+ else:
+ assert_denied(response)
+
+
[email protected]("legacy", [False, True])
+def test_protect_tag_deny_prevents_removal_without_blocking_other_tags(logs_auth, legacy):
+ call, create, policy, _, _ = logs_auth
+ name = "logs-context-protected"
+ arn = create(name, {"protect": "true", "harmless": "yes"})
+ action = "UntagLogGroup" if legacy else "UntagResource"
+ policy(
+ {"Effect": "Allow", "Action": f"logs:{action}", "Resource": "*"},
+ {"Effect": "Deny", "Action": f"logs:{action}", "Resource": "*",
+ "Condition": {"StringEquals": {"aws:ResourceTag/protect": "true"},
+ "ForAnyValue:StringEquals": {"aws:TagKeys": ["protect"]}}},
+ )
+ target = {"logGroupName": name} if legacy else {"resourceArn": arn}
+ field = "tags" if legacy else "tagKeys"
+ assert_denied(call(action, **target, **{field: ["harmless", "protect"]}), explicit=True)
+ assert call("ListTagsForResource", root=True, resourceArn=arn) == (
+ 200, {"tags": {"protect": "true", "harmless": "yes"}},
+ )
+ assert call(action, **target, **{field: ["harmless"]})[0] == 200
+ assert call("ListTagsForResource", root=True, resourceArn=arn) == (200, {"tags": {"protect": "true"}})
+
+
[email protected]("action", ["CreateLogGroup", "TagLogGroup", "TagResource"])
+def test_request_tags_and_keys_use_the_operation_payload(logs_auth, action):
+ call, create, policy, _, _ = logs_auth
+ name = "logs-context-create"
+ arn = f"arn:aws:logs:us-east-1:123456789012:log-group:{name}"
+ if action != "CreateLogGroup":
+ create(name, {"owner": "team-a"})
+ policy({"Effect": "Allow", "Action": f"logs:{action}", "Resource": arn + "*",
+ "Condition": {"StringEquals": {"aws:RequestTag/owner": "team-a"},
+ "ForAllValues:StringEquals": {"aws:TagKeys": ["owner"]}}})
+ target = {"resourceArn": arn} if action == "TagResource" else {"logGroupName": name}
+ for tags in ({"owner": "team-b"}, {}, {"owner": "team-a", "extra": "bad"}):
+ assert_denied(call(action, **target, tags=tags))
+ assert call(action, **target, tags={"owner": "team-a"})[0] == 200
+
+
+def test_modern_tag_actions_enforce_exact_target_arn(logs_auth):
+ call, create, policy, _, _ = logs_auth
+ allowed = create("logs-context-exact-allow")
+ denied = create("logs-context-exact-deny", {"protect": "true"})
+ policy({"Effect": "Allow", "Action": ["logs:TagResource", "logs:UntagResource", "logs:ListTagsForResource"],
+ "Resource": allowed})
+ assert call("TagResource", resourceArn=allowed, tags={"owner": "team-a"})[0] == 200
+ assert call("ListTagsForResource", resourceArn=allowed) == (200, {"tags": {"owner": "team-a"}})
+ assert call("UntagResource", resourceArn=allowed, tagKeys=["owner"])[0] == 200
+ for action, extra in (("TagResource", {"tags": {"owner": "wrong"}}),
+ ("UntagResource", {"tagKeys": ["protect"]}), ("ListTagsForResource", {})):
+ assert_denied(call(action, resourceArn=denied, logGroupName="logs-context-exact-allow", **extra))
+ assert call("ListTagsForResource", root=True, resourceArn=denied) == (200, {"tags": {"protect": "true"}})
+
+
[email protected]("legacy", [False, True])
+def test_incoming_owner_tag_cannot_replace_existing_ownership_context(logs_auth, legacy):
+ call, create, policy, _, _ = logs_auth
+ name = "logs-context-change-owner"
+ arn = create(name, {"owner": "team-b"})
+ action = "TagLogGroup" if legacy else "TagResource"
+ policy({"Effect": "Allow", "Action": f"logs:{action}", "Resource": "*",
+ "Condition": {"StringEquals": {"aws:ResourceTag/owner": "team-a",
+ "aws:RequestTag/owner": "team-a"}}})
+ target = {"logGroupName": name} if legacy else {"resourceArn": arn}
+ assert_denied(call(action, **target, tags={"owner": "team-a"}))
+ assert call("ListTagsForResource", root=True, resourceArn=arn) == (200, {"tags": {"owner": "team-b"}})
+
+
+def test_disabled_auth_keeps_logs_tag_calls_permissive(logs_auth, monkeypatch):
+ call, create, policy, _, _ = logs_auth
+ arn = create("logs-context-auth-disabled", {"protect": "true"})
+ policy({"Effect": "Deny", "Action": "logs:*", "Resource": "*"})
+ monkeypatch.setattr(_app_mod, "AUTH", False)
+ assert call("UntagResource", root=True, resourceArn=arn, tagKeys=["protect"])[0] == 200
+ assert call("ListTagsForResource", root=True, resourceArn=arn) == (200, {"tags": {}})
+
+
[email protected]("resource_type,store", [
+ ("delivery-source", _logs_svc._delivery_sources),
+ ("delivery-destination", _logs_svc._delivery_destinations),
+ ("delivery", _logs_svc._deliveries),
+])
+def test_modern_tag_context_uses_the_supported_delivery_resource(logs_auth, resource_type, store):
+ call, _, policy, account, region = logs_auth
+ name = "logs-context-delivery"
+ arn = f"arn:aws:logs:{region}:{account}:{resource_type}:{name}"
+ store.set_scoped(account, region, name, {"arn": arn, "tags": {"owner": "team-a", "protect": "true"}})
+ policy(
+ {"Effect": "Allow", "Action": ["logs:ListTagsForResource", "logs:UntagResource"], "Resource": arn,
+ "Condition": {"StringEquals": {"aws:ResourceTag/owner": "team-a"}}},
+ {"Effect": "Deny", "Action": "logs:UntagResource", "Resource": arn,
+ "Condition": {"ForAnyValue:StringEquals": {"aws:TagKeys": ["protect"]}}},
+ )
+ try:
+ assert call("ListTagsForResource", resourceArn=arn) == (
+ 200, {"tags": {"owner": "team-a", "protect": "true"}},
+ )
+ assert_denied(call("UntagResource", resourceArn=arn, tagKeys=["protect"]), explicit=True)
+ assert store.get_scoped(account, region, name)["tags"]["protect"] == "true"
+ finally:
+ store.pop_scoped(account, region, name, None)
+
+
+def test_owner_context_is_scoped_to_resource_account_and_region(logs_auth):
+ call, create, policy, account, region = logs_auth
+ name = "logs-context-scope"
+ local = create(name, {"owner": "team-a"})
+ remote_region = create(name, {"owner": "team-b"}, request_region="us-west-2")
+ _logs_svc._log_groups.set_scoped("111111111111", region, name, {
+ "arn": f"arn:aws:logs:{region}:111111111111:log-group:{name}:*", "tags": {"owner": "team-a"},
+ })
+ policy({"Effect": "Allow", "Action": "logs:ListTagsForResource", "Resource": "*",
+ "Condition": {"StringEquals": {"aws:ResourceTag/owner": "team-a"}}})
+ try:
+ assert call("ListTagsForResource", resourceArn=local)[0] == 200
+ assert_denied(call("ListTagsForResource", resourceArn=remote_region, request_region="us-west-2"))
+ for invalid in (remote_region, local.replace(account, "111111111111")):
+ assert call("ListTagsForResource", resourceArn=invalid) == (
+ 400, {"__type": "ValidationException", "message": "Invalid resourceArn"},
+ )
+ finally:
+ _logs_svc._log_groups.pop_scoped("111111111111", region, name, None)
+
+
[email protected]("auth", [False, True])
[email protected]("resource_type,store", [
+ ("log-group", _logs_svc._log_groups),
+ ("delivery-source", _logs_svc._delivery_sources),
+ ("delivery-destination", _logs_svc._delivery_destinations),
+ ("delivery", _logs_svc._deliveries),
+])
+def test_modern_tag_actions_reject_aliases_to_unrelated_arns(
+ logs_auth, monkeypatch, auth, resource_type, store):
+ call, create, policy, account, region = logs_auth
+ name = "logs-context-resolver"
+ tags = {"owner": "team-a", "protect": "true"}
+ arn = f"arn:aws:logs:{region}:{account}:{resource_type}:{name}"
+ if resource_type == "log-group":
+ create(name, tags)
+ else:
+ store.set_scoped(account, region, name, {"arn": arn, "tags": dict(tags)})
+ monkeypatch.setattr(_app_mod, "AUTH", auth)
+ invalid_arns = [
+ arn.replace(account, "111111111111"),
+ arn.replace(region, "us-west-2"),
+ arn.replace(":logs:", ":s3:"),
+ arn.replace("arn:aws:", "arn:aws-cn:"),
+ arn + ":**" if resource_type == "log-group" else arn.replace(
+ f":{resource_type}:", f":{resource_type}:other:"),
+ ]
+ if resource_type == "log-group":
+ invalid_arns.append(arn + ":*")
+ try:
+ for invalid in invalid_arns:
+ # Permission on the supplied ARN must never authorize a mutation
+ # or a read of the same-named local resource.
+ policy({"Effect": "Allow", "Action": "logs:*", "Resource": invalid})
+ for action, extra in (
+ ("TagResource", {"tags": {"protect": "false"}}),
+ ("UntagResource", {"tagKeys": ["protect"]}),
+ ("ListTagsForResource", {}),
+ ):
+ assert call(action, root=not auth, resourceArn=invalid, **extra) == (
+ 400, {"__type": "ValidationException", "message": "Invalid resourceArn"},
+ )
+ assert store.get_scoped(account, region, name)["tags"] == tags
+ finally:
+ if resource_type != "log-group":
+ store.pop_scoped(account, region, name, None)
+
+
+def test_invalid_tag_arn_precedes_policy_denial_but_preserves_credential_errors(logs_auth):
+ call, create, policy, account, _ = logs_auth
+ arn = create("logs-context-validation", {"protect": "true"})
+ policy({"Effect": "Deny", "Action": "logs:*", "Resource": "*"})
+ status, body, headers = call("UntagResource", resourceArn=arn + ":*",
+ tagKeys=["protect"], with_headers=True)
+ assert (status, body) == (400, {"__type": "ValidationException", "message": "Invalid resourceArn"})
+ assert headers[b"content-type"] == b"application/x-amz-json-1.1"
+ assert b"x-amzn-errortype" not in headers
+ _iam_svc._access_keys.get_scoped(account, None, "AKIALOGSTAGCONTEXT")["Status"] = "Inactive"
+ status, body = call("UntagResource", resourceArn=arn + ":*", tagKeys=["protect"])
+ assert status == 403 and body["__type"] == "InvalidClientTokenId"
+
+
[email protected]("auth", [False, True])
+def test_tag_arn_validation_preserves_malformed_json_error(logs_auth, monkeypatch, auth):
+ call, _, _, _, _ = logs_auth
+ monkeypatch.setattr(_app_mod, "AUTH", auth)
+ for action in ("TagResource", "UntagResource", "ListTagsForResource"):
+ assert call(action, root=True, raw_body=b"{") == (
+ 400, {"__type": "SerializationException", "message": "Invalid JSON"},
+ )
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 5e85fcb7..a500c0ed 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -19,6 +19,7 @@ from urllib.parse import urlencode
import pytest
from botocore.exceptions import ClientError
+from ministack.core.iam_actions import extract_iam_action, extract_resource_arn
from ministack.core.iam_evaluator import (
AmbiguousAccessKeyError,
AuthError,
@@ -1394,6 +1395,17 @@ class TestResourceArn:
"arn:aws:dynamodb:us-east-1:123:table/snapshots",
]
+ def test_dynamodb_table_name_may_be_the_table_arn(self):
+ from ministack.core.iam_actions import dynamodb_resource_arns, dynamodb_transaction_checks
+ arn = "arn:aws:dynamodb:us-east-1:123:table/users"
+ assert dynamodb_resource_arns(json.dumps({"TableName": arn, "IndexName": "by-email"}).encode(),
+ "us-east-1", "123") == [f"{arn}/index/by-email"]
+ assert dynamodb_resource_arns(json.dumps({"RequestItems": {arn: []}}).encode(),
+ "us-east-1", "123") == [arn]
+ body = json.dumps({"TransactItems": [{"Put": {"TableName": arn, "Item": {}}}]}).encode()
+ assert dynamodb_transaction_checks("dynamodb:TransactWriteItems", body, "us-east-1", "123") == [
+ ("dynamodb:PutItem", arn)]
+
def test_eventbridge_put_events_returns_every_bus(self):
from ministack.core.iam_actions import eventbridge_resource_arns
body = json.dumps({"Entries": [
@@ -4368,3 +4380,104 @@ def test_access_denied_message_names_an_explicit_deny(service, action, explicit_
service, action, "arn:aws:iam::000000000000:user/u", "req-1", explicit_deny=explicit_deny)
expected = f"User: arn:aws:iam::000000000000:user/u is not authorized to perform: {action} "
assert (expected + reason.format(action=action)) in body.decode()
+
+
+# ── API Gateway management actions and resource paths ──
+
+
[email protected]("path", ["/restapis/api/stages/prod", "/v2/apis/api/stages/prod"])
[email protected]("method", ["GET", "POST", "PUT", "PATCH", "DELETE"])
+def test_management_actions_use_http_verbs(path, method):
+ # Neither query-protocol parameters nor JSON-protocol headers may override
+ # the action of this REST-only service.
+ assert extract_iam_action(
+ "apigateway", method, path,
+ {"x-amz-target": "ApiGateway.GetStage"}, b"", {"Action": "GetStage"},
+ ) == f"apigateway:{method}"
+
+
[email protected]("path, resource", [
+ ("/restapis", "/restapis"),
+ ("/restapis/api", "/restapis/api"),
+ ("/restapis/api/stages", "/restapis/api/stages"),
+ ("/restapis/api/stages/prod", "/restapis/api/stages/prod"),
+ ("/restapis/api/stages/prod/", "/restapis/api/stages/prod"),
+ ("/restapis/api/stages/", "/restapis/api/stages"),
+ ("/restapis/api/resources/root/methods/GET/integration", "/restapis/api/resources/root/methods/GET/integration"),
+ ("/v2/apis", "/apis"),
+ ("/v2/apis/api", "/apis/api"),
+ ("/v2/apis/api/stages", "/apis/api/stages"),
+ ("/v2/apis/api/stages/", "/apis/api/stages"),
+ ("/v2/apis/api/stages/prod/", "/apis/api/stages/prod"),
+ ("/v2/apis/api/stages/%24default", "/apis/api/stages/$default"),
+ ("/v2/apis/api/stages/%24default/", "/apis/api/stages/$default"),
+ ("/v2/apis/api/routes/route", "/apis/api/routes/route"),
+ ("/domainnames/example.com/basepathmappings", "/domainnames/example.com/basepathmappings"),
+ ("/v2/domainnames/example.com/apimappings", "/domainnames/example.com/apimappings"),
+ ("/account", "/account"),
+ ("/tags/arn:aws:apigateway:us-east-2::/restapis/api",
+ "/tags/arn%3Aaws%3Aapigateway%3Aus-east-2%3A%3A%2Frestapis%2Fapi"),
+ ("/tags/arn%3Aaws%3Aapigateway%3Aus-east-2%3A%3A%2Frestapis%2Fapi",
+ "/tags/arn%3Aaws%3Aapigateway%3Aus-east-2%3A%3A%2Frestapis%2Fapi"),
+ ("/v2/tags/arn:aws:apigateway:us-east-2::/apis/api",
+ "/tags/arn%3Aaws%3Aapigateway%3Aus-east-2%3A%3A%2Fapis%2Fapi"),
+])
+def test_management_resource_preserves_path(path, resource):
+ assert extract_resource_arn(
+ "apigateway", "GET", path, {}, b"", {}, "us-east-2", "000000000000",
+ ) == f"arn:aws:apigateway:us-east-2::{resource}"
+
+
[email protected]("prefix", ["/restapis/api", "/v2/apis/api"])
[email protected]("suffix", ["", "/"])
[email protected]("case, method, stage, expected", [
+ ("stage-grant", "GET", "prod", 200),
+ ("stage-grant", "PATCH", "prod", 200),
+ ("stage-grant", "GET", "dev", 403),
+ ("parent-grant", "GET", "prod", 403),
+ ("operation-grant", "GET", "prod", 403),
+ ("stage-deny", "GET", "prod", 403),
+ ("stage-deny", "GET", "dev", 200),
+])
+def test_stage_policy_is_enforced_on_dispatch(monkeypatch, prefix, suffix, case, method, stage, expected):
+ import ministack.app as app
+ from ministack.core import iam_evaluator
+
+ parent = f"arn:aws:apigateway:us-east-2::{prefix.removeprefix('/v2')}"
+ grants = {
+ "stage-grant": [{"Effect": "Allow", "Action": ["apigateway:GET", "apigateway:PATCH"],
+ "Resource": f"{parent}/stages/prod"}],
+ "parent-grant": [{"Effect": "Allow", "Action": "apigateway:GET", "Resource": parent}],
+ "operation-grant": [{"Effect": "Allow", "Action": "apigateway:GetStage", "Resource": "*"}],
+ "stage-deny": [
+ {"Effect": "Allow", "Action": "apigateway:*", "Resource": f"{parent}/*"},
+ {"Effect": "Deny", "Action": "apigateway:GET", "Resource": f"{parent}/stages/prod"},
+ ],
+ }
+ statements = parse_policy_document({"Statement": grants[case]})
+ dispatched = []
+
+ def enforce_policy(access_key, action, service, region, resource_arn="*", service_context=None):
+ result = evaluate(EvalContext(
+ principal_arn="arn:aws:iam::000000000000:user/caller",
+ principal_type="User", principal_account="000000000000",
+ action=action, resource_arn=resource_arn, region=region,
+ ), [statements])
+ return None if result.decision == "Allow" else result
+
+ async def handler(*args):
+ dispatched.append(args)
+ return 200, {}, b"{}"
+
+ monkeypatch.setattr(app, "AUTH", True)
+ monkeypatch.setattr(iam_evaluator, "enforce", enforce_policy)
+ monkeypatch.setattr(iam_evaluator, "pin_request_caller", lambda *args: None)
+ monkeypatch.setitem(app.SERVICE_HANDLERS, "apigateway", handler)
+ headers = {"authorization": "AWS4-HMAC-SHA256 Credential=test/20261006/us-east-2/apigateway/aws4_request"}
+ status, _, body = asyncio.run(app._dispatch_service_request(
+ method, f"{prefix}/stages/{stage}{suffix}", headers, b"", {}, "request-stage",
+ ))
+ assert status == expected
+ assert bool(dispatched) == (expected == 200)
+ if expected == 403:
+ assert f"apigateway:{method}" in json.loads(body)["message"]
diff --git a/tests/test_logs_iam_context.py b/tests/test_logs_iam_context.py
deleted file mode 100644
index 176e7fd6..00000000
--- a/tests/test_logs_iam_context.py
+++ /dev/null
@@ -1,311 +0,0 @@
-"""Exercise Logs tag conditions through the ASGI authorization boundary."""
-
-import asyncio
-import json
-
-import pytest
-
-from ministack import app as app_mod
-from ministack.services import cloudwatch_logs as logs
-from ministack.services import iam
-
-
-def logs_auth(monkeypatch):
- monkeypatch.setattr(app_mod, "AUTH", True)
- account, region = "123456789012", "us-east-1"
- user, key = "logs-tag-context", "AKIALOGSTAGCONTEXT"
- iam._users.set_scoped(account, None, user, {"UserName": user, "AttachedPolicies": []})
- iam._access_keys.set_scoped(account, None, key, {
- "AccessKeyId": key, "SecretAccessKey": "test", "Status": "Active", "UserName": user,
- })
- created = []
-
- def call(action, *, root=False, request_region=region, with_headers=False, raw_body=None, **payload):
- body = json.dumps(payload).encode() if raw_body is None else raw_body
- sent = []
-
- async def receive():
- return {"type": "http.request", "body": body, "more_body": False}
-
- async def send(message):
- sent.append(message)
-
- scope = {
- "type": "http", "method": "POST", "path": "/", "query_string": b"",
- "headers": [
- (b"host", f"logs.{request_region}.amazonaws.com".encode()),
- (b"x-amz-target", f"Logs_20140328.{action}".encode()),
- (b"content-type", b"application/x-amz-json-1.1"),
- (b"authorization", (
- f"AWS4-HMAC-SHA256 Credential={account if root else key}"
- f"/20261006/{request_region}/logs/aws4_request"
- ).encode()),
- ],
- }
- asyncio.run(app_mod.app(scope, receive, send))
- response = sent[0]["status"], json.loads(sent[1]["body"])
- if with_headers:
- return *response, {name.lower(): value for name, value in sent[0]["headers"]}
- return response
-
- def create(name, tags=None, request_region=region):
- assert call("CreateLogGroup", root=True, request_region=request_region,
- logGroupName=name, tags=tags or {})[0] == 200
- created.append((request_region, name))
- return f"arn:aws:logs:{request_region}:{account}:log-group:{name}"
-
- def policy(*statements):
- iam._user_inline_policies.set_scoped(account, None, user, {
- "context": {"Version": "2012-10-17", "Statement": list(statements)},
- })
-
- try:
- yield call, create, policy, account, region
- finally:
- iam._user_inline_policies.pop_scoped(account, None, user, None)
- iam._access_keys.pop_scoped(account, None, key, None)
- iam._users.pop_scoped(account, None, user, None)
- for request_region, name in created:
- logs._log_groups.pop_scoped(account, request_region, name, None)
- logs._log_groups.pop_scoped(account, region, "logs-context-create", None)
-
-
-def assert_denied(response, *, explicit=False):
- status, body = response
- assert status == 400 and body["__type"] == "AccessDeniedException"
- if explicit:
- assert "explicit deny" in body["Message"]
-
-
[email protected]("explicit", [False, True])
-def test_authorization_denial_matches_live_logs_error_envelope(logs_auth, explicit):
- call, create, policy, _, _ = logs_auth
- arn = create("logs-context-denial-envelope", {"protect": "true"})
- if explicit:
- policy(
- {"Effect": "Allow", "Action": "logs:UntagResource", "Resource": arn},
- {"Effect": "Deny", "Action": "logs:UntagResource", "Resource": arn},
- )
- else:
- policy()
- status, body, headers = call("UntagResource", resourceArn=arn, tagKeys=["protect"], with_headers=True)
- assert_denied((status, body), explicit=explicit)
- assert f"on resource: {arn}" in body["Message"]
- if not explicit:
- assert "because no identity-based policy allows the logs:UntagResource action" in body["Message"]
- assert headers[b"content-type"] == b"application/x-amz-json-1.1"
- assert b"x-amzn-errortype" not in headers
- assert "message" not in body
-
-
[email protected]("action", ["PutRetentionPolicy", "ListTagsLogGroup", "ListTagsForResource"])
-def test_owner_tag_allows_only_matching_existing_group(logs_auth, action):
- call, create, policy, _, _ = logs_auth
- for owner in ("team-a", "team-b", None):
- name = f"logs-context-owner-{owner}"
- arn = create(name, {"owner": owner} if owner else {})
- policy({"Effect": "Allow", "Action": f"logs:{action}", "Resource": arn + "*",
- "Condition": {"StringEquals": {"aws:ResourceTag/owner": "team-a"}}})
- params = {"resourceArn": arn} if action == "ListTagsForResource" else {"logGroupName": name}
- if action == "PutRetentionPolicy":
- params["retentionInDays"] = 7
- response = call(action, **params)
- if owner == "team-a":
- assert response[0] == 200
- else:
- assert_denied(response)
-
-
[email protected]("legacy", [False, True])
-def test_protect_tag_deny_prevents_removal_without_blocking_other_tags(logs_auth, legacy):
- call, create, policy, _, _ = logs_auth
- name = "logs-context-protected"
- arn = create(name, {"protect": "true", "harmless": "yes"})
- action = "UntagLogGroup" if legacy else "UntagResource"
- policy(
- {"Effect": "Allow", "Action": f"logs:{action}", "Resource": "*"},
- {"Effect": "Deny", "Action": f"logs:{action}", "Resource": "*",
- "Condition": {"StringEquals": {"aws:ResourceTag/protect": "true"},
- "ForAnyValue:StringEquals": {"aws:TagKeys": ["protect"]}}},
- )
- target = {"logGroupName": name} if legacy else {"resourceArn": arn}
- field = "tags" if legacy else "tagKeys"
- assert_denied(call(action, **target, **{field: ["harmless", "protect"]}), explicit=True)
- assert call("ListTagsForResource", root=True, resourceArn=arn) == (
- 200, {"tags": {"protect": "true", "harmless": "yes"}},
- )
- assert call(action, **target, **{field: ["harmless"]})[0] == 200
- assert call("ListTagsForResource", root=True, resourceArn=arn) == (200, {"tags": {"protect": "true"}})
-
-
[email protected]("action", ["CreateLogGroup", "TagLogGroup", "TagResource"])
-def test_request_tags_and_keys_use_the_operation_payload(logs_auth, action):
- call, create, policy, _, _ = logs_auth
- name = "logs-context-create"
- arn = f"arn:aws:logs:us-east-1:123456789012:log-group:{name}"
- if action != "CreateLogGroup":
- create(name, {"owner": "team-a"})
- policy({"Effect": "Allow", "Action": f"logs:{action}", "Resource": arn + "*",
- "Condition": {"StringEquals": {"aws:RequestTag/owner": "team-a"},
- "ForAllValues:StringEquals": {"aws:TagKeys": ["owner"]}}})
- target = {"resourceArn": arn} if action == "TagResource" else {"logGroupName": name}
- for tags in ({"owner": "team-b"}, {}, {"owner": "team-a", "extra": "bad"}):
- assert_denied(call(action, **target, tags=tags))
- assert call(action, **target, tags={"owner": "team-a"})[0] == 200
-
-
-def test_modern_tag_actions_enforce_exact_target_arn(logs_auth):
- call, create, policy, _, _ = logs_auth
- allowed = create("logs-context-exact-allow")
- denied = create("logs-context-exact-deny", {"protect": "true"})
- policy({"Effect": "Allow", "Action": ["logs:TagResource", "logs:UntagResource", "logs:ListTagsForResource"],
- "Resource": allowed})
- assert call("TagResource", resourceArn=allowed, tags={"owner": "team-a"})[0] == 200
- assert call("ListTagsForResource", resourceArn=allowed) == (200, {"tags": {"owner": "team-a"}})
- assert call("UntagResource", resourceArn=allowed, tagKeys=["owner"])[0] == 200
- for action, extra in (("TagResource", {"tags": {"owner": "wrong"}}),
- ("UntagResource", {"tagKeys": ["protect"]}), ("ListTagsForResource", {})):
- assert_denied(call(action, resourceArn=denied, logGroupName="logs-context-exact-allow", **extra))
- assert call("ListTagsForResource", root=True, resourceArn=denied) == (200, {"tags": {"protect": "true"}})
-
-
[email protected]("legacy", [False, True])
-def test_incoming_owner_tag_cannot_replace_existing_ownership_context(logs_auth, legacy):
- call, create, policy, _, _ = logs_auth
- name = "logs-context-change-owner"
- arn = create(name, {"owner": "team-b"})
- action = "TagLogGroup" if legacy else "TagResource"
- policy({"Effect": "Allow", "Action": f"logs:{action}", "Resource": "*",
- "Condition": {"StringEquals": {"aws:ResourceTag/owner": "team-a",
- "aws:RequestTag/owner": "team-a"}}})
- target = {"logGroupName": name} if legacy else {"resourceArn": arn}
- assert_denied(call(action, **target, tags={"owner": "team-a"}))
- assert call("ListTagsForResource", root=True, resourceArn=arn) == (200, {"tags": {"owner": "team-b"}})
-
-
-def test_disabled_auth_keeps_logs_tag_calls_permissive(logs_auth, monkeypatch):
- call, create, policy, _, _ = logs_auth
- arn = create("logs-context-auth-disabled", {"protect": "true"})
- policy({"Effect": "Deny", "Action": "logs:*", "Resource": "*"})
- monkeypatch.setattr(app_mod, "AUTH", False)
- assert call("UntagResource", root=True, resourceArn=arn, tagKeys=["protect"])[0] == 200
- assert call("ListTagsForResource", root=True, resourceArn=arn) == (200, {"tags": {}})
-
-
[email protected]("resource_type,store", [
- ("delivery-source", logs._delivery_sources),
- ("delivery-destination", logs._delivery_destinations),
- ("delivery", logs._deliveries),
-])
-def test_modern_tag_context_uses_the_supported_delivery_resource(logs_auth, resource_type, store):
- call, _, policy, account, region = logs_auth
- name = "logs-context-delivery"
- arn = f"arn:aws:logs:{region}:{account}:{resource_type}:{name}"
- store.set_scoped(account, region, name, {"arn": arn, "tags": {"owner": "team-a", "protect": "true"}})
- policy(
- {"Effect": "Allow", "Action": ["logs:ListTagsForResource", "logs:UntagResource"], "Resource": arn,
- "Condition": {"StringEquals": {"aws:ResourceTag/owner": "team-a"}}},
- {"Effect": "Deny", "Action": "logs:UntagResource", "Resource": arn,
- "Condition": {"ForAnyValue:StringEquals": {"aws:TagKeys": ["protect"]}}},
- )
- try:
- assert call("ListTagsForResource", resourceArn=arn) == (
- 200, {"tags": {"owner": "team-a", "protect": "true"}},
- )
- assert_denied(call("UntagResource", resourceArn=arn, tagKeys=["protect"]), explicit=True)
- assert store.get_scoped(account, region, name)["tags"]["protect"] == "true"
- finally:
- store.pop_scoped(account, region, name, None)
-
-
-def test_owner_context_is_scoped_to_resource_account_and_region(logs_auth):
- call, create, policy, account, region = logs_auth
- name = "logs-context-scope"
- local = create(name, {"owner": "team-a"})
- remote_region = create(name, {"owner": "team-b"}, request_region="us-west-2")
- logs._log_groups.set_scoped("111111111111", region, name, {
- "arn": f"arn:aws:logs:{region}:111111111111:log-group:{name}:*", "tags": {"owner": "team-a"},
- })
- policy({"Effect": "Allow", "Action": "logs:ListTagsForResource", "Resource": "*",
- "Condition": {"StringEquals": {"aws:ResourceTag/owner": "team-a"}}})
- try:
- assert call("ListTagsForResource", resourceArn=local)[0] == 200
- assert_denied(call("ListTagsForResource", resourceArn=remote_region, request_region="us-west-2"))
- for invalid in (remote_region, local.replace(account, "111111111111")):
- assert call("ListTagsForResource", resourceArn=invalid) == (
- 400, {"__type": "ValidationException", "message": "Invalid resourceArn"},
- )
- finally:
- logs._log_groups.pop_scoped("111111111111", region, name, None)
-
-
[email protected]("auth", [False, True])
[email protected]("resource_type,store", [
- ("log-group", logs._log_groups),
- ("delivery-source", logs._delivery_sources),
- ("delivery-destination", logs._delivery_destinations),
- ("delivery", logs._deliveries),
-])
-def test_modern_tag_actions_reject_aliases_to_unrelated_arns(
- logs_auth, monkeypatch, auth, resource_type, store):
- call, create, policy, account, region = logs_auth
- name = "logs-context-resolver"
- tags = {"owner": "team-a", "protect": "true"}
- arn = f"arn:aws:logs:{region}:{account}:{resource_type}:{name}"
- if resource_type == "log-group":
- create(name, tags)
- else:
- store.set_scoped(account, region, name, {"arn": arn, "tags": dict(tags)})
- monkeypatch.setattr(app_mod, "AUTH", auth)
- invalid_arns = [
- arn.replace(account, "111111111111"),
- arn.replace(region, "us-west-2"),
- arn.replace(":logs:", ":s3:"),
- arn.replace("arn:aws:", "arn:aws-cn:"),
- arn + ":**" if resource_type == "log-group" else arn.replace(
- f":{resource_type}:", f":{resource_type}:other:"),
- ]
- if resource_type == "log-group":
- invalid_arns.append(arn + ":*")
- try:
- for invalid in invalid_arns:
- # Permission on the supplied ARN must never authorize a mutation
- # or a read of the same-named local resource.
- policy({"Effect": "Allow", "Action": "logs:*", "Resource": invalid})
- for action, extra in (
- ("TagResource", {"tags": {"protect": "false"}}),
- ("UntagResource", {"tagKeys": ["protect"]}),
- ("ListTagsForResource", {}),
- ):
- assert call(action, root=not auth, resourceArn=invalid, **extra) == (
- 400, {"__type": "ValidationException", "message": "Invalid resourceArn"},
- )
- assert store.get_scoped(account, region, name)["tags"] == tags
- finally:
- if resource_type != "log-group":
- store.pop_scoped(account, region, name, None)
-
-
-def test_invalid_tag_arn_precedes_policy_denial_but_preserves_credential_errors(logs_auth):
- call, create, policy, account, _ = logs_auth
- arn = create("logs-context-validation", {"protect": "true"})
- policy({"Effect": "Deny", "Action": "logs:*", "Resource": "*"})
- status, body, headers = call("UntagResource", resourceArn=arn + ":*",
- tagKeys=["protect"], with_headers=True)
- assert (status, body) == (400, {"__type": "ValidationException", "message": "Invalid resourceArn"})
- assert headers[b"content-type"] == b"application/x-amz-json-1.1"
- assert b"x-amzn-errortype" not in headers
- iam._access_keys.get_scoped(account, None, "AKIALOGSTAGCONTEXT")["Status"] = "Inactive"
- status, body = call("UntagResource", resourceArn=arn + ":*", tagKeys=["protect"])
- assert status == 403 and body["__type"] == "InvalidClientTokenId"
-
-
[email protected]("auth", [False, True])
-def test_tag_arn_validation_preserves_malformed_json_error(logs_auth, monkeypatch, auth):
- call, _, _, _, _ = logs_auth
- monkeypatch.setattr(app_mod, "AUTH", auth)
- for action in ("TagResource", "UntagResource", "ListTagsForResource"):
- assert call(action, root=True, raw_body=b"{") == (
- 400, {"__type": "SerializationException", "message": "Invalid JSON"},
- )
diff --git a/tests/test_ministack.py b/tests/test_ministack.py
index d63a8b14..a131bc42 100644
--- a/tests/test_ministack.py
+++ b/tests/test_ministack.py
@@ -807,6 +807,47 @@ def test_boot_sweep_takes_our_predecessor_but_spares_other_instances(fake_docker
assert "another-instance" in fake_docker.live(), "boot sweep destroyed another instance's container"
+def test_boot_sweep_survives_one_container_whose_inspect_fails(fake_docker, monkeypatch):
+ """A full listing inspects every container, so one failed inspect used to cost the whole sweep."""
+ from ministack.core import container_reaper
+
+ monkeypatch.setenv("GATEWAY_PORT", "4566")
+ monkeypatch.setattr(container_reaper, "_boot_nonce", "run-1")
+ for name in ("left-1", "left-2", "left-3"):
+ _exited_container(fake_docker, container_reaper, name, db_id=name)
+ full_list = fake_docker.containers.list
+
+ def listing(all=False, filters=None, sparse=False):
+ if not sparse:
+ raise RuntimeError("inspect of left-2 failed")
+ return full_list(all=all, filters=filters, sparse=sparse)
+
+ monkeypatch.setattr(fake_docker.containers, "list", listing)
+ monkeypatch.setattr(container_reaper, "_boot_nonce", "run-2")
+ assert container_reaper.reap_all(fake_docker, include_unlabelled=True) == 3
+ assert fake_docker.live() == []
+
+
+def test_periodic_reaper_skips_only_the_container_it_cannot_inspect(fake_docker, monkeypatch):
+ from ministack.core import container_reaper
+
+ monkeypatch.setattr(container_reaper, "EXITED_GRACE", 0)
+ monkeypatch.setenv("GATEWAY_PORT", "4566")
+ monkeypatch.setattr(container_reaper, "_boot_nonce", "nonce-mine")
+ for name in ("gone-1", "broken", "gone-2"):
+ _exited_container(fake_docker, container_reaper, name, db_id=name)
+
+ def failing_reload():
+ raise RuntimeError("inspect failed")
+
+ monkeypatch.setattr(fake_docker.containers.get("broken"), "reload", failing_reload)
+ container_reaper.register_live_ids("rds", lambda: [])
+ assert container_reaper.reap_abandoned(fake_docker) == 2
+ assert fake_docker.live() == ["broken"]
+
+
def test_persistence_keeps_state_when_a_module_fails_to_load():
"""A service that could not import must not overwrite its persisted state.
diff --git a/tests/test_ses.py b/tests/test_ses.py
index 7f78855a..96b2f524 100644
--- a/tests/test_ses.py
+++ b/tests/test_ses.py
@@ -1,13 +1,29 @@
"""SES tests — API operations + SMTP relay integration."""
+import asyncio
import json
import os
import time
import uuid as _uuid_mod
+from datetime import datetime
from unittest.mock import MagicMock, patch
+from urllib.parse import urlencode
+from uuid import uuid4
import pytest
+from botocore import UNSIGNED
from botocore.exceptions import ClientError
+from botocore.parsers import create_parser
+from botocore.serialize import create_serializer
+from botocore.session import Session
+
+from ministack.core import persistence
+from ministack.core.responses import (
+ AccountRegionScopedDict,
+ set_request_account_id,
+ set_request_region,
+)
+from ministack.services import ses as _ses_svc
def test_ses_parse_smtp_host_not_set():
@@ -1127,6 +1143,393 @@ def test_ses_send_from_an_unverified_sender_is_rejected():
assert exc.value.response["Error"]["Code"] == "MessageRejected"
+# ── Receipt rules ──
+def receipt_api(monkeypatch):
+ # Private stores keep in-process reset/persistence tests independent of the
+ # running integration server and other services' fixtures on this worker.
+ for name in (
+ "_identities", "_sent_emails", "_templates", "_configuration_sets",
+ "_account_details", "_receipt_rule_sets", "_active_receipt_rule_set",
+ ):
+ monkeypatch.setattr(_ses_svc, name, AccountRegionScopedDict())
+ model = Session().get_service_model("ses")
+ # Exercise service-side required-field errors instead of SDK validation.
+ serializer = create_serializer("query", include_validation=False)
+ parser = create_parser("query")
+
+ def call(action, **params):
+ operation = model.operation_model(action)
+ request = serializer.serialize_to_request(params, operation)
+ status, headers, body = asyncio.run(_ses_svc.handle_request(
+ "POST", "/", {}, urlencode(request["body"]).encode(), {}
+ ))
+ result = parser.parse(
+ {"status_code": status, "headers": headers, "body": body},
+ operation.output_shape,
+ )
+ if status >= 400:
+ raise ClientError(result, action)
+ assert status == 200
+ return {key: value for key, value in result.items() if key != "ResponseMetadata"}
+
+ return call
+
+
+def assert_error(api, action, code, message, **params):
+ with pytest.raises(ClientError) as exc:
+ api(action, **params)
+ response = exc.value.response
+ assert response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert response["Error"] == {"Code": code, "Message": message, "Type": "Sender"}
+
+
+def test_receipt_rule_set_and_rule_lifecycle(receipt_api):
+ api = receipt_api
+ assert api("DescribeActiveReceiptRuleSet") == {}
+ api("CreateReceiptRuleSet", RuleSetName="set.with-periods")
+ empty = api("DescribeReceiptRuleSet", RuleSetName="set.with-periods")
+ assert empty["Metadata"]["Name"] == "set.with-periods"
+ assert isinstance(empty["Metadata"]["CreatedTimestamp"], datetime)
+ assert empty["Rules"] == []
+ assert api("ListReceiptRuleSets")["RuleSets"] == [empty["Metadata"]]
+
+ api("CreateReceiptRule", RuleSetName="set.with-periods", Rule={"Name": "first"})
+ assert api("DescribeReceiptRule", RuleSetName="set.with-periods", RuleName="first")["Rule"] == {
+ "Name": "first", "Enabled": False, "ScanEnabled": False,
+ "TlsPolicy": "Optional", "Actions": [],
+ }
+ rule = {
+ "Name": "second", "Enabled": True, "ScanEnabled": True,
+ "TlsPolicy": "Require", "Recipients": ["EXAMPLE.COM", "[email protected]", ".EXAMPLE.COM", "foo.example-test.com"],
+ "Actions": [
+ {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "value<&"}},
+ {"StopAction": {"Scope": "RuleSet"}},
+ ],
+ }
+ api("CreateReceiptRule", RuleSetName="set.with-periods", Rule=rule)
+ rule["Recipients"] = [".example.com", "example.com", "foo.example-test.com", "[email protected]"]
+ assert api("DescribeReceiptRule", RuleSetName="set.with-periods", RuleName="second")["Rule"] == rule
+ api("CreateReceiptRule", RuleSetName="set.with-periods", After="second", Rule={"Name": "third"})
+ described = api("DescribeReceiptRuleSet", RuleSetName="set.with-periods")
+ assert [r["Name"] for r in described["Rules"]] == ["second", "third", "first"]
+ api("SetActiveReceiptRuleSet", RuleSetName="set.with-periods")
+ assert api("DescribeActiveReceiptRuleSet") == described
+ assert_error(api, "DeleteReceiptRuleSet", "CannotDelete",
+ "Cannot delete active rule set: set.with-periods", RuleSetName="set.with-periods")
+ api("DeleteReceiptRule", RuleSetName="set.with-periods", RuleName="third")
+ assert [r["Name"] for r in api("DescribeActiveReceiptRuleSet")["Rules"]] == ["second", "first"]
+ api("SetActiveReceiptRuleSet")
+ assert api("DescribeActiveReceiptRuleSet") == {}
+ api("DeleteReceiptRuleSet", RuleSetName="set.with-periods")
+ api("DeleteReceiptRuleSet", RuleSetName="set.with-periods")
+ assert api("ListReceiptRuleSets") == {"RuleSets": []}
+
+
+def test_receipt_duplicate_and_missing_resource_errors_leave_order_unchanged(receipt_api):
+ api = receipt_api
+ for action, params in (
+ ("DescribeReceiptRuleSet", {}), ("SetActiveReceiptRuleSet", {}),
+ ("CreateReceiptRule", {"Rule": {"Name": "first"}}),
+ ("DescribeReceiptRule", {"RuleName": "first"}),
+ ("DeleteReceiptRule", {"RuleName": "first"}),
+ ):
+ assert_error(api, action, "RuleSetDoesNotExist", "Rule set does not exist: missing",
+ RuleSetName="missing", **params)
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ assert_error(api, "CreateReceiptRuleSet", "AlreadyExists", "Rule set already exists: rules",
+ RuleSetName="rules")
+ api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "first"})
+ assert_error(api, "CreateReceiptRule", "AlreadyExists", "Rule already exists: first",
+ RuleSetName="rules", Rule={"Name": "first"}, After="missing")
+ assert_error(api, "CreateReceiptRule", "RuleDoesNotExist", "Rule does not exist: missing",
+ RuleSetName="rules", Rule={"Name": "second"}, After="missing")
+ assert_error(api, "DescribeReceiptRule", "RuleDoesNotExist", "Rule does not exist: missing",
+ RuleSetName="rules", RuleName="missing")
+ api("DeleteReceiptRule", RuleSetName="rules", RuleName="missing")
+ assert [r["Name"] for r in api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"]] == ["first"]
+ assert_error(api, "ListReceiptRuleSets", "InvalidParameterValue", "Invalid token: invalid", NextToken="invalid")
+
+
[email protected]("name", ["-bad", "bad-", "a" * 65])
+def test_receipt_invalid_names(receipt_api, name):
+ api = receipt_api
+ assert_error(api, "CreateReceiptRuleSet", "InvalidParameterValue",
+ f"Not a valid ruleSetName: {name}", RuleSetName=name)
+ # AWS validates rule metadata before looking up the parent rule set.
+ assert_error(api, "CreateReceiptRule", "InvalidParameterValue",
+ f"Not a valid ruleName: {name}", RuleSetName="missing", Rule={"Name": name})
+ assert api("ListReceiptRuleSets") == {"RuleSets": []}
+
+
[email protected]("name", ["-bad", "bad-", "a" * 65])
[email protected]("action,params,field", [
+ ("DescribeReceiptRuleSet", {}, "ruleSetName"),
+ ("DeleteReceiptRuleSet", {}, "ruleSetName"),
+ ("SetActiveReceiptRuleSet", {}, "ruleSetName"),
+ ("CreateReceiptRule", {"Rule": {"Name": "valid"}}, "ruleSetName"),
+ ("DescribeReceiptRule", {"RuleName": "valid"}, "ruleSetName"),
+ ("DeleteReceiptRule", {"RuleName": "valid"}, "ruleSetName"),
+ ("DescribeReceiptRule", {"RuleSetName": "rules"}, "ruleName"),
+ ("DeleteReceiptRule", {"RuleSetName": "rules"}, "ruleName"),
+])
+def test_receipt_lookup_delete_and_activation_validate_names(receipt_api, name, action, params, field):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "valid"})
+ api("SetActiveReceiptRuleSet", RuleSetName="rules")
+ before = api("DescribeActiveReceiptRuleSet")
+ key = "RuleSetName" if field == "ruleSetName" else "RuleName"
+ assert_error(api, action, "InvalidParameterValue",
+ f"Not a valid {field}: {name}", **{**params, key: name})
+ assert api("DescribeActiveReceiptRuleSet") == before
+ assert api("ListReceiptRuleSets")["RuleSets"] == [before["Metadata"]]
+
+
[email protected]("action,params", [
+ ("CreateReceiptRuleSet", {}),
+ ("DescribeReceiptRuleSet", {}),
+ ("DeleteReceiptRuleSet", {}),
+ ("CreateReceiptRule", {"Rule": {"Name": "valid"}}),
+ ("DescribeReceiptRule", {"RuleName": "valid"}),
+ ("DeleteReceiptRule", {"RuleName": "valid"}),
+])
+def test_receipt_missing_rule_set_name_error(receipt_api, action, params):
+ assert_error(receipt_api, action, "ValidationError",
+ "1 validation error detected: Value at 'ruleSetName' failed to satisfy constraint: Member must not be null",
+ **params)
+ assert receipt_api("ListReceiptRuleSets") == {"RuleSets": []}
+
+
[email protected]("action,params,field", [
+ ("CreateReceiptRule", {}, "rule"),
+ ("CreateReceiptRule", {"Rule": {}}, "rule"),
+ ("CreateReceiptRule", {"Rule": {"Enabled": True}}, "rule.name"),
+ ("DescribeReceiptRule", {}, "ruleName"),
+ ("DeleteReceiptRule", {}, "ruleName"),
+])
+def test_receipt_missing_rule_fields_error(receipt_api, action, params, field):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ assert_error(api, action, "ValidationError",
+ f"1 validation error detected: Value at '{field}' failed to satisfy constraint: Member must not be null",
+ RuleSetName="rules", **params)
+ assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"] == []
+
+
[email protected]("recipients", [
+])
+def test_receipt_empty_recipient_is_rejected_without_creating_a_rule(receipt_api, recipients):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ assert_error(api, "CreateReceiptRule", "InvalidParameterValue", "Invalid recipient: ",
+ RuleSetName="rules", Rule={"Name": "invalid", "Recipients": recipients})
+ assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"] == []
+
+
[email protected]("value", ["a\tb", "café 雪 😀 <&>"])
+def test_receipt_header_tab_and_unicode_round_trip(receipt_api, value):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ actions = [{"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": value}}]
+ api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "header", "Actions": actions})
+ api("SetActiveReceiptRuleSet", RuleSetName="rules")
+ assert api("DescribeReceiptRule", RuleSetName="rules", RuleName="header")["Rule"]["Actions"] == actions
+ assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"][0]["Actions"] == actions
+ assert api("DescribeActiveReceiptRuleSet")["Rules"][0]["Actions"] == actions
+
+
+def test_receipt_nul_header_is_created_but_readback_fails_until_deleted(receipt_api):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "valid"})
+ api("SetActiveReceiptRuleSet", RuleSetName="rules")
+ before = api("DescribeActiveReceiptRuleSet")
+ assert api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "broken", "Actions": [
+ {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "a\x00b"}},
+ ]}) == {}
+ for action, params in (
+ ("DescribeReceiptRule", {"RuleSetName": "rules", "RuleName": "broken"}),
+ ("DescribeReceiptRuleSet", {"RuleSetName": "rules"}),
+ ("DescribeActiveReceiptRuleSet", {}),
+ ):
+ with pytest.raises(ClientError) as exc:
+ api(action, **params)
+ response = exc.value.response
+ assert response["ResponseMetadata"]["HTTPStatusCode"] == 500
+ assert response["Error"] == {"Type": "Receiver", "Code": "InternalFailure"}
+ assert api("DescribeReceiptRule", RuleSetName="rules", RuleName="valid")["Rule"] == before["Rules"][0]
+ assert api("ListReceiptRuleSets")["RuleSets"] == [before["Metadata"]]
+ api("DeleteReceiptRule", RuleSetName="rules", RuleName="broken")
+ assert api("DescribeReceiptRuleSet", RuleSetName="rules") == before
+ assert api("DescribeActiveReceiptRuleSet") == before
+
+
[email protected]("rule,code,message", [
+ ({"Name": "tls", "TlsPolicy": "Invalid"}, "ValidationError",
+ "1 validation error detected: Value at 'rule.tlsPolicy' failed to satisfy constraint: Member must satisfy enum value set: [Optional, Require]"),
+ ({"Name": "recipient", "Recipients": ["not valid"]}, "InvalidParameterValue", "Invalid recipient: not valid"),
+ ({"Name": "scope", "Actions": [{"StopAction": {"Scope": "Invalid"}}]}, "ValidationError",
+ "1 validation error detected: Value at 'rule.actions.1.member.stopAction.scope' failed to satisfy constraint: Member must satisfy enum value set: [RuleSet]"),
+ ({"Name": "ordering", "Actions": [{"StopAction": {"Scope": "RuleSet"}},
+ {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "ok"}}]}, "InvalidParameterValue",
+ "Stop action, if any, must be placed at the end of the actions list"),
+ ({"Name": "multiple", "Actions": [{"StopAction": {"Scope": "RuleSet"},
+ "AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "ok"}}]}, "InvalidParameterValue",
+ "Exactly one action type must be specified for each ReceiptAction"),
+ ({"Name": "header", "Actions": [{"AddHeaderAction": {"HeaderName": "X bad", "HeaderValue": "ok"}}]},
+ "InvalidParameterValue", "Invalid header name: X bad"),
+ ({"Name": "newline", "Actions": [{"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "a\nb"}}]},
+ "InvalidParameterValue", "Invalid header value: a0x000ab"),
+])
+def test_receipt_invalid_rule_metadata_is_atomic(receipt_api, rule, code, message):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ assert_error(api, "CreateReceiptRule", code, message, RuleSetName="rules", Rule=rule)
+ assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"] == []
+
+
[email protected]("header,missing", [
+ ({"HeaderName": "X-Test"}, "headerValue"),
+ ({"HeaderValue": "value"}, "headerName"),
+])
+def test_receipt_missing_header_fields_are_rejected_without_creating_a_rule(receipt_api, header, missing):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ assert_error(api, "CreateReceiptRule", "ValidationError",
+ f"1 validation error detected: Value at 'rule.actions.1.member.addHeaderAction.{missing}' failed to satisfy constraint: Member must not be null",
+ RuleSetName="rules", Rule={"Name": "missing", "Actions": [{"AddHeaderAction": header}]})
+ assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"] == []
+
+
[email protected]("recipient", [
+ "example..com", "example.-com", "example-.com", "foo..example.com",
+ "foo.-example.com", "foo.example-.com", "example.com-",
+])
+def test_receipt_invalid_domain_labels_are_rejected_without_creating_a_rule(receipt_api, recipient):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ assert_error(api, "CreateReceiptRule", "InvalidParameterValue", f"Invalid recipient: {recipient}",
+ RuleSetName="rules", Rule={"Name": "invalid", "Recipients": [recipient]})
+ assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"] == []
+
+
+def test_receipt_recipients_are_lowercased_deduplicated_and_sorted(receipt_api):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "recipients", "Recipients": [
+ "example.com", ".EXAMPLE.COM", ".example.com",
+ ]})
+ recipients = [".example.com", "[email protected]", "example.com", "[email protected]"]
+ assert api("DescribeReceiptRule", RuleSetName="rules", RuleName="recipients")["Rule"]["Recipients"] == recipients
+ assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"][0]["Recipients"] == recipients
+
+
[email protected]("action", [
+ {"S3Action": {"BucketName": "bucket"}},
+ {"SNSAction": {"TopicArn": "arn:aws:sns:us-east-1:111111111111:topic"}},
+ {"LambdaAction": {"FunctionArn": "arn:aws:lambda:us-east-1:111111111111:function:test"}},
+ {"BounceAction": {"SmtpReplyCode": "550", "Message": "no", "Sender": "[email protected]"}},
+ {"WorkmailAction": {"OrganizationArn": "arn:aws:workmail:us-east-1:111111111111:organization/m-test"}},
+ {"ConnectAction": {"InstanceARN": "arn:aws:connect:us-east-1:111111111111:instance/test",
+ "IAMRoleARN": "arn:aws:iam::111111111111:role/test"}},
+ {"StopAction": {"Scope": "RuleSet", "TopicArn": "arn:aws:sns:us-east-1:111111111111:topic"}},
+])
+def test_receipt_every_action_type_is_stored(receipt_api, action):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "rule", "Actions": [action]})
+ assert api("DescribeReceiptRule", RuleSetName="rules", RuleName="rule")["Rule"]["Actions"] == [action]
+
+
+def test_receipt_explicit_empty_fields_are_preserved_and_after_is_validated(receipt_api):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "empty", "Recipients": [], "Actions": [{}]})
+ assert api("DescribeReceiptRule", RuleSetName="rules", RuleName="empty")["Rule"]["Recipients"] == []
+ for name, action in (("empty-stop", {"StopAction": {}}), ("empty-header", {"AddHeaderAction": {}})):
+ api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": name, "Actions": [action]})
+ assert api("DescribeReceiptRule", RuleSetName="rules", RuleName=name)["Rule"]["Actions"] == []
+ api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "header", "Actions": [
+ {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": ""}},
+ ]})
+ assert api("DescribeReceiptRule", RuleSetName="rules", RuleName="header")["Rule"]["Actions"] == [
+ {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": ""}},
+ ]
+ assert_error(api, "CreateReceiptRule", "ValidationError",
+ "2 validation errors detected: Value at 'after' failed to satisfy constraint: Member must have length greater than or equal to 1; Value at 'after' failed to satisfy constraint: Member must satisfy regular expression pattern: ^[a-zA-Z0-9_.-]+$",
+ RuleSetName="rules", After="", Rule={"Name": "after"})
+
+
+def test_receipt_metadata_and_active_selection_survive_all_tenant_persistence_and_reset(receipt_api, monkeypatch, tmp_path):
+ api = receipt_api
+ scopes = [("111111111111", "us-east-1"), ("111111111111", "us-west-2"), ("222222222222", "us-east-1")]
+ expected = {}
+ for i, (account, region) in enumerate(scopes):
+ set_request_account_id(account)
+ set_request_region(region)
+ assert api("ListReceiptRuleSets") == {"RuleSets": []}
+ api("CreateReceiptRuleSet", RuleSetName="same-name")
+ api("CreateReceiptRule", RuleSetName="same-name", Rule={"Name": f"rule-{i}"})
+ api("SetActiveReceiptRuleSet", RuleSetName="same-name")
+ expected[account, region] = api("DescribeActiveReceiptRuleSet")
+ snapshot = _ses_svc.get_state()
+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)
+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))
+ persistence.save_state("ses", snapshot)
+ _ses_svc.reset()
+ for account, region in scopes:
+ set_request_account_id(account)
+ set_request_region(region)
+ assert api("ListReceiptRuleSets") == {"RuleSets": []}
+ assert api("DescribeActiveReceiptRuleSet") == {}
+ _ses_svc.load_persisted_state(persistence.load_state("ses"))
+ for account, region in scopes:
+ set_request_account_id(account)
+ set_request_region(region)
+ assert api("DescribeActiveReceiptRuleSet") == expected[account, region]
+ api("SetActiveReceiptRuleSet")
+ api("DeleteReceiptRuleSet", RuleSetName="same-name")
+ set_request_account_id(scopes[0][0])
+ set_request_region(scopes[0][1])
+ assert api("DescribeActiveReceiptRuleSet") == expected[scopes[0]]
+ assert snapshot["_receipt_rule_sets"].get_scoped(*scopes[-1], "same-name")["Rules"]
+
+
+def test_receipt_unsigned_sdk_lifecycle():
+ # The endpoint comes from conftest so this uses the same isolated local
+ # server as the integration suite. Activation changes shared server state.
+ from conftest import make_client
+
+ client = make_client("ses", additional_config_kwargs={"signature_version": UNSIGNED})
+ name = f"unsigned-receipts-{uuid4().hex[:12]}"
+ previous = client.describe_active_receipt_rule_set().get("Metadata", {}).get("Name")
+ client.create_receipt_rule_set(RuleSetName=name)
+ try:
+ assert name in {item["Name"] for item in client.list_receipt_rule_sets()["RuleSets"]}
+ client.create_receipt_rule(RuleSetName=name, Rule={"Name": "first"})
+ client.create_receipt_rule(RuleSetName=name, After="first", Rule={"Name": "second", "Actions": [
+ {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "value<&"}},
+ {"StopAction": {"Scope": "RuleSet"}},
+ ]})
+ described = client.describe_receipt_rule_set(RuleSetName=name)
+ assert [rule["Name"] for rule in described["Rules"]] == ["first", "second"]
+ assert client.describe_receipt_rule(RuleSetName=name, RuleName="second")["Rule"] == described["Rules"][1]
+ client.set_active_receipt_rule_set(RuleSetName=name)
+ active = client.describe_active_receipt_rule_set()
+ assert active["Metadata"] == described["Metadata"]
+ assert active["Rules"] == described["Rules"]
+ client.delete_receipt_rule(RuleSetName=name, RuleName="second")
+ assert [rule["Name"] for rule in client.describe_active_receipt_rule_set()["Rules"]] == ["first"]
+ finally:
+ client.set_active_receipt_rule_set(**({"RuleSetName": previous} if previous else {}))
+ client.delete_receipt_rule_set(RuleSetName=name)
+ assert name not in {item["Name"] for item in client.list_receipt_rule_sets()["RuleSets"]}
@pytest.fixture
def ses_notify_queue(ses, sns, sqs):
"""An SNS topic subscribed by an SQS queue, plus a `drain(n)` collector of the
@@ -1178,19 +1581,26 @@ def test_ses_identity_notifications_published_to_sns_sqs(ses, ses_notify_queue):
bind(sender)
msg_id = ses.send_email(
- Source=sender, Destination={"ToAddresses": dest}, Message=_NOTIFY_MSG,
+ Source=f'"Notify" <{sender}>', Destination={"ToAddresses": dest}, Message=_NOTIFY_MSG,
)["MessageId"]
- got = {n["notificationType"]: n for n in drain(3)}
- assert set(got) == {"Delivery", "Bounce", "Complaint"}
- assert got["Delivery"]["mail"]["messageId"] == msg_id
- assert got["Delivery"]["mail"]["source"] == sender
- assert got["Delivery"]["mail"]["destination"] == dest
- assert got["Delivery"]["delivery"]["recipients"] == ["[email protected]"]
- assert got["Bounce"]["bounce"]["bouncedRecipients"][0]["emailAddress"] == dest[1]
- assert got["Complaint"]["complaint"]["complainedRecipients"][0]["emailAddress"] == dest[2]
+ got = drain(5)
+ by_kind = {}
+ for n in got:
+ by_kind.setdefault(n["notificationType"], []).append(n)
+ # complaint@ is delivered before it is marked as spam; suppressionlist@ is a suppressed hard bounce.
+ assert sorted(r for n in by_kind["Delivery"] for r in n["delivery"]["recipients"]) == [dest[2], dest[0]]
+ bounces = {n["bounce"]["bouncedRecipients"][0]["emailAddress"]: n["bounce"] for n in by_kind["Bounce"]}
+ assert (bounces[dest[1]]["bounceType"], bounces[dest[1]]["bounceSubType"]) == ("Permanent", "General")
+ assert (bounces[dest[3]]["bounceType"], bounces[dest[3]]["bounceSubType"]) == ("Permanent", "Suppressed")
+ assert [n["complaint"]["complainedRecipients"][0]["emailAddress"] for n in by_kind["Complaint"]] == [dest[2]]
+ mail = got[0]["mail"]
+ assert mail["messageId"] == msg_id
+ assert mail["source"] == sender
+ assert mail["sourceArn"].endswith(f":identity/{sender}")
+ assert mail["destination"] == dest
def test_ses_identity_notifications_fall_back_to_domain_identity(ses, ses_notify_queue):
@@ -1206,6 +1616,7 @@ def test_ses_identity_notifications_fall_back_to_domain_identity(ses, ses_notify
got = drain(1)
assert [n["mail"]["messageId"] for n in got if n["notificationType"] == "Delivery"] == [msg_id]
+ assert got[0]["mail"]["sourceArn"].endswith(f":identity/{domain}")
def test_ses_identity_notifications_simulator_subaddress(ses, ses_notify_queue):
diff --git a/tests/test_ses_receipts.py b/tests/test_ses_receipts.py
deleted file mode 100644
index f2e8c74f..00000000
--- a/tests/test_ses_receipts.py
+++ /dev/null
@@ -1,417 +0,0 @@
-# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
-"""SES receipt metadata through the SDK's Query serializer and XML parser."""
-
-import asyncio
-from datetime import datetime
-from urllib.parse import urlencode
-from uuid import uuid4
-
-import pytest
-from botocore import UNSIGNED
-from botocore.exceptions import ClientError
-from botocore.parsers import create_parser
-from botocore.serialize import create_serializer
-from botocore.session import Session
-
-from ministack.core import persistence
-from ministack.core.responses import (
- AccountRegionScopedDict,
- set_request_account_id,
- set_request_region,
-)
-from ministack.services import ses
-
-
-def receipt_api(monkeypatch):
- # Private stores keep in-process reset/persistence tests independent of the
- # running integration server and other services' fixtures on this worker.
- for name in (
- "_identities", "_sent_emails", "_templates", "_configuration_sets",
- "_account_details", "_receipt_rule_sets", "_active_receipt_rule_set",
- ):
- monkeypatch.setattr(ses, name, AccountRegionScopedDict())
- model = Session().get_service_model("ses")
- # Exercise service-side required-field errors instead of SDK validation.
- serializer = create_serializer("query", include_validation=False)
- parser = create_parser("query")
-
- def call(action, **params):
- operation = model.operation_model(action)
- request = serializer.serialize_to_request(params, operation)
- status, headers, body = asyncio.run(ses.handle_request(
- "POST", "/", {}, urlencode(request["body"]).encode(), {}
- ))
- result = parser.parse(
- {"status_code": status, "headers": headers, "body": body},
- operation.output_shape,
- )
- if status >= 400:
- raise ClientError(result, action)
- assert status == 200
- return {key: value for key, value in result.items() if key != "ResponseMetadata"}
-
- return call
-
-
-def assert_error(api, action, code, message, **params):
- with pytest.raises(ClientError) as exc:
- api(action, **params)
- response = exc.value.response
- assert response["ResponseMetadata"]["HTTPStatusCode"] == 400
- assert response["Error"] == {"Code": code, "Message": message, "Type": "Sender"}
-
-
-def test_receipt_rule_set_and_rule_lifecycle(receipt_api):
- api = receipt_api
- assert api("DescribeActiveReceiptRuleSet") == {}
- api("CreateReceiptRuleSet", RuleSetName="set.with-periods")
- empty = api("DescribeReceiptRuleSet", RuleSetName="set.with-periods")
- assert empty["Metadata"]["Name"] == "set.with-periods"
- assert isinstance(empty["Metadata"]["CreatedTimestamp"], datetime)
- assert empty["Rules"] == []
- assert api("ListReceiptRuleSets")["RuleSets"] == [empty["Metadata"]]
-
- api("CreateReceiptRule", RuleSetName="set.with-periods", Rule={"Name": "first"})
- assert api("DescribeReceiptRule", RuleSetName="set.with-periods", RuleName="first")["Rule"] == {
- "Name": "first", "Enabled": False, "ScanEnabled": False,
- "TlsPolicy": "Optional", "Actions": [],
- }
- rule = {
- "Name": "second", "Enabled": True, "ScanEnabled": True,
- "TlsPolicy": "Require", "Recipients": ["EXAMPLE.COM", "[email protected]", ".EXAMPLE.COM", "foo.example-test.com"],
- "Actions": [
- {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "value<&"}},
- {"StopAction": {"Scope": "RuleSet"}},
- ],
- }
- api("CreateReceiptRule", RuleSetName="set.with-periods", Rule=rule)
- rule["Recipients"] = [".example.com", "example.com", "foo.example-test.com", "[email protected]"]
- assert api("DescribeReceiptRule", RuleSetName="set.with-periods", RuleName="second")["Rule"] == rule
- api("CreateReceiptRule", RuleSetName="set.with-periods", After="second", Rule={"Name": "third"})
- described = api("DescribeReceiptRuleSet", RuleSetName="set.with-periods")
- assert [r["Name"] for r in described["Rules"]] == ["second", "third", "first"]
- api("SetActiveReceiptRuleSet", RuleSetName="set.with-periods")
- assert api("DescribeActiveReceiptRuleSet") == described
- assert_error(api, "DeleteReceiptRuleSet", "CannotDelete",
- "Cannot delete active rule set: set.with-periods", RuleSetName="set.with-periods")
- api("DeleteReceiptRule", RuleSetName="set.with-periods", RuleName="third")
- assert [r["Name"] for r in api("DescribeActiveReceiptRuleSet")["Rules"]] == ["second", "first"]
- api("SetActiveReceiptRuleSet")
- assert api("DescribeActiveReceiptRuleSet") == {}
- api("DeleteReceiptRuleSet", RuleSetName="set.with-periods")
- api("DeleteReceiptRuleSet", RuleSetName="set.with-periods")
- assert api("ListReceiptRuleSets") == {"RuleSets": []}
-
-
-def test_receipt_duplicate_and_missing_resource_errors_leave_order_unchanged(receipt_api):
- api = receipt_api
- for action, params in (
- ("DescribeReceiptRuleSet", {}), ("SetActiveReceiptRuleSet", {}),
- ("CreateReceiptRule", {"Rule": {"Name": "first"}}),
- ("DescribeReceiptRule", {"RuleName": "first"}),
- ("DeleteReceiptRule", {"RuleName": "first"}),
- ):
- assert_error(api, action, "RuleSetDoesNotExist", "Rule set does not exist: missing",
- RuleSetName="missing", **params)
- api("CreateReceiptRuleSet", RuleSetName="rules")
- assert_error(api, "CreateReceiptRuleSet", "AlreadyExists", "Rule set already exists: rules",
- RuleSetName="rules")
- api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "first"})
- assert_error(api, "CreateReceiptRule", "AlreadyExists", "Rule already exists: first",
- RuleSetName="rules", Rule={"Name": "first"}, After="missing")
- assert_error(api, "CreateReceiptRule", "RuleDoesNotExist", "Rule does not exist: missing",
- RuleSetName="rules", Rule={"Name": "second"}, After="missing")
- assert_error(api, "DescribeReceiptRule", "RuleDoesNotExist", "Rule does not exist: missing",
- RuleSetName="rules", RuleName="missing")
- api("DeleteReceiptRule", RuleSetName="rules", RuleName="missing")
- assert [r["Name"] for r in api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"]] == ["first"]
- assert_error(api, "ListReceiptRuleSets", "InvalidParameterValue", "Invalid token: invalid", NextToken="invalid")
-
-
[email protected]("name", ["-bad", "bad-", "a" * 65])
-def test_receipt_invalid_names(receipt_api, name):
- api = receipt_api
- assert_error(api, "CreateReceiptRuleSet", "InvalidParameterValue",
- f"Not a valid ruleSetName: {name}", RuleSetName=name)
- # AWS validates rule metadata before looking up the parent rule set.
- assert_error(api, "CreateReceiptRule", "InvalidParameterValue",
- f"Not a valid ruleName: {name}", RuleSetName="missing", Rule={"Name": name})
- assert api("ListReceiptRuleSets") == {"RuleSets": []}
-
-
[email protected]("name", ["-bad", "bad-", "a" * 65])
[email protected]("action,params,field", [
- ("DescribeReceiptRuleSet", {}, "ruleSetName"),
- ("DeleteReceiptRuleSet", {}, "ruleSetName"),
- ("SetActiveReceiptRuleSet", {}, "ruleSetName"),
- ("CreateReceiptRule", {"Rule": {"Name": "valid"}}, "ruleSetName"),
- ("DescribeReceiptRule", {"RuleName": "valid"}, "ruleSetName"),
- ("DeleteReceiptRule", {"RuleName": "valid"}, "ruleSetName"),
- ("DescribeReceiptRule", {"RuleSetName": "rules"}, "ruleName"),
- ("DeleteReceiptRule", {"RuleSetName": "rules"}, "ruleName"),
-])
-def test_receipt_lookup_delete_and_activation_validate_names(receipt_api, name, action, params, field):
- api = receipt_api
- api("CreateReceiptRuleSet", RuleSetName="rules")
- api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "valid"})
- api("SetActiveReceiptRuleSet", RuleSetName="rules")
- before = api("DescribeActiveReceiptRuleSet")
- key = "RuleSetName" if field == "ruleSetName" else "RuleName"
- assert_error(api, action, "InvalidParameterValue",
- f"Not a valid {field}: {name}", **{**params, key: name})
- assert api("DescribeActiveReceiptRuleSet") == before
- assert api("ListReceiptRuleSets")["RuleSets"] == [before["Metadata"]]
-
-
[email protected]("action,params", [
- ("CreateReceiptRuleSet", {}),
- ("DescribeReceiptRuleSet", {}),
- ("DeleteReceiptRuleSet", {}),
- ("CreateReceiptRule", {"Rule": {"Name": "valid"}}),
- ("DescribeReceiptRule", {"RuleName": "valid"}),
- ("DeleteReceiptRule", {"RuleName": "valid"}),
-])
-def test_receipt_missing_rule_set_name_error(receipt_api, action, params):
- assert_error(receipt_api, action, "ValidationError",
- "1 validation error detected: Value at 'ruleSetName' failed to satisfy constraint: Member must not be null",
- **params)
- assert receipt_api("ListReceiptRuleSets") == {"RuleSets": []}
-
-
[email protected]("action,params,field", [
- ("CreateReceiptRule", {}, "rule"),
- ("CreateReceiptRule", {"Rule": {}}, "rule"),
- ("CreateReceiptRule", {"Rule": {"Enabled": True}}, "rule.name"),
- ("DescribeReceiptRule", {}, "ruleName"),
- ("DeleteReceiptRule", {}, "ruleName"),
-])
-def test_receipt_missing_rule_fields_error(receipt_api, action, params, field):
- api = receipt_api
- api("CreateReceiptRuleSet", RuleSetName="rules")
- assert_error(api, action, "ValidationError",
- f"1 validation error detected: Value at '{field}' failed to satisfy constraint: Member must not be null",
- RuleSetName="rules", **params)
- assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"] == []
-
-
[email protected]("recipients", [
-])
-def test_receipt_empty_recipient_is_rejected_without_creating_a_rule(receipt_api, recipients):
- api = receipt_api
- api("CreateReceiptRuleSet", RuleSetName="rules")
- assert_error(api, "CreateReceiptRule", "InvalidParameterValue", "Invalid recipient: ",
- RuleSetName="rules", Rule={"Name": "invalid", "Recipients": recipients})
- assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"] == []
-
-
[email protected]("value", ["a\tb", "café 雪 😀 <&>"])
-def test_receipt_header_tab_and_unicode_round_trip(receipt_api, value):
- api = receipt_api
- api("CreateReceiptRuleSet", RuleSetName="rules")
- actions = [{"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": value}}]
- api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "header", "Actions": actions})
- api("SetActiveReceiptRuleSet", RuleSetName="rules")
- assert api("DescribeReceiptRule", RuleSetName="rules", RuleName="header")["Rule"]["Actions"] == actions
- assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"][0]["Actions"] == actions
- assert api("DescribeActiveReceiptRuleSet")["Rules"][0]["Actions"] == actions
-
-
-def test_receipt_nul_header_is_created_but_readback_fails_until_deleted(receipt_api):
- api = receipt_api
- api("CreateReceiptRuleSet", RuleSetName="rules")
- api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "valid"})
- api("SetActiveReceiptRuleSet", RuleSetName="rules")
- before = api("DescribeActiveReceiptRuleSet")
- assert api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "broken", "Actions": [
- {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "a\x00b"}},
- ]}) == {}
- for action, params in (
- ("DescribeReceiptRule", {"RuleSetName": "rules", "RuleName": "broken"}),
- ("DescribeReceiptRuleSet", {"RuleSetName": "rules"}),
- ("DescribeActiveReceiptRuleSet", {}),
- ):
- with pytest.raises(ClientError) as exc:
- api(action, **params)
- response = exc.value.response
- assert response["ResponseMetadata"]["HTTPStatusCode"] == 500
- assert response["Error"] == {"Type": "Receiver", "Code": "InternalFailure"}
- assert api("DescribeReceiptRule", RuleSetName="rules", RuleName="valid")["Rule"] == before["Rules"][0]
- assert api("ListReceiptRuleSets")["RuleSets"] == [before["Metadata"]]
- api("DeleteReceiptRule", RuleSetName="rules", RuleName="broken")
- assert api("DescribeReceiptRuleSet", RuleSetName="rules") == before
- assert api("DescribeActiveReceiptRuleSet") == before
-
-
[email protected]("rule,code,message", [
- ({"Name": "tls", "TlsPolicy": "Invalid"}, "ValidationError",
- "1 validation error detected: Value at 'rule.tlsPolicy' failed to satisfy constraint: Member must satisfy enum value set: [Optional, Require]"),
- ({"Name": "recipient", "Recipients": ["not valid"]}, "InvalidParameterValue", "Invalid recipient: not valid"),
- ({"Name": "scope", "Actions": [{"StopAction": {"Scope": "Invalid"}}]}, "ValidationError",
- "1 validation error detected: Value at 'rule.actions.1.member.stopAction.scope' failed to satisfy constraint: Member must satisfy enum value set: [RuleSet]"),
- ({"Name": "ordering", "Actions": [{"StopAction": {"Scope": "RuleSet"}},
- {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "ok"}}]}, "InvalidParameterValue",
- "Stop action, if any, must be placed at the end of the actions list"),
- ({"Name": "multiple", "Actions": [{"StopAction": {"Scope": "RuleSet"},
- "AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "ok"}}]}, "InvalidParameterValue",
- "Exactly one action type must be specified for each ReceiptAction"),
- ({"Name": "header", "Actions": [{"AddHeaderAction": {"HeaderName": "X bad", "HeaderValue": "ok"}}]},
- "InvalidParameterValue", "Invalid header name: X bad"),
- ({"Name": "newline", "Actions": [{"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "a\nb"}}]},
- "InvalidParameterValue", "Invalid header value: a0x000ab"),
-])
-def test_receipt_invalid_rule_metadata_is_atomic(receipt_api, rule, code, message):
- api = receipt_api
- api("CreateReceiptRuleSet", RuleSetName="rules")
- assert_error(api, "CreateReceiptRule", code, message, RuleSetName="rules", Rule=rule)
- assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"] == []
-
-
[email protected]("header,missing", [
- ({"HeaderName": "X-Test"}, "headerValue"),
- ({"HeaderValue": "value"}, "headerName"),
-])
-def test_receipt_missing_header_fields_are_rejected_without_creating_a_rule(receipt_api, header, missing):
- api = receipt_api
- api("CreateReceiptRuleSet", RuleSetName="rules")
- assert_error(api, "CreateReceiptRule", "ValidationError",
- f"1 validation error detected: Value at 'rule.actions.1.member.addHeaderAction.{missing}' failed to satisfy constraint: Member must not be null",
- RuleSetName="rules", Rule={"Name": "missing", "Actions": [{"AddHeaderAction": header}]})
- assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"] == []
-
-
[email protected]("recipient", [
- "example..com", "example.-com", "example-.com", "foo..example.com",
- "foo.-example.com", "foo.example-.com", "example.com-",
-])
-def test_receipt_invalid_domain_labels_are_rejected_without_creating_a_rule(receipt_api, recipient):
- api = receipt_api
- api("CreateReceiptRuleSet", RuleSetName="rules")
- assert_error(api, "CreateReceiptRule", "InvalidParameterValue", f"Invalid recipient: {recipient}",
- RuleSetName="rules", Rule={"Name": "invalid", "Recipients": [recipient]})
- assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"] == []
-
-
-def test_receipt_recipients_are_lowercased_deduplicated_and_sorted(receipt_api):
- api = receipt_api
- api("CreateReceiptRuleSet", RuleSetName="rules")
- api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "recipients", "Recipients": [
- "example.com", ".EXAMPLE.COM", ".example.com",
- ]})
- recipients = [".example.com", "[email protected]", "example.com", "[email protected]"]
- assert api("DescribeReceiptRule", RuleSetName="rules", RuleName="recipients")["Rule"]["Recipients"] == recipients
- assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"][0]["Recipients"] == recipients
-
-
[email protected]("action", [
- {"S3Action": {"BucketName": "bucket"}},
- {"SNSAction": {"TopicArn": "arn:aws:sns:us-east-1:111111111111:topic"}},
- {"LambdaAction": {"FunctionArn": "arn:aws:lambda:us-east-1:111111111111:function:test"}},
- {"BounceAction": {"SmtpReplyCode": "550", "Message": "no", "Sender": "[email protected]"}},
- {"WorkmailAction": {"OrganizationArn": "arn:aws:workmail:us-east-1:111111111111:organization/m-test"}},
- {"ConnectAction": {"InstanceARN": "arn:aws:connect:us-east-1:111111111111:instance/test",
- "IAMRoleARN": "arn:aws:iam::111111111111:role/test"}},
- {"StopAction": {"Scope": "RuleSet", "TopicArn": "arn:aws:sns:us-east-1:111111111111:topic"}},
-])
-def test_receipt_external_actions_are_explicitly_unsupported(receipt_api, action):
- # Intentional supported-subset boundary: destination/permission validation
- # and receiving execution have not been implemented for these action types.
- api = receipt_api
- api("CreateReceiptRuleSet", RuleSetName="rules")
- name = next(iter(action))
- if name == "StopAction":
- name += " with TopicArn"
- assert_error(api, "CreateReceiptRule", "InvalidAction",
- f"Receipt action {name} is not implemented",
- RuleSetName="rules", Rule={"Name": "unsupported", "Actions": [action]})
- assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"] == []
-
-
-def test_receipt_explicit_empty_fields_are_preserved_and_after_is_validated(receipt_api):
- api = receipt_api
- api("CreateReceiptRuleSet", RuleSetName="rules")
- api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "empty", "Recipients": [], "Actions": [{}]})
- assert api("DescribeReceiptRule", RuleSetName="rules", RuleName="empty")["Rule"]["Recipients"] == []
- for name, action in (("empty-stop", {"StopAction": {}}), ("empty-header", {"AddHeaderAction": {}})):
- api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": name, "Actions": [action]})
- assert api("DescribeReceiptRule", RuleSetName="rules", RuleName=name)["Rule"]["Actions"] == []
- api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "header", "Actions": [
- {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": ""}},
- ]})
- assert api("DescribeReceiptRule", RuleSetName="rules", RuleName="header")["Rule"]["Actions"] == [
- {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": ""}},
- ]
- assert_error(api, "CreateReceiptRule", "ValidationError",
- "2 validation errors detected: Value at 'after' failed to satisfy constraint: Member must have length greater than or equal to 1; Value at 'after' failed to satisfy constraint: Member must satisfy regular expression pattern: ^[a-zA-Z0-9_.-]+$",
- RuleSetName="rules", After="", Rule={"Name": "after"})
-
-
-def test_receipt_metadata_and_active_selection_survive_all_tenant_persistence_and_reset(receipt_api, monkeypatch, tmp_path):
- api = receipt_api
- scopes = [("111111111111", "us-east-1"), ("111111111111", "us-west-2"), ("222222222222", "us-east-1")]
- expected = {}
- for i, (account, region) in enumerate(scopes):
- set_request_account_id(account)
- set_request_region(region)
- assert api("ListReceiptRuleSets") == {"RuleSets": []}
- api("CreateReceiptRuleSet", RuleSetName="same-name")
- api("CreateReceiptRule", RuleSetName="same-name", Rule={"Name": f"rule-{i}"})
- api("SetActiveReceiptRuleSet", RuleSetName="same-name")
- expected[account, region] = api("DescribeActiveReceiptRuleSet")
- snapshot = ses.get_state()
- monkeypatch.setattr(persistence, "PERSIST_STATE", True)
- monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))
- persistence.save_state("ses", snapshot)
- ses.reset()
- for account, region in scopes:
- set_request_account_id(account)
- set_request_region(region)
- assert api("ListReceiptRuleSets") == {"RuleSets": []}
- assert api("DescribeActiveReceiptRuleSet") == {}
- ses.load_persisted_state(persistence.load_state("ses"))
- for account, region in scopes:
- set_request_account_id(account)
- set_request_region(region)
- assert api("DescribeActiveReceiptRuleSet") == expected[account, region]
- api("SetActiveReceiptRuleSet")
- api("DeleteReceiptRuleSet", RuleSetName="same-name")
- set_request_account_id(scopes[0][0])
- set_request_region(scopes[0][1])
- assert api("DescribeActiveReceiptRuleSet") == expected[scopes[0]]
- assert snapshot["_receipt_rule_sets"].get_scoped(*scopes[-1], "same-name")["Rules"]
-
-
-def test_receipt_unsigned_sdk_lifecycle():
- # The endpoint comes from conftest so this uses the same isolated local
- # server as the integration suite. Activation changes shared server state.
- from conftest import make_client
-
- client = make_client("ses", additional_config_kwargs={"signature_version": UNSIGNED})
- name = f"unsigned-receipts-{uuid4().hex[:12]}"
- previous = client.describe_active_receipt_rule_set().get("Metadata", {}).get("Name")
- client.create_receipt_rule_set(RuleSetName=name)
- try:
- assert name in {item["Name"] for item in client.list_receipt_rule_sets()["RuleSets"]}
- client.create_receipt_rule(RuleSetName=name, Rule={"Name": "first"})
- client.create_receipt_rule(RuleSetName=name, After="first", Rule={"Name": "second", "Actions": [
- {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "value<&"}},
- {"StopAction": {"Scope": "RuleSet"}},
- ]})
- described = client.describe_receipt_rule_set(RuleSetName=name)
- assert [rule["Name"] for rule in described["Rules"]] == ["first", "second"]
- assert client.describe_receipt_rule(RuleSetName=name, RuleName="second")["Rule"] == described["Rules"][1]
- client.set_active_receipt_rule_set(RuleSetName=name)
- active = client.describe_active_receipt_rule_set()
- assert active["Metadata"] == described["Metadata"]
- assert active["Rules"] == described["Rules"]
- client.delete_receipt_rule(RuleSetName=name, RuleName="second")
- assert [rule["Name"] for rule in client.describe_active_receipt_rule_set()["Rules"]] == ["first"]
- finally:
- client.set_active_receipt_rule_set(**({"RuleSetName": previous} if previous else {}))
- client.delete_receipt_rule_set(RuleSetName=name)
- assert name not in {item["Name"] for item in client.list_receipt_rule_sets()["RuleSets"]}
diff --git a/tests/test_ses_tenants.py b/tests/test_ses_tenants.py
deleted file mode 100644
index 761eb5b2..00000000
--- a/tests/test_ses_tenants.py
+++ /dev/null
@@ -1,575 +0,0 @@
-# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
-"""SES tenant lifecycle, resource associations, and AWS-observed errors."""
-
-import copy
-import json
-import re
-import uuid
-
-import pytest
-from botocore.exceptions import ClientError
-
-from ministack.core.responses import set_request_account_id, set_request_region
-
-
-def _error(client, operation, code, message, **params):
- with pytest.raises(ClientError) as caught:
- getattr(client, operation)(**params)
- response = caught.value.response
- assert response["Error"] == {"Code": code, "Message": message}
- assert response["ResponseMetadata"]["HTTPStatusCode"] == (404 if code == "NotFoundException" else 400)
-
-
-def test_tenant_configuration_set_association_lifecycle(sesv2):
- name = "tenant-" + uuid.uuid4().hex[:10]
- tags = [{"Key": "purpose", "Value": "regression"}]
- sesv2.create_configuration_set(ConfigurationSetName=name, Tags=tags)
- tenant = sesv2.create_tenant(TenantName=name, Tags=tags)
- assert re.fullmatch(r"tn-[a-f0-9]{29}", tenant["TenantId"])
- assert tenant["TenantArn"].endswith(f"tenant/{name}/{tenant['TenantId']}")
- assert tenant["SendingStatus"] == "ENABLED"
- assert tenant["Tags"] == tags
- assert sesv2.get_tenant(TenantName=name)["Tenant"] == {k: v for k, v in tenant.items() if k != "ResponseMetadata"}
- _error(
- sesv2,
- "create_tenant",
- "AlreadyExistsException",
- f"Tenant with name {name} already exists in account 000000000000",
- TenantName=name,
- )
- listed = sesv2.list_tenants(Filter={"TENANT_NAME_CONTAINS": name, "SENDING_STATUS": "ENABLED"})["Tenants"]
- assert listed == [{k: v for k, v in tenant.items() if k not in ("ResponseMetadata", "Tags")}]
- assert sesv2.list_tags_for_resource(ResourceArn=tenant["TenantArn"])["Tags"] == tags
- sesv2.tag_resource(ResourceArn=tenant["TenantArn"], Tags=[{"Key": "updated", "Value": "yes"}])
- sesv2.untag_resource(ResourceArn=tenant["TenantArn"], TagKeys=["purpose"])
- assert sesv2.get_tenant(TenantName=name)["Tenant"]["Tags"] == [{"Key": "updated", "Value": "yes"}]
- arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{name}"
- sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=arn)
- _error(
- sesv2,
- "create_tenant_resource_association",
- "AlreadyExistsException",
- f"Resources {arn} has already been associated with tenant {name}",
- TenantName=name,
- ResourceArn=arn,
- )
- assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == [
- {"ResourceType": "configuration-set", "ResourceArn": arn}
- ]
- inverse = sesv2.list_resource_tenants(ResourceArn=arn)["ResourceTenants"]
- assert inverse[0]["TenantId"] == tenant["TenantId"]
- assert inverse[0]["ResourceArn"] == arn
- _error(
- sesv2,
- "delete_configuration_set",
- "BadRequestException",
- f"Cannot delete <{arn}> because it has tenant associations. Remove all tenant associations and try again.",
- ConfigurationSetName=name,
- )
- sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=arn)
- sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=arn)
- assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == []
- sesv2.delete_tenant(TenantName=name)
- _error(sesv2, "get_tenant", "NotFoundException", f"The requested tenant <{name}> does not exist.", TenantName=name)
- _error(
- sesv2,
- "list_tags_for_resource",
- "NotFoundException",
- f"No Tenant present with name: {name}with tenantId: {tenant['TenantId']}",
- ResourceArn=tenant["TenantArn"],
- )
- for operation, params in [
- ("tag_resource", {"Tags": [{"Key": "purpose", "Value": "regression"}]}),
- ("untag_resource", {"TagKeys": ["purpose"]}),
- ]:
- _error(sesv2, operation, "NotFoundException", f"No Tenant present with name: {name}with tenantId: {tenant['TenantId']}",
- ResourceArn=tenant["TenantArn"], **params)
- sesv2.delete_configuration_set(ConfigurationSetName=name)
-
-
-def test_tenant_invalid_and_missing_resources(sesv2):
- name = "tenant-errors-" + uuid.uuid4().hex[:10]
- _error(
- sesv2,
- "create_tenant",
- "BadRequestException",
- f"Invalid tenant name <{name} bad>: only alphanumeric ASCII characters, '_', and '-' are allowed.",
- TenantName=name + " bad",
- )
- _error(
- sesv2,
- "create_tenant_resource_association",
- "NotFoundException",
- f"The requested tenant <{name}> does not exist.",
- TenantName=name,
- ResourceArn="invalid-arn",
- )
- sesv2.create_tenant(TenantName=name)
- _error(
- sesv2,
- "create_tenant_resource_association",
- "BadRequestException",
- "Provided resource identifier is not an SES resource",
- TenantName=name,
- ResourceArn="invalid-arn",
- )
- arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{name}"
- _error(
- sesv2,
- "create_tenant_resource_association",
- "NotFoundException",
- f"Configuration set <{name}> does not exist:",
- TenantName=name,
- ResourceArn=arn,
- )
- other = arn.replace("us-east-1", "us-west-2")
- _error(
- sesv2,
- "create_tenant_resource_association",
- "BadRequestException",
- f"Resource <{other}> must be in the same region",
- TenantName=name,
- ResourceArn=other,
- )
- sesv2.delete_tenant(TenantName=name)
-
-
[email protected]("filters,message", [
- ({"INVALID": "template"},
- "1 validation error detected: Value at 'filter' failed to satisfy constraint: Map keys must satisfy constraint: [Member must satisfy enum value set: [RESOURCE_TYPE]]"),
- ({"RESOURCE_TYPE": "bogus"}, "Invalid resource type bogus specified."),
- ({"RESOURCE_TYPE": "template,configuration-set"},
- "Invalid resource type template,configuration-set specified."),
-])
-def test_tenant_resource_filter_errors(sesv2, filters, message):
- name = "tenant-filter-" + uuid.uuid4().hex[:10]
- sesv2.create_tenant(TenantName=name)
- _error(sesv2, "list_tenant_resources", "BadRequestException", message,
- TenantName=name, Filter=filters)
- sesv2.delete_tenant(TenantName=name)
-
-
-def test_tenant_sending_status_filter(sesv2):
- name = "tenant-status-" + uuid.uuid4().hex[:10]
- sesv2.create_tenant(TenantName=name)
- _error(sesv2, "list_tenants", "BadRequestException", "Invalid sending status <bogus>.",
- Filter={"TENANT_NAME_CONTAINS": name, "SENDING_STATUS": "bogus"})
- for status in ("REINSTATED", "DISABLED"):
- assert sesv2.list_tenants(Filter={"TENANT_NAME_CONTAINS": name, "SENDING_STATUS": status})["Tenants"] == []
- sesv2.delete_tenant(TenantName=name)
-
-
-def test_tenant_template_association_and_delete_with_associations(sesv2):
- name = "tenant-template-" + uuid.uuid4().hex[:10]
- sesv2.create_email_template(TemplateName=name, TemplateContent={"Subject": "probe", "Text": "probe"})
- sesv2.create_configuration_set(ConfigurationSetName=name)
- template_arn = f"arn:aws:ses:us-east-1:000000000000:template/{name}"
- config_arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{name}"
- tenants = [name + suffix for suffix in ("-a", "-b")]
- for tenant_name in tenants:
- sesv2.create_tenant(TenantName=tenant_name)
- for arn in (config_arn, template_arn):
- sesv2.create_tenant_resource_association(TenantName=tenant_name, ResourceArn=arn)
- assert sesv2.list_tenant_resources(TenantName=tenant_name, Filter={"RESOURCE_TYPE": "template"})["TenantResources"] == [
- {"ResourceType": "template", "ResourceArn": template_arn}
- ]
- first = sesv2.list_tenant_resources(TenantName=tenant_name, PageSize=1)
- second = sesv2.list_tenant_resources(TenantName=tenant_name, PageSize=1, NextToken=first["NextToken"])
- assert first["TenantResources"] + second["TenantResources"] == [
- {"ResourceType": "configuration-set", "ResourceArn": config_arn},
- {"ResourceType": "template", "ResourceArn": template_arn},
- ]
- assert "NextToken" not in second
- first = sesv2.list_resource_tenants(ResourceArn=config_arn, PageSize=1)
- second = sesv2.list_resource_tenants(ResourceArn=config_arn, PageSize=1, NextToken=first["NextToken"])
- assert [item["TenantName"] for item in first["ResourceTenants"] + second["ResourceTenants"]] == tenants
- assert "NextToken" not in second
- sesv2.delete_tenant(TenantName=tenants[0])
- assert [item["TenantName"] for item in sesv2.list_resource_tenants(ResourceArn=config_arn)["ResourceTenants"]] == tenants[1:]
- _error(sesv2, "delete_configuration_set", "BadRequestException",
- f"Cannot delete <{config_arn}> because it has tenant associations. Remove all tenant associations and try again.",
- ConfigurationSetName=name)
- sesv2.delete_tenant(TenantName=tenants[1])
- assert sesv2.list_resource_tenants(ResourceArn=config_arn)["ResourceTenants"] == []
- sesv2.delete_configuration_set(ConfigurationSetName=name)
- sesv2.delete_email_template(TemplateName=name)
-
-
-def test_tenant_state_roundtrip_and_account_region_isolation():
- from ministack.core.persistence import _json_default, _json_object_hook
- from ministack.services import ses_v2
-
- snapshot = copy.deepcopy(ses_v2.get_state())
- scopes = [
- ("000000000000", "us-east-1"),
- ("111111111111", "us-east-1"),
- ("000000000000", "us-west-2"),
- ]
- saved_tenants = {}
- try:
- for account, region in scopes:
- set_request_account_id(account)
- set_request_region(region)
- assert "same" not in ses_v2._tenants
- assert "same" not in ses_v2._tenant_resources
- status, _, body = ses_v2._tenant_request(
- "POST", "/tenants", {"TenantName": "same", "Tags": [{"Key": "region", "Value": region}]}
- )
- assert status == 200
- saved_tenants[(account, region)] = json.loads(body)
- arn = f"arn:aws:ses:{region}:{account}:configuration-set/same"
- ses_v2._config_sets["same"] = {"ConfigurationSetName": "same"}
- assert ses_v2._tenant_request(
- "POST", "/tenants/resources", {"TenantName": "same", "ResourceArn": arn}
- )[0] == 200
-
- encoded = json.dumps(ses_v2.get_state(), default=_json_default, sort_keys=True)
- saved = json.loads(encoded, object_hook=_json_object_hook)
- ses_v2.reset()
- for account, region in scopes:
- set_request_account_id(account)
- set_request_region(region)
- assert not ses_v2._tenants
- assert not ses_v2._tenant_resources
- ses_v2.load_persisted_state(saved)
- assert json.dumps(ses_v2.get_state(), default=_json_default, sort_keys=True) == encoded
- for account, region in scopes:
- set_request_account_id(account)
- set_request_region(region)
- tenant = saved_tenants[(account, region)]
- assert ses_v2._tenants["same"] == tenant
- assert ses_v2._ses_tags[tenant["TenantArn"]] == [{"Key": "region", "Value": region}]
- arn = f"arn:aws:ses:{region}:{account}:configuration-set/same"
- assert list(ses_v2._tenant_resources["same"]) == [arn]
- inverse = json.loads(ses_v2._tenant_request(
- "POST", "/resources/tenants/list", {"ResourceArn": arn}
- )[2])["ResourceTenants"]
- assert inverse == [{
- "TenantName": "same",
- "TenantId": tenant["TenantId"],
- "ResourceArn": arn,
- "AssociatedTimestamp": ses_v2._tenant_resources["same"][arn],
- }]
- finally:
- ses_v2.reset()
- ses_v2.load_persisted_state(snapshot)
-
-
-def test_tenant_suppression_lifecycle(sesv2):
- name = "tenant-suppr-" + uuid.uuid4().hex[:10]
- attrs = {"SuppressedReasons": ["BOUNCE"], "SuppressionScope": "TENANT"}
- created = sesv2.create_tenant(TenantName=name, SuppressionAttributes=attrs)
- assert created["SuppressionAttributes"] == attrs
- assert sesv2.get_tenant(TenantName=name)["Tenant"]["SuppressionAttributes"] == attrs
- listed = sesv2.list_tenants(Filter={"TENANT_NAME_CONTAINS": name})["Tenants"]
- assert listed and "SuppressionAttributes" not in listed[0]
- updated = {"SuppressedReasons": ["BOUNCE", "COMPLAINT"], "SuppressionScope": "ACCOUNT"}
- sesv2.put_tenant_suppression_attributes(TenantName=name, **updated)
- assert sesv2.get_tenant(TenantName=name)["Tenant"]["SuppressionAttributes"] == updated
- sesv2.put_tenant_suppression_attributes(TenantName=name)
- assert "SuppressionAttributes" not in sesv2.get_tenant(TenantName=name)["Tenant"]
- sesv2.put_tenant_suppression_attributes(
- TenantName=name, SuppressedReasons=[], SuppressionScope="TENANT"
- )
- assert sesv2.get_tenant(TenantName=name)["Tenant"]["SuppressionAttributes"] == {
- "SuppressedReasons": [],
- "SuppressionScope": "TENANT",
- }
- sesv2.delete_tenant(TenantName=name)
-
-
-def test_tenant_suppression_validation(sesv2):
- name = "tenant-supval-" + uuid.uuid4().hex[:10]
- create_reasons = (
- "1 validation error detected: Value at 'suppressionAttributes.suppressedReasons'"
- " failed to satisfy constraint: Member must satisfy constraint:"
- " [Member must satisfy enum value set: [BOUNCE, COMPLAINT]]"
- )
- create_scope = (
- "1 validation error detected: Value at 'suppressionAttributes.suppressionScope'"
- " failed to satisfy constraint: Member must satisfy enum value set: [TENANT, ACCOUNT]"
- )
- put_reasons = create_reasons.replace("suppressionAttributes.suppressedReasons", "suppressedReasons")
- put_scope = create_scope.replace("suppressionAttributes.suppressionScope", "suppressionScope")
- null_reasons = (
- "1 validation error detected: Value null at 'suppressionAttributes.suppressedReasons'"
- " failed to satisfy constraint: Member must not be null"
- )
- null_scope = (
- "1 validation error detected: Value null at 'suppressionAttributes.suppressionScope'"
- " failed to satisfy constraint: Member must not be null"
- )
- both_null = "2 validation errors detected: " + "; ".join(
- [null_reasons.split(": ", 1)[1], null_scope.split(": ", 1)[1]]
- )
- both_create = "2 validation errors detected: " + "; ".join(
- [create_reasons.split(": ", 1)[1], create_scope.split(": ", 1)[1]]
- )
- both_put = "2 validation errors detected: " + "; ".join(
- [put_reasons.split(": ", 1)[1], put_scope.split(": ", 1)[1]]
- )
- bad_attrs = {"SuppressedReasons": ["NOPE"], "SuppressionScope": "TENANT"}
- _error(sesv2, "create_tenant", "BadRequestException", create_reasons,
- TenantName=name, SuppressionAttributes=bad_attrs)
- _error(sesv2, "create_tenant", "BadRequestException", create_scope,
- TenantName=name,
- SuppressionAttributes={"SuppressedReasons": ["BOUNCE"], "SuppressionScope": "NOPE"})
- _error(sesv2, "create_tenant", "BadRequestException", both_create,
- TenantName=name,
- SuppressionAttributes={"SuppressedReasons": ["NOPE"], "SuppressionScope": "NOPE"})
- _error(sesv2, "create_tenant", "BadRequestException",
- "SuppressedReasons cannot be specified without SuppressionScope.",
- TenantName=name, SuppressionAttributes={"SuppressedReasons": ["BOUNCE"]})
- _error(sesv2, "create_tenant", "BadRequestException",
- "SuppressionScope cannot be specified without SuppressedReasons.",
- TenantName=name, SuppressionAttributes={"SuppressionScope": "TENANT"})
- _error(sesv2, "create_tenant", "BadRequestException", both_null,
- TenantName=name, SuppressionAttributes={})
- _error(sesv2, "create_tenant", "BadRequestException", null_scope,
- TenantName=name, SuppressionAttributes={"SuppressedReasons": []})
- # Precedence: model enum errors beat the name check, which beats pairing rules,
- # which beat the duplicate check.
- _error(sesv2, "create_tenant", "BadRequestException", create_reasons,
- TenantName="bad name", SuppressionAttributes=bad_attrs)
- _error(sesv2, "create_tenant", "BadRequestException",
- "Invalid tenant name <bad name>: only alphanumeric ASCII characters, '_', and '-' are allowed.",
- TenantName="bad name", SuppressionAttributes={"SuppressedReasons": ["BOUNCE"]})
- sesv2.create_tenant(TenantName=name)
- _error(sesv2, "create_tenant", "BadRequestException", create_reasons,
- TenantName=name, SuppressionAttributes=bad_attrs)
- _error(sesv2, "create_tenant", "BadRequestException",
- "SuppressedReasons cannot be specified without SuppressionScope.",
- TenantName=name, SuppressionAttributes={"SuppressedReasons": ["BOUNCE"]})
- _error(sesv2, "put_tenant_suppression_attributes", "BadRequestException", put_reasons,
- TenantName=name, SuppressedReasons=["NOPE"], SuppressionScope="TENANT")
- _error(sesv2, "put_tenant_suppression_attributes", "BadRequestException", put_scope,
- TenantName=name, SuppressedReasons=["BOUNCE"], SuppressionScope="NOPE")
- _error(sesv2, "put_tenant_suppression_attributes", "BadRequestException", both_put,
- TenantName=name, SuppressedReasons=["NOPE"], SuppressionScope="NOPE")
- _error(sesv2, "put_tenant_suppression_attributes", "BadRequestException",
- "SuppressedReasons cannot be specified without SuppressionScope.",
- TenantName=name, SuppressedReasons=["BOUNCE"])
- _error(sesv2, "put_tenant_suppression_attributes", "BadRequestException",
- "SuppressionScope is required when SuppressedReasons are provided. Valid values are: TENANT, ACCOUNT",
- TenantName=name, SuppressedReasons=[])
- _error(sesv2, "put_tenant_suppression_attributes", "BadRequestException",
- "SuppressionScope cannot be specified without SuppressedReasons.",
- TenantName=name, SuppressionScope="TENANT")
- missing = name + "-missing"
- _error(sesv2, "put_tenant_suppression_attributes", "BadRequestException", put_reasons,
- TenantName=missing, SuppressedReasons=["NOPE"], SuppressionScope="TENANT")
- _error(sesv2, "put_tenant_suppression_attributes", "BadRequestException",
- "SuppressionScope cannot be specified without SuppressedReasons.",
- TenantName=missing, SuppressionScope="TENANT")
- _error(sesv2, "put_tenant_suppression_attributes", "NotFoundException",
- f"The requested tenant <{missing}> does not exist.", TenantName=missing)
- sesv2.delete_tenant(TenantName=name)
-
-
-def test_tenant_list_ordering(sesv2):
- prefix = "tenant-ord-" + uuid.uuid4().hex[:10]
- first, second = prefix + "-zz", prefix + "-aa"
- sesv2.create_tenant(TenantName=first)
- sesv2.create_tenant(TenantName=second)
- names = [
- t["TenantName"]
- for t in sesv2.list_tenants(Filter={"TENANT_NAME_CONTAINS": prefix})["Tenants"]
- ]
- assert names == [second, first]
- cs_b, cs_a = prefix + "-cs-b", prefix + "-cs-a"
- sesv2.create_configuration_set(ConfigurationSetName=cs_b)
- sesv2.create_configuration_set(ConfigurationSetName=cs_a)
- dom = prefix + ".example.com"
- sesv2.create_email_identity(EmailIdentity=dom)
- arns = [
- f"arn:aws:ses:us-east-1:000000000000:{kind}/{leaf}"
- for kind, leaf in [
- ("configuration-set", cs_b),
- ("identity", dom),
- ("configuration-set", cs_a),
- ]
- ]
- for arn in arns:
- sesv2.create_tenant_resource_association(TenantName=first, ResourceArn=arn)
- listed = sesv2.list_tenant_resources(TenantName=first)["TenantResources"]
- assert [item["ResourceArn"] for item in listed] == sorted(arns)
- for arn in arns:
- sesv2.delete_tenant_resource_association(TenantName=first, ResourceArn=arn)
- sesv2.delete_tenant(TenantName=first)
- sesv2.delete_tenant(TenantName=second)
- sesv2.delete_configuration_set(ConfigurationSetName=cs_b)
- sesv2.delete_configuration_set(ConfigurationSetName=cs_a)
- sesv2.delete_email_identity(EmailIdentity=dom)
-
-
-def test_tenant_resource_tenants_keep_creation_order(sesv2):
- prefix = "tenant-rto-" + uuid.uuid4().hex[:10]
- cs = prefix + "-cs"
- sesv2.create_configuration_set(ConfigurationSetName=cs)
- arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{cs}"
- early, late = prefix + "-early", prefix + "-late"
- sesv2.create_tenant(TenantName=early)
- sesv2.create_tenant(TenantName=late)
- sesv2.create_tenant_resource_association(TenantName=late, ResourceArn=arn)
- sesv2.create_tenant_resource_association(TenantName=early, ResourceArn=arn)
- names = [
- item["TenantName"]
- for item in sesv2.list_resource_tenants(ResourceArn=arn)["ResourceTenants"]
- ]
- assert names == [early, late]
- sesv2.delete_tenant(TenantName=early)
- sesv2.delete_tenant(TenantName=late)
- sesv2.delete_configuration_set(ConfigurationSetName=cs)
-
-
-def test_tenant_resource_delete_guards(sesv2, ses):
- prefix = "tenant-guard-" + uuid.uuid4().hex[:10]
- cs, tpl, dom = prefix + "-cs", prefix + "-tpl", prefix + ".example.com"
- sesv2.create_configuration_set(ConfigurationSetName=cs)
- sesv2.create_email_template(TemplateName=tpl, TemplateContent={"Subject": "s", "Text": "t"})
- sesv2.create_email_identity(EmailIdentity=dom)
- name = prefix + "-t"
- sesv2.create_tenant(TenantName=name)
- arns = {
- kind: f"arn:aws:ses:us-east-1:000000000000:{kind}/{leaf}"
- for kind, leaf in [("configuration-set", cs), ("template", tpl), ("identity", dom)]
- }
- for arn in arns.values():
- sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=arn)
- for operation, params in [
- ("delete_configuration_set", {"ConfigurationSetName": cs}),
- ("delete_email_template", {"TemplateName": tpl}),
- ("delete_email_identity", {"EmailIdentity": dom}),
- ]:
- kind = {"delete_configuration_set": "configuration-set",
- "delete_email_template": "template",
- "delete_email_identity": "identity"}[operation]
- _error(sesv2, operation, "BadRequestException",
- f"Cannot delete <{arns[kind]}> because it has tenant associations."
- " Remove all tenant associations and try again.",
- **params)
- for operation, params in [
- ("delete_configuration_set", {"ConfigurationSetName": cs}),
- ("delete_template", {"TemplateName": tpl}),
- ("delete_identity", {"Identity": dom}),
- ]:
- kind = {"delete_configuration_set": "configuration-set",
- "delete_template": "template",
- "delete_identity": "identity"}[operation]
- _error(ses, operation, "InvalidParameterValue",
- f"Cannot delete <{arns[kind]}> because it has tenant associations."
- " Remove all tenant associations and try again.",
- **params)
- for arn in arns.values():
- sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=arn)
- sesv2.delete_tenant(TenantName=name)
- sesv2.delete_configuration_set(ConfigurationSetName=cs)
- sesv2.delete_email_template(TemplateName=tpl)
- sesv2.delete_email_identity(EmailIdentity=dom)
-
-
-def test_tenant_association_rejects_non_ses_arn(sesv2):
- name = "tenant-nonses-" + uuid.uuid4().hex[:10]
- sesv2.create_tenant(TenantName=name)
- _error(sesv2, "create_tenant_resource_association", "BadRequestException",
- "Provided ARN is not in SES resource ARN format",
- TenantName=name, ResourceArn=f"arn:aws:s3:::{name}-bucket")
- _error(sesv2, "list_tags_for_resource", "NotFoundException",
- f"No Tenant present with name: nullwith tenantId: {name}",
- ResourceArn=f"arn:aws:ses:us-east-1:000000000000:tenant/{name}")
- sesv2.delete_tenant(TenantName=name)
-
-
-def test_tenant_list_pagesize_bounds(sesv2):
- name = "tenant-pages-" + uuid.uuid4().hex[:10]
- sesv2.create_tenant(TenantName=name)
- _error(sesv2, "list_tenants", "BadRequestException",
- "1 validation error detected: Value '0' at 'pageSize' failed to satisfy"
- " constraint: Member must have value greater than or equal to 1",
- PageSize=0)
- over = ("1 validation error detected: Value '101' at 'pageSize' failed to satisfy"
- " constraint: Member must have value less than or equal to 100")
- _error(sesv2, "list_tenants", "BadRequestException", over, PageSize=101)
- _error(sesv2, "list_tenant_resources", "BadRequestException", over,
- TenantName=name, PageSize=101)
- cs = name + "-cs"
- sesv2.create_configuration_set(ConfigurationSetName=cs)
- arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{cs}"
- _error(sesv2, "list_resource_tenants", "BadRequestException", over,
- ResourceArn=arn, PageSize=101)
- sesv2.delete_tenant(TenantName=name)
- sesv2.delete_configuration_set(ConfigurationSetName=cs)
-
-
-def test_tenant_v1_resources_can_be_associated(sesv2, ses):
- prefix = "tenant-v1res-" + uuid.uuid4().hex[:10]
- cs, dom = prefix + "-cs", prefix + ".example.com"
- ses.create_configuration_set(ConfigurationSet={"Name": cs})
- ses.verify_domain_identity(Domain=dom)
- name = prefix + "-t"
- sesv2.create_tenant(TenantName=name)
- cs_arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{cs}"
- idn_arn = f"arn:aws:ses:us-east-1:000000000000:identity/{dom}"
- sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=cs_arn)
- sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=idn_arn)
- assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == [
- {"ResourceType": "configuration-set", "ResourceArn": cs_arn},
- {"ResourceType": "identity", "ResourceArn": idn_arn},
- ]
- blocked = "because it has tenant associations. Remove all tenant associations and try again."
- _error(sesv2, "delete_configuration_set", "BadRequestException",
- f"Cannot delete <{cs_arn}> {blocked}", ConfigurationSetName=cs)
- _error(sesv2, "delete_email_identity", "BadRequestException",
- f"Cannot delete <{idn_arn}> {blocked}", EmailIdentity=dom)
- _error(ses, "delete_configuration_set", "InvalidParameterValue",
- f"Cannot delete <{cs_arn}> {blocked}", ConfigurationSetName=cs)
- _error(ses, "delete_identity", "InvalidParameterValue",
- f"Cannot delete <{idn_arn}> {blocked}", Identity=dom)
- sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=cs_arn)
- sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=idn_arn)
- sesv2.delete_tenant(TenantName=name)
- ses.delete_configuration_set(ConfigurationSetName=cs)
- ses.delete_identity(Identity=dom)
-
-
-def test_tenant_association_normalizes_foreign_partitions(sesv2):
- prefix = "tenant-part-" + uuid.uuid4().hex[:10]
- cs = prefix + "-cs"
- sesv2.create_configuration_set(ConfigurationSetName=cs)
- name = prefix + "-t"
- tenant = sesv2.create_tenant(TenantName=name)
- aws_arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{cs}"
- cn_arn = f"arn:aws-cn:ses:us-east-1:000000000000:configuration-set/{cs}"
- sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=cn_arn)
- assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == [
- {"ResourceType": "configuration-set", "ResourceArn": aws_arn}
- ]
- _error(sesv2, "create_tenant_resource_association", "AlreadyExistsException",
- f"Resources {aws_arn} has already been associated with tenant {name}",
- TenantName=name, ResourceArn=aws_arn)
- inverse = sesv2.list_resource_tenants(ResourceArn=cn_arn)["ResourceTenants"]
- assert [(item["TenantName"], item["ResourceArn"]) for item in inverse] == [(name, aws_arn)]
- _error(sesv2, "delete_configuration_set", "BadRequestException",
- f"Cannot delete <{aws_arn}> because it has tenant associations."
- " Remove all tenant associations and try again.",
- ConfigurationSetName=cs)
- sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=aws_arn)
- assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == []
- sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=aws_arn)
- sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=cn_arn)
- assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == []
- xacct = f"arn:aws-cn:ses:us-east-1:111122223333:configuration-set/{cs}"
- _error(sesv2, "create_tenant_resource_association", "BadRequestException",
- f"Resource <{xacct}> must be in the same account",
- TenantName=name, ResourceArn=xacct)
- cn_tenant = tenant["TenantArn"].replace("arn:aws:", "arn:aws-cn:", 1)
- sesv2.tag_resource(ResourceArn=cn_tenant, Tags=[{"Key": "pk", "Value": "v"}])
- assert sesv2.list_tags_for_resource(ResourceArn=tenant["TenantArn"])["Tags"] == [
- {"Key": "pk", "Value": "v"}
- ]
- sesv2.tag_resource(ResourceArn=cn_arn, Tags=[{"Key": "ck", "Value": "v"}])
- assert sesv2.list_tags_for_resource(ResourceArn=aws_arn)["Tags"] == [
- {"Key": "ck", "Value": "v"}
- ]
- sesv2.delete_tenant(TenantName=name)
- sesv2.delete_configuration_set(ConfigurationSetName=cs)
diff --git a/tests/test_ses_v2.py b/tests/test_ses_v2.py
index f77163c7..e4bebb0c 100644
--- a/tests/test_ses_v2.py
+++ b/tests/test_ses_v2.py
@@ -1,7 +1,11 @@
import asyncio
+import copy
import json
+import re
+import uuid
import pytest
+from botocore.exceptions import ClientError
from ministack.core.responses import set_request_account_id, set_request_region
@@ -260,6 +264,7 @@ def test_ses_v2_configuration_set_tag_resource_uses_parser_backed_resource_arn(s
[
"not-an-arn",
f"arn:aws:ses:{REGION}:{ACCOUNT_ID}",
+ _arn("identity", "parser.example.com", partition="aws-cn"),
_arn("identity", "parser.example.com", service="sesv2"),
_arn("identity", "parser.example.com", region="us-west-2"),
_arn("identity", "parser.example.com", account="111111111111"),
@@ -302,22 +307,6 @@ def test_ses_v2_tag_apis_reject_invalid_resource_arns_before_touching_tags(ses_v
assert body["Tags"] == [{"Key": "keep", "Value": "yes"}]
-def test_ses_v2_tag_apis_accept_foreign_partitions_on_one_store(ses_v2):
- identity = "partition.example.com"
- aws_arn = _arn("identity", identity)
- cn_arn = _arn("identity", identity, partition="aws-cn")
- _call(ses_v2, "POST", "/v2/email/identities", body={"EmailIdentity": identity})
-
- status, _ = _call(
- ses_v2, "POST", body={"ResourceArn": cn_arn, "Tags": [{"Key": "team", "Value": "email"}]}
- )
- assert status == 200
- for arn in (aws_arn, cn_arn):
- status, body = _call(ses_v2, "GET", query={"ResourceArn": [arn]})
- assert status == 200
- assert body["Tags"] == [{"Key": "team", "Value": "email"}]
-
-
@pytest.mark.parametrize("method", ["GET", "POST", "DELETE"])
def test_ses_v2_tag_apis_reject_missing_local_resources_before_touching_tags(ses_v2, method):
missing_arn = _arn("identity", "missing.example.com")
@@ -723,3 +712,563 @@ def test_ses_v2_send_bulk_email_rejects_missing_template_without_recording_sends
assert status == 404
assert body["name"] == "NotFoundException"
assert ses_v2._sent_emails_list() == []
+
+
+# ── Tenants and resource associations ──
+
+
+def _tenant_error(client, operation, code, message, **params):
+ with pytest.raises(ClientError) as caught:
+ getattr(client, operation)(**params)
+ response = caught.value.response
+ assert response["Error"] == {"Code": code, "Message": message}
+ assert response["ResponseMetadata"]["HTTPStatusCode"] == (404 if code == "NotFoundException" else 400)
+
+
+def test_tenant_configuration_set_association_lifecycle(sesv2):
+ name = "tenant-" + uuid.uuid4().hex[:10]
+ tags = [{"Key": "purpose", "Value": "regression"}]
+ sesv2.create_configuration_set(ConfigurationSetName=name, Tags=tags)
+ tenant = sesv2.create_tenant(TenantName=name, Tags=tags)
+ assert re.fullmatch(r"tn-[a-f0-9]{29}", tenant["TenantId"])
+ assert tenant["TenantArn"].endswith(f"tenant/{name}/{tenant['TenantId']}")
+ assert tenant["SendingStatus"] == "ENABLED"
+ assert tenant["Tags"] == tags
+ assert sesv2.get_tenant(TenantName=name)["Tenant"] == {k: v for k, v in tenant.items() if k != "ResponseMetadata"}
+ _tenant_error(
+ sesv2,
+ "create_tenant",
+ "AlreadyExistsException",
+ f"Tenant with name {name} already exists in account 000000000000",
+ TenantName=name,
+ )
+ listed = sesv2.list_tenants(Filter={"TENANT_NAME_CONTAINS": name, "SENDING_STATUS": "ENABLED"})["Tenants"]
+ assert listed == [{k: v for k, v in tenant.items() if k not in ("ResponseMetadata", "Tags")}]
+ assert sesv2.list_tags_for_resource(ResourceArn=tenant["TenantArn"])["Tags"] == tags
+ sesv2.tag_resource(ResourceArn=tenant["TenantArn"], Tags=[{"Key": "updated", "Value": "yes"}])
+ sesv2.untag_resource(ResourceArn=tenant["TenantArn"], TagKeys=["purpose"])
+ assert sesv2.get_tenant(TenantName=name)["Tenant"]["Tags"] == [{"Key": "updated", "Value": "yes"}]
+ arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{name}"
+ sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=arn)
+ _tenant_error(
+ sesv2,
+ "create_tenant_resource_association",
+ "AlreadyExistsException",
+ f"Resources {arn} has already been associated with tenant {name}",
+ TenantName=name,
+ ResourceArn=arn,
+ )
+ assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == [
+ {"ResourceType": "CONFIGURATION_SET", "ResourceArn": arn}
+ ]
+ inverse = sesv2.list_resource_tenants(ResourceArn=arn)["ResourceTenants"]
+ assert inverse[0]["TenantId"] == tenant["TenantId"]
+ assert inverse[0]["ResourceArn"] == arn
+ _tenant_error(
+ sesv2,
+ "delete_configuration_set",
+ "BadRequestException",
+ f"Cannot delete <{arn}> because it has tenant associations. Remove all tenant associations and try again.",
+ ConfigurationSetName=name,
+ )
+ sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=arn)
+ sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=arn)
+ assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == []
+ sesv2.delete_tenant(TenantName=name)
+ _tenant_error(sesv2, "get_tenant", "NotFoundException", f"The requested tenant <{name}> does not exist.", TenantName=name)
+ _tenant_error(
+ sesv2,
+ "list_tags_for_resource",
+ "NotFoundException",
+ f"No Tenant present with name: {name}with tenantId: {tenant['TenantId']}",
+ ResourceArn=tenant["TenantArn"],
+ )
+ for operation, params in [
+ ("tag_resource", {"Tags": [{"Key": "purpose", "Value": "regression"}]}),
+ ("untag_resource", {"TagKeys": ["purpose"]}),
+ ]:
+ _tenant_error(sesv2, operation, "NotFoundException", f"No Tenant present with name: {name}with tenantId: {tenant['TenantId']}",
+ ResourceArn=tenant["TenantArn"], **params)
+ sesv2.delete_configuration_set(ConfigurationSetName=name)
+
+
+def test_tenant_invalid_and_missing_resources(sesv2):
+ name = "tenant-errors-" + uuid.uuid4().hex[:10]
+ _tenant_error(
+ sesv2,
+ "create_tenant",
+ "BadRequestException",
+ f"Invalid tenant name <{name} bad>: only alphanumeric ASCII characters, '_', and '-' are allowed.",
+ TenantName=name + " bad",
+ )
+ _tenant_error(
+ sesv2,
+ "create_tenant_resource_association",
+ "NotFoundException",
+ f"The requested tenant <{name}> does not exist.",
+ TenantName=name,
+ ResourceArn="invalid-arn",
+ )
+ sesv2.create_tenant(TenantName=name)
+ _tenant_error(
+ sesv2,
+ "create_tenant_resource_association",
+ "BadRequestException",
+ "Provided resource identifier is not an SES resource",
+ TenantName=name,
+ ResourceArn="invalid-arn",
+ )
+ arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{name}"
+ _tenant_error(
+ sesv2,
+ "create_tenant_resource_association",
+ "NotFoundException",
+ f"Configuration set <{name}> does not exist:",
+ TenantName=name,
+ ResourceArn=arn,
+ )
+ other = arn.replace("us-east-1", "us-west-2")
+ _tenant_error(
+ sesv2,
+ "create_tenant_resource_association",
+ "BadRequestException",
+ f"Resource <{other}> must be in the same region",
+ TenantName=name,
+ ResourceArn=other,
+ )
+ sesv2.delete_tenant(TenantName=name)
+
+
[email protected]("filters,message", [
+ ({"INVALID": "template"},
+ "1 validation error detected: Value at 'filter' failed to satisfy constraint: Map keys must satisfy constraint: [Member must satisfy enum value set: [RESOURCE_TYPE]]"),
+ ({"RESOURCE_TYPE": "bogus"}, "Invalid resource type bogus specified."),
+ ({"RESOURCE_TYPE": "template,configuration-set"},
+ "Invalid resource type template,configuration-set specified."),
+])
+def test_tenant_resource_filter_errors(sesv2, filters, message):
+ name = "tenant-filter-" + uuid.uuid4().hex[:10]
+ sesv2.create_tenant(TenantName=name)
+ _tenant_error(sesv2, "list_tenant_resources", "BadRequestException", message,
+ TenantName=name, Filter=filters)
+ sesv2.delete_tenant(TenantName=name)
+
+
+def test_tenant_sending_status_filter(sesv2):
+ name = "tenant-status-" + uuid.uuid4().hex[:10]
+ sesv2.create_tenant(TenantName=name)
+ _tenant_error(sesv2, "list_tenants", "BadRequestException", "Invalid sending status <bogus>.",
+ Filter={"TENANT_NAME_CONTAINS": name, "SENDING_STATUS": "bogus"})
+ for status in ("REINSTATED", "DISABLED"):
+ assert sesv2.list_tenants(Filter={"TENANT_NAME_CONTAINS": name, "SENDING_STATUS": status})["Tenants"] == []
+ sesv2.delete_tenant(TenantName=name)
+
+
+def test_tenant_template_association_and_delete_with_associations(sesv2):
+ name = "tenant-template-" + uuid.uuid4().hex[:10]
+ sesv2.create_email_template(TemplateName=name, TemplateContent={"Subject": "probe", "Text": "probe"})
+ sesv2.create_configuration_set(ConfigurationSetName=name)
+ template_arn = f"arn:aws:ses:us-east-1:000000000000:template/{name}"
+ config_arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{name}"
+ tenants = [name + suffix for suffix in ("-a", "-b")]
+ for tenant_name in tenants:
+ sesv2.create_tenant(TenantName=tenant_name)
+ for arn in (config_arn, template_arn):
+ sesv2.create_tenant_resource_association(TenantName=tenant_name, ResourceArn=arn)
+ assert sesv2.list_tenant_resources(TenantName=tenant_name, Filter={"RESOURCE_TYPE": "EMAIL_TEMPLATE"})["TenantResources"] == [
+ {"ResourceType": "EMAIL_TEMPLATE", "ResourceArn": template_arn}
+ ]
+ first = sesv2.list_tenant_resources(TenantName=tenant_name, PageSize=1)
+ second = sesv2.list_tenant_resources(TenantName=tenant_name, PageSize=1, NextToken=first["NextToken"])
+ assert first["TenantResources"] + second["TenantResources"] == [
+ {"ResourceType": "CONFIGURATION_SET", "ResourceArn": config_arn},
+ {"ResourceType": "EMAIL_TEMPLATE", "ResourceArn": template_arn},
+ ]
+ assert "NextToken" not in second
+ first = sesv2.list_resource_tenants(ResourceArn=config_arn, PageSize=1)
+ second = sesv2.list_resource_tenants(ResourceArn=config_arn, PageSize=1, NextToken=first["NextToken"])
+ assert [item["TenantName"] for item in first["ResourceTenants"] + second["ResourceTenants"]] == tenants
+ assert "NextToken" not in second
+ sesv2.delete_tenant(TenantName=tenants[0])
+ assert [item["TenantName"] for item in sesv2.list_resource_tenants(ResourceArn=config_arn)["ResourceTenants"]] == tenants[1:]
+ _tenant_error(sesv2, "delete_configuration_set", "BadRequestException",
+ f"Cannot delete <{config_arn}> because it has tenant associations. Remove all tenant associations and try again.",
+ ConfigurationSetName=name)
+ sesv2.delete_tenant(TenantName=tenants[1])
+ assert sesv2.list_resource_tenants(ResourceArn=config_arn)["ResourceTenants"] == []
+ sesv2.delete_configuration_set(ConfigurationSetName=name)
+ sesv2.delete_email_template(TemplateName=name)
+
+
+def test_tenant_state_roundtrip_and_account_region_isolation():
+ from ministack.core.persistence import _json_default, _json_object_hook
+ from ministack.services import ses_v2
+
+ snapshot = copy.deepcopy(ses_v2.get_state())
+ scopes = [
+ ("000000000000", "us-east-1"),
+ ("111111111111", "us-east-1"),
+ ("000000000000", "us-west-2"),
+ ]
+ saved_tenants = {}
+ try:
+ for account, region in scopes:
+ set_request_account_id(account)
+ set_request_region(region)
+ assert "same" not in ses_v2._tenants
+ assert "same" not in ses_v2._tenant_resources
+ status, _, body = ses_v2._tenant_request(
+ "POST", "/tenants", {"TenantName": "same", "Tags": [{"Key": "region", "Value": region}]}
+ )
+ assert status == 200
+ saved_tenants[(account, region)] = json.loads(body)
+ arn = f"arn:aws:ses:{region}:{account}:configuration-set/same"
+ ses_v2._config_sets["same"] = {"ConfigurationSetName": "same"}
+ assert ses_v2._tenant_request(
+ "POST", "/tenants/resources", {"TenantName": "same", "ResourceArn": arn}
+ )[0] == 200
+
+ encoded = json.dumps(ses_v2.get_state(), default=_json_default, sort_keys=True)
+ saved = json.loads(encoded, object_hook=_json_object_hook)
+ ses_v2.reset()
+ for account, region in scopes:
+ set_request_account_id(account)
+ set_request_region(region)
+ assert not ses_v2._tenants
+ assert not ses_v2._tenant_resources
+ ses_v2.load_persisted_state(saved)
+ assert json.dumps(ses_v2.get_state(), default=_json_default, sort_keys=True) == encoded
+ for account, region in scopes:
+ set_request_account_id(account)
+ set_request_region(region)
+ tenant = saved_tenants[(account, region)]
+ assert ses_v2._tenants["same"] == tenant
+ assert ses_v2._ses_tags[tenant["TenantArn"]] == [{"Key": "region", "Value": region}]
+ arn = f"arn:aws:ses:{region}:{account}:configuration-set/same"
+ assert list(ses_v2._tenant_resources["same"]) == [arn]
+ inverse = json.loads(ses_v2._tenant_request(
+ "POST", "/resources/tenants/list", {"ResourceArn": arn}
+ )[2])["ResourceTenants"]
+ assert inverse == [{
+ "TenantName": "same",
+ "TenantId": tenant["TenantId"],
+ "ResourceArn": arn,
+ "AssociatedTimestamp": ses_v2._tenant_resources["same"][arn],
+ }]
+ finally:
+ ses_v2.reset()
+ ses_v2.load_persisted_state(snapshot)
+
+
+def test_tenant_suppression_lifecycle(sesv2):
+ name = "tenant-suppr-" + uuid.uuid4().hex[:10]
+ attrs = {"SuppressedReasons": ["BOUNCE"], "SuppressionScope": "TENANT"}
+ created = sesv2.create_tenant(TenantName=name, SuppressionAttributes=attrs)
+ assert created["SuppressionAttributes"] == attrs
+ assert sesv2.get_tenant(TenantName=name)["Tenant"]["SuppressionAttributes"] == attrs
+ listed = sesv2.list_tenants(Filter={"TENANT_NAME_CONTAINS": name})["Tenants"]
+ assert listed and "SuppressionAttributes" not in listed[0]
+ updated = {"SuppressedReasons": ["BOUNCE", "COMPLAINT"], "SuppressionScope": "ACCOUNT"}
+ sesv2.put_tenant_suppression_attributes(TenantName=name, **updated)
+ assert sesv2.get_tenant(TenantName=name)["Tenant"]["SuppressionAttributes"] == updated
+ sesv2.put_tenant_suppression_attributes(TenantName=name)
+ assert "SuppressionAttributes" not in sesv2.get_tenant(TenantName=name)["Tenant"]
+ sesv2.put_tenant_suppression_attributes(
+ TenantName=name, SuppressedReasons=[], SuppressionScope="TENANT"
+ )
+ assert sesv2.get_tenant(TenantName=name)["Tenant"]["SuppressionAttributes"] == {
+ "SuppressedReasons": [],
+ "SuppressionScope": "TENANT",
+ }
+ sesv2.delete_tenant(TenantName=name)
+
+
+def test_tenant_suppression_validation(sesv2):
+ name = "tenant-supval-" + uuid.uuid4().hex[:10]
+ create_reasons = (
+ "1 validation error detected: Value at 'suppressionAttributes.suppressedReasons'"
+ " failed to satisfy constraint: Member must satisfy constraint:"
+ " [Member must satisfy enum value set: [BOUNCE, COMPLAINT]]"
+ )
+ create_scope = (
+ "1 validation error detected: Value at 'suppressionAttributes.suppressionScope'"
+ " failed to satisfy constraint: Member must satisfy enum value set: [TENANT, ACCOUNT]"
+ )
+ put_reasons = create_reasons.replace("suppressionAttributes.suppressedReasons", "suppressedReasons")
+ put_scope = create_scope.replace("suppressionAttributes.suppressionScope", "suppressionScope")
+ null_reasons = (
+ "1 validation error detected: Value null at 'suppressionAttributes.suppressedReasons'"
+ " failed to satisfy constraint: Member must not be null"
+ )
+ null_scope = (
+ "1 validation error detected: Value null at 'suppressionAttributes.suppressionScope'"
+ " failed to satisfy constraint: Member must not be null"
+ )
+ both_null = "2 validation errors detected: " + "; ".join(
+ [null_reasons.split(": ", 1)[1], null_scope.split(": ", 1)[1]]
+ )
+ both_create = "2 validation errors detected: " + "; ".join(
+ [create_reasons.split(": ", 1)[1], create_scope.split(": ", 1)[1]]
+ )
+ both_put = "2 validation errors detected: " + "; ".join(
+ [put_reasons.split(": ", 1)[1], put_scope.split(": ", 1)[1]]
+ )
+ bad_attrs = {"SuppressedReasons": ["NOPE"], "SuppressionScope": "TENANT"}
+ _tenant_error(sesv2, "create_tenant", "BadRequestException", create_reasons,
+ TenantName=name, SuppressionAttributes=bad_attrs)
+ _tenant_error(sesv2, "create_tenant", "BadRequestException", create_scope,
+ TenantName=name,
+ SuppressionAttributes={"SuppressedReasons": ["BOUNCE"], "SuppressionScope": "NOPE"})
+ _tenant_error(sesv2, "create_tenant", "BadRequestException", both_create,
+ TenantName=name,
+ SuppressionAttributes={"SuppressedReasons": ["NOPE"], "SuppressionScope": "NOPE"})
+ _tenant_error(sesv2, "create_tenant", "BadRequestException",
+ "SuppressedReasons cannot be specified without SuppressionScope.",
+ TenantName=name, SuppressionAttributes={"SuppressedReasons": ["BOUNCE"]})
+ _tenant_error(sesv2, "create_tenant", "BadRequestException",
+ "SuppressionScope cannot be specified without SuppressedReasons.",
+ TenantName=name, SuppressionAttributes={"SuppressionScope": "TENANT"})
+ _tenant_error(sesv2, "create_tenant", "BadRequestException", both_null,
+ TenantName=name, SuppressionAttributes={})
+ _tenant_error(sesv2, "create_tenant", "BadRequestException", null_scope,
+ TenantName=name, SuppressionAttributes={"SuppressedReasons": []})
+ # Precedence: model enum errors beat the name check, which beats pairing rules,
+ # which beat the duplicate check.
+ _tenant_error(sesv2, "create_tenant", "BadRequestException", create_reasons,
+ TenantName="bad name", SuppressionAttributes=bad_attrs)
+ _tenant_error(sesv2, "create_tenant", "BadRequestException",
+ "Invalid tenant name <bad name>: only alphanumeric ASCII characters, '_', and '-' are allowed.",
+ TenantName="bad name", SuppressionAttributes={"SuppressedReasons": ["BOUNCE"]})
+ sesv2.create_tenant(TenantName=name)
+ _tenant_error(sesv2, "create_tenant", "BadRequestException", create_reasons,
+ TenantName=name, SuppressionAttributes=bad_attrs)
+ _tenant_error(sesv2, "create_tenant", "BadRequestException",
+ "SuppressedReasons cannot be specified without SuppressionScope.",
+ TenantName=name, SuppressionAttributes={"SuppressedReasons": ["BOUNCE"]})
+ _tenant_error(sesv2, "put_tenant_suppression_attributes", "BadRequestException", put_reasons,
+ TenantName=name, SuppressedReasons=["NOPE"], SuppressionScope="TENANT")
+ _tenant_error(sesv2, "put_tenant_suppression_attributes", "BadRequestException", put_scope,
+ TenantName=name, SuppressedReasons=["BOUNCE"], SuppressionScope="NOPE")
+ _tenant_error(sesv2, "put_tenant_suppression_attributes", "BadRequestException", both_put,
+ TenantName=name, SuppressedReasons=["NOPE"], SuppressionScope="NOPE")
+ _tenant_error(sesv2, "put_tenant_suppression_attributes", "BadRequestException",
+ "SuppressedReasons cannot be specified without SuppressionScope.",
+ TenantName=name, SuppressedReasons=["BOUNCE"])
+ _tenant_error(sesv2, "put_tenant_suppression_attributes", "BadRequestException",
+ "SuppressionScope is required when SuppressedReasons are provided. Valid values are: TENANT, ACCOUNT",
+ TenantName=name, SuppressedReasons=[])
+ _tenant_error(sesv2, "put_tenant_suppression_attributes", "BadRequestException",
+ "SuppressionScope cannot be specified without SuppressedReasons.",
+ TenantName=name, SuppressionScope="TENANT")
+ missing = name + "-missing"
+ _tenant_error(sesv2, "put_tenant_suppression_attributes", "BadRequestException", put_reasons,
+ TenantName=missing, SuppressedReasons=["NOPE"], SuppressionScope="TENANT")
+ _tenant_error(sesv2, "put_tenant_suppression_attributes", "BadRequestException",
+ "SuppressionScope cannot be specified without SuppressedReasons.",
+ TenantName=missing, SuppressionScope="TENANT")
+ _tenant_error(sesv2, "put_tenant_suppression_attributes", "NotFoundException",
+ f"The requested tenant <{missing}> does not exist.", TenantName=missing)
+ sesv2.delete_tenant(TenantName=name)
+
+
+def test_tenant_list_ordering(sesv2):
+ prefix = "tenant-ord-" + uuid.uuid4().hex[:10]
+ first, second = prefix + "-zz", prefix + "-aa"
+ sesv2.create_tenant(TenantName=first)
+ sesv2.create_tenant(TenantName=second)
+ names = [
+ t["TenantName"]
+ for t in sesv2.list_tenants(Filter={"TENANT_NAME_CONTAINS": prefix})["Tenants"]
+ ]
+ assert names == [second, first]
+ cs_b, cs_a = prefix + "-cs-b", prefix + "-cs-a"
+ sesv2.create_configuration_set(ConfigurationSetName=cs_b)
+ sesv2.create_configuration_set(ConfigurationSetName=cs_a)
+ dom = prefix + ".example.com"
+ sesv2.create_email_identity(EmailIdentity=dom)
+ arns = [
+ f"arn:aws:ses:us-east-1:000000000000:{kind}/{leaf}"
+ for kind, leaf in [
+ ("configuration-set", cs_b),
+ ("identity", dom),
+ ("configuration-set", cs_a),
+ ]
+ ]
+ for arn in arns:
+ sesv2.create_tenant_resource_association(TenantName=first, ResourceArn=arn)
+ listed = sesv2.list_tenant_resources(TenantName=first)["TenantResources"]
+ assert [item["ResourceArn"] for item in listed] == sorted(arns)
+ for arn in arns:
+ sesv2.delete_tenant_resource_association(TenantName=first, ResourceArn=arn)
+ sesv2.delete_tenant(TenantName=first)
+ sesv2.delete_tenant(TenantName=second)
+ sesv2.delete_configuration_set(ConfigurationSetName=cs_b)
+ sesv2.delete_configuration_set(ConfigurationSetName=cs_a)
+ sesv2.delete_email_identity(EmailIdentity=dom)
+
+
+def test_tenant_resource_tenants_keep_creation_order(sesv2):
+ prefix = "tenant-rto-" + uuid.uuid4().hex[:10]
+ cs = prefix + "-cs"
+ sesv2.create_configuration_set(ConfigurationSetName=cs)
+ arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{cs}"
+ early, late = prefix + "-early", prefix + "-late"
+ sesv2.create_tenant(TenantName=early)
+ sesv2.create_tenant(TenantName=late)
+ sesv2.create_tenant_resource_association(TenantName=late, ResourceArn=arn)
+ sesv2.create_tenant_resource_association(TenantName=early, ResourceArn=arn)
+ names = [
+ item["TenantName"]
+ for item in sesv2.list_resource_tenants(ResourceArn=arn)["ResourceTenants"]
+ ]
+ assert names == [early, late]
+ sesv2.delete_tenant(TenantName=early)
+ sesv2.delete_tenant(TenantName=late)
+ sesv2.delete_configuration_set(ConfigurationSetName=cs)
+
+
+def test_tenant_resource_delete_guards(sesv2, ses):
+ prefix = "tenant-guard-" + uuid.uuid4().hex[:10]
+ cs, tpl, dom = prefix + "-cs", prefix + "-tpl", prefix + ".example.com"
+ sesv2.create_configuration_set(ConfigurationSetName=cs)
+ sesv2.create_email_template(TemplateName=tpl, TemplateContent={"Subject": "s", "Text": "t"})
+ sesv2.create_email_identity(EmailIdentity=dom)
+ name = prefix + "-t"
+ sesv2.create_tenant(TenantName=name)
+ arns = {
+ kind: f"arn:aws:ses:us-east-1:000000000000:{kind}/{leaf}"
+ for kind, leaf in [("configuration-set", cs), ("template", tpl), ("identity", dom)]
+ }
+ for arn in arns.values():
+ sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=arn)
+ for operation, params in [
+ ("delete_configuration_set", {"ConfigurationSetName": cs}),
+ ("delete_email_template", {"TemplateName": tpl}),
+ ("delete_email_identity", {"EmailIdentity": dom}),
+ ]:
+ kind = {"delete_configuration_set": "configuration-set",
+ "delete_email_template": "template",
+ "delete_email_identity": "identity"}[operation]
+ _tenant_error(sesv2, operation, "BadRequestException",
+ f"Cannot delete <{arns[kind]}> because it has tenant associations."
+ " Remove all tenant associations and try again.",
+ **params)
+ for operation, params in [
+ ("delete_configuration_set", {"ConfigurationSetName": cs}),
+ ("delete_template", {"TemplateName": tpl}),
+ ("delete_identity", {"Identity": dom}),
+ ]:
+ kind = {"delete_configuration_set": "configuration-set",
+ "delete_template": "template",
+ "delete_identity": "identity"}[operation]
+ _tenant_error(ses, operation, "InvalidParameterValue",
+ f"Cannot delete <{arns[kind]}> because it has tenant associations."
+ " Remove all tenant associations and try again.",
+ **params)
+ for arn in arns.values():
+ sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=arn)
+ sesv2.delete_tenant(TenantName=name)
+ sesv2.delete_configuration_set(ConfigurationSetName=cs)
+ sesv2.delete_email_template(TemplateName=tpl)
+ sesv2.delete_email_identity(EmailIdentity=dom)
+
+
+def test_tenant_association_rejects_non_ses_arn(sesv2):
+ name = "tenant-nonses-" + uuid.uuid4().hex[:10]
+ sesv2.create_tenant(TenantName=name)
+ _tenant_error(sesv2, "create_tenant_resource_association", "BadRequestException",
+ "Provided ARN is not in SES resource ARN format",
+ TenantName=name, ResourceArn=f"arn:aws:s3:::{name}-bucket")
+ _tenant_error(sesv2, "list_tags_for_resource", "NotFoundException",
+ f"No Tenant present with name: nullwith tenantId: {name}",
+ ResourceArn=f"arn:aws:ses:us-east-1:000000000000:tenant/{name}")
+ sesv2.delete_tenant(TenantName=name)
+
+
+def test_tenant_list_pagesize_bounds(sesv2):
+ name = "tenant-pages-" + uuid.uuid4().hex[:10]
+ sesv2.create_tenant(TenantName=name)
+ _tenant_error(sesv2, "list_tenants", "BadRequestException",
+ "1 validation error detected: Value '0' at 'pageSize' failed to satisfy"
+ " constraint: Member must have value greater than or equal to 1",
+ PageSize=0)
+ over = ("1 validation error detected: Value '101' at 'pageSize' failed to satisfy"
+ " constraint: Member must have value less than or equal to 100")
+ _tenant_error(sesv2, "list_tenants", "BadRequestException", over, PageSize=101)
+ _tenant_error(sesv2, "list_tenant_resources", "BadRequestException", over,
+ TenantName=name, PageSize=101)
+ cs = name + "-cs"
+ sesv2.create_configuration_set(ConfigurationSetName=cs)
+ arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{cs}"
+ _tenant_error(sesv2, "list_resource_tenants", "BadRequestException", over,
+ ResourceArn=arn, PageSize=101)
+ sesv2.delete_tenant(TenantName=name)
+ sesv2.delete_configuration_set(ConfigurationSetName=cs)
+
+
+def test_tenant_v1_resources_can_be_associated(sesv2, ses):
+ prefix = "tenant-v1res-" + uuid.uuid4().hex[:10]
+ cs, dom = prefix + "-cs", prefix + ".example.com"
+ ses.create_configuration_set(ConfigurationSet={"Name": cs})
+ ses.verify_domain_identity(Domain=dom)
+ name = prefix + "-t"
+ sesv2.create_tenant(TenantName=name)
+ cs_arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{cs}"
+ idn_arn = f"arn:aws:ses:us-east-1:000000000000:identity/{dom}"
+ sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=cs_arn)
+ sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=idn_arn)
+ assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == [
+ {"ResourceType": "CONFIGURATION_SET", "ResourceArn": cs_arn},
+ {"ResourceType": "EMAIL_IDENTITY", "ResourceArn": idn_arn},
+ ]
+ blocked = "because it has tenant associations. Remove all tenant associations and try again."
+ _tenant_error(sesv2, "delete_configuration_set", "BadRequestException",
+ f"Cannot delete <{cs_arn}> {blocked}", ConfigurationSetName=cs)
+ _tenant_error(sesv2, "delete_email_identity", "BadRequestException",
+ f"Cannot delete <{idn_arn}> {blocked}", EmailIdentity=dom)
+ _tenant_error(ses, "delete_configuration_set", "InvalidParameterValue",
+ f"Cannot delete <{cs_arn}> {blocked}", ConfigurationSetName=cs)
+ _tenant_error(ses, "delete_identity", "InvalidParameterValue",
+ f"Cannot delete <{idn_arn}> {blocked}", Identity=dom)
+ sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=cs_arn)
+ sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=idn_arn)
+ sesv2.delete_tenant(TenantName=name)
+ ses.delete_configuration_set(ConfigurationSetName=cs)
+ ses.delete_identity(Identity=dom)
+
+
+def test_tenant_association_normalizes_foreign_partitions(sesv2):
+ prefix = "tenant-part-" + uuid.uuid4().hex[:10]
+ cs = prefix + "-cs"
+ sesv2.create_configuration_set(ConfigurationSetName=cs)
+ name = prefix + "-t"
+ tenant = sesv2.create_tenant(TenantName=name)
+ aws_arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{cs}"
+ cn_arn = f"arn:aws-cn:ses:us-east-1:000000000000:configuration-set/{cs}"
+ sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=cn_arn)
+ assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == [
+ {"ResourceType": "CONFIGURATION_SET", "ResourceArn": aws_arn}
+ ]
+ _tenant_error(sesv2, "create_tenant_resource_association", "AlreadyExistsException",
+ f"Resources {aws_arn} has already been associated with tenant {name}",
+ TenantName=name, ResourceArn=aws_arn)
+ inverse = sesv2.list_resource_tenants(ResourceArn=cn_arn)["ResourceTenants"]
+ assert [(item["TenantName"], item["ResourceArn"]) for item in inverse] == [(name, aws_arn)]
+ _tenant_error(sesv2, "delete_configuration_set", "BadRequestException",
+ f"Cannot delete <{aws_arn}> because it has tenant associations."
+ " Remove all tenant associations and try again.",
+ ConfigurationSetName=cs)
+ sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=aws_arn)
+ assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == []
+ sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=aws_arn)
+ sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=cn_arn)
+ assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == []
+ xacct = f"arn:aws-cn:ses:us-east-1:111122223333:configuration-set/{cs}"
+ _tenant_error(sesv2, "create_tenant_resource_association", "BadRequestException",
+ f"Resource <{xacct}> must be in the same account",
+ TenantName=name, ResourceArn=xacct)
+ # Tag APIs keep rejecting a non-aws partition.
+ with pytest.raises(ClientError):
+ sesv2.tag_resource(ResourceArn=cn_arn, Tags=[{"Key": "ck", "Value": "v"}])
+ sesv2.delete_tenant(TenantName=name)
+ sesv2.delete_configuration_set(ConfigurationSetName=cs)