Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(sns): add Get/SetPlatformApplicationAttributes (#1515)
Johannes Grumböckceee1b5ee0d6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 65cf0603..f32c3ba4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added+- **SNS — `GetPlatformApplicationAttributes` / `SetPlatformApplicationAttributes`** — a platform application could be created and deleted but never read back or updated: both actions answered `400 InvalidAction`, so `terraform plan` on an `aws_sns_platform_application` failed at refresh (`reading SNS Platform Application (...): Unknown action: GetPlatformApplicationAttributes`) and the resource could never reach a clean state. Both now answer with the documented shapes — `Get` returns the attribute map as `entry` key/value pairs, `Set` merges the supplied entries (`PlatformCredential`, `PlatformPrincipal`, the `Event*` topic ARNs, `*FeedbackRoleArn`, `Enabled`, ...) and returns only `ResponseMetadata` — with `InvalidParameter` (400) for a missing `PlatformApplicationArn` or `Attributes` and `NotFound` (404) for an unknown application. `CreatePlatformApplication` also seeds `Enabled=true`, as AWS reports for a newly created application.+### Fixed- **S3 — a presigned upload no longer drops the `x-amz-*` headers it was signed with** — a presigned URL is sent by a caller who has only the URL and a body, so SigV4 lets the `x-amz-*` headers an operation asked for be hoisted into the query string, where the signature covers them exactly as a signed header would. SDKs presign that way and real S3 applies those params as the headers they stand for. MiniStack only ever read headers, so a presigned `PutObject` carrying user metadata in its query string answered `200` and stored the object with no metadata at all. Hoisted `x-amz-*` params are now folded back into the request headers before routing (user metadata, storage class, tagging, ACL, SSE and copy source) while an explicitly sent header still wins over its hoisted twin, and the SigV4 signing params are never mistaken for one. Contributed by @dennmart.- **CloudFormation — `Fn::Sub` honors the `${!Literal}` escape** — the leading `!` was not recognized, so the name fell through every lookup and rendered as `!Literal` with the braces consumed; `${!Literal}` now renders as the literal `${Literal}` and no longer registers a dependency on a resource of that name. An `AWS::IoT::Policy` pinned to `${!iot:Connection.Thing.ThingName}` deployed with a document matching nothing, so the policy denied every connect, publish and subscribe while the stack still reported `CREATE_COMPLETE`. Reported by @iot-rocket.diff --git a/README.md b/README.mdindex 96347989..c9055205 100644--- a/README.md+++ b/README.md@@ -398,7 +398,7 @@ subnet = ec2.create_subnet(|---------|-----------|-------|| **S3** | CreateBucket, DeleteBucket, ListBuckets, HeadBucket, PutObject, GetObject, DeleteObject, HeadObject, CopyObject, ListObjects v1/v2, DeleteObjects, GetBucketVersioning, PutBucketVersioning, GetBucketEncryption, PutBucketEncryption, DeleteBucketEncryption, GetBucketLifecycleConfiguration, PutBucketLifecycleConfiguration, DeleteBucketLifecycle, GetBucketCors, PutBucketCors, DeleteBucketCors, GetBucketAcl, PutBucketAcl, GetBucketTagging, PutBucketTagging, DeleteBucketTagging, GetBucketPolicy, PutBucketPolicy, DeleteBucketPolicy, GetBucketNotificationConfiguration, PutBucketNotificationConfiguration, GetBucketLogging, PutBucketLogging, ListObjectVersions, CreateMultipartUpload, UploadPart, CompleteMultipartUpload, AbortMultipartUpload, PutObjectLockConfiguration, GetObjectLockConfiguration, PutObjectRetention, GetObjectRetention, PutObjectLegalHold, GetObjectLegalHold, PutBucketReplication, GetBucketReplication, DeleteBucketReplication, GetObjectTagging, PutObjectTagging, DeleteObjectTagging | Optional disk persistence via `S3_PERSIST=1`; Object Lock with retention & legal hold enforcement on delete; object tags are versioned (`?tagging&versionId=…` reads, writes, and deletes the per-version tag set) || **SQS** | CreateQueue, DeleteQueue, ListQueues, GetQueueUrl, GetQueueAttributes, SetQueueAttributes, PurgeQueue, SendMessage, ReceiveMessage, DeleteMessage, ChangeMessageVisibility, ChangeMessageVisibilityBatch, SendMessageBatch, DeleteMessageBatch, TagQueue, UntagQueue, ListQueueTags | Both Query API and JSON protocol; FIFO queues with deduplication; DLQ support |-| **SNS** | CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes, Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, GetSubscriptionAttributes, SetSubscriptionAttributes, ConfirmSubscription, Publish, PublishBatch, TagResource, UntagResource, ListTagsForResource, CreatePlatformApplication, CreatePlatformEndpoint, GetEndpointAttributes, SetEndpointAttributes, DeleteEndpoint, DeletePlatformApplication | SNS→SQS fanout delivery; SNS→Lambda fanout (asynchronous delivery); FIFO topics with 5-minute deduplication, sequence numbers, content-based deduplication, and subscription validation; mobile-push endpoint lifecycle with device-token dedup and `Publish` to platform-endpoint `TargetArn` |+| **SNS** | CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes, Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, GetSubscriptionAttributes, SetSubscriptionAttributes, ConfirmSubscription, Publish, PublishBatch, TagResource, UntagResource, ListTagsForResource, CreatePlatformApplication, ListPlatformApplications, GetPlatformApplicationAttributes, SetPlatformApplicationAttributes, CreatePlatformEndpoint, GetEndpointAttributes, SetEndpointAttributes, DeleteEndpoint, DeletePlatformApplication | SNS→SQS fanout delivery; SNS→Lambda fanout (asynchronous delivery); FIFO topics with 5-minute deduplication, sequence numbers, content-based deduplication, and subscription validation; mobile-push endpoint lifecycle with device-token dedup and `Publish` to platform-endpoint `TargetArn` || **DynamoDB** | CreateTable, UpdateTable, DeleteTable, DescribeTable, ListTables, PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem, TransactWriteItems, TransactGetItems, DescribeTimeToLive, UpdateTimeToLive, DescribeContinuousBackups, UpdateContinuousBackups, DescribeEndpoints, TagResource, UntagResource, ListTagsOfResource, EnableKinesisStreamingDestination, DisableKinesisStreamingDestination, DescribeKinesisStreamingDestination, UpdateKinesisStreamingDestination | TTL enforced via thread-safe background reaper (60s cadence); DynamoDB Streams — `StreamSpecification` emits INSERT/MODIFY/REMOVE records on all write operations, respects `StreamViewType`; Kinesis streaming destinations (`aws_dynamodb_kinesis_streaming_destination`) fan item mutations out into any Kinesis stream by ARN while the destination is ACTIVE || **DynamoDB Streams** | ListStreams, DescribeStream, GetShardIterator, GetRecords | Reads records emitted by the main DynamoDB service via `boto3.client("dynamodbstreams")` — single synthetic shard per stream; `TRIM_HORIZON`/`LATEST`/`AT_SEQUENCE_NUMBER`/`AFTER_SEQUENCE_NUMBER` iterator types; `NEW_AND_OLD_IMAGES`, `NEW_IMAGE`, `OLD_IMAGE`, `KEYS_ONLY` view types; opaque base64 iterator tokens || **Lambda** | CreateFunction, DeleteFunction, GetFunction, GetFunctionConfiguration, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration, AddPermission, RemovePermission, GetPolicy, ListVersionsByFunction, PublishVersion, CreateAlias, GetAlias, UpdateAlias, DeleteAlias, ListAliases, TagResource, UntagResource, ListTags, CreateEventSourceMapping, DeleteEventSourceMapping, GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping, CreateFunctionUrlConfig, GetFunctionUrlConfig, UpdateFunctionUrlConfig, DeleteFunctionUrlConfig, ListFunctionUrlConfigs, PutFunctionConcurrency, GetFunctionConcurrency, DeleteFunctionConcurrency, PutFunctionEventInvokeConfig, GetFunctionEventInvokeConfig, DeleteFunctionEventInvokeConfig, PublishLayerVersion, GetLayerVersion, GetLayerVersionByArn, ListLayerVersions, DeleteLayerVersion, ListLayers, AddLayerVersionPermission, RemoveLayerVersionPermission, GetLayerVersionPolicy, CheckpointDurableExecution, GetDurableExecution, GetDurableExecutionState, GetDurableExecutionHistory, ListDurableExecutionsByFunction, StopDurableExecution, SendDurableExecutionCallbackSuccess, SendDurableExecutionCallbackFailure, SendDurableExecutionCallbackHeartbeat | Python and Node.js runtimes execute with warm worker pool; `provided.al2023`/`provided.al2` runtimes execute via Docker RIE (Go, Rust, C++ support); `Publish=True` creates immutable numbered versions; Code via `ZipFile`, `S3Bucket`/`S3Key` (with optional `S3ObjectVersion`), or `ImageUri` (Docker image); `PackageType: Image` pulls and invokes user-provided Docker images via Lambda RIE; SQS, Kinesis, and DynamoDB Streams event source mappings; Function URL CRUD; Lambda Layers CRUD; Aliases; Concurrency; EventInvokeConfig; **Durable Functions** — `CreateFunction` accepts `DurableConfig`; checkpoint/state/history/list/stop ops at the preview API (`2025-12-01`); external `SendCallback{Success,Failure,Heartbeat}` resume the SDK across invocations; resume scheduler fires WAIT expiries, callback timeouts, and step-retry backoffs; verified against the official `aws-durable-execution-sdk-python` and `aws-durable-execution-sdk-java`; **X-Ray active tracing** — `TracingConfig.Mode=Active` injects `_X_AMZN_TRACE_ID` (`Root=1-<hex>-<hex>;Parent=<hex>;Sampled=1`) into the runtime per invocation so the AWS X-Ray SDK runs without `Missing AWS Lambda trace data`; supported on the warm Python / Node executor, provided runtimes, and the local subprocess fallback (docker RIE upstream does not implement X-Ray and is logged but unsupported) |diff --git a/ministack/services/sns.py b/ministack/services/sns.pyindex ee780725..76f2c3c8 100644--- a/ministack/services/sns.py+++ b/ministack/services/sns.py@@ -7,6 +7,7 @@ Supports: CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttrPublish, PublishBatch,ListTagsForResource, TagResource, UntagResource,CreatePlatformApplication, ListPlatformApplications,+ GetPlatformApplicationAttributes, SetPlatformApplicationAttributes,DeletePlatformApplication,CreatePlatformEndpoint, GetEndpointAttributes, SetEndpointAttributes,DeleteEndpoint.@@ -184,6 +185,8 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, que"UntagResource": _untag_resource,"CreatePlatformApplication": _create_platform_application,"ListPlatformApplications": _list_platform_applications,+ "GetPlatformApplicationAttributes": _get_platform_application_attributes,+ "SetPlatformApplicationAttributes": _set_platform_application_attributes,"CreatePlatformEndpoint": _create_platform_endpoint,"DeletePlatformApplication": _delete_platform_application,"GetEndpointAttributes": _get_endpoint_attributes,@@ -1179,6 +1182,8 @@ def _create_platform_application(params):attrs[key] = vali += 1+ attrs.setdefault("Enabled", "true")+_platform_applications[arn] = {"arn": arn,"name": name,@@ -1226,6 +1231,61 @@ def _list_platform_applications(params):f"{next_token_xml}</ListPlatformApplicationsResult>")+def _get_platform_application_attributes(params):+ # https://docs.aws.amazon.com/sns/latest/api/API_GetPlatformApplicationAttributes.html+ # PlatformApplicationArn is required (InvalidParameter/400); an unknown ARN+ # is NotFound/404. Attributes are returned as entry key/value pairs, e.g.+ # Enabled, AllowEndpointPolicies, AuthenticationMethod and the Event* topic+ # ARNs. Unlike the endpoint APIs there is no separate "Enabled" default in+ # the request, so CreatePlatformApplication seeds it.+ arn = _p(params, "PlatformApplicationArn")+ if not arn:+ return _error("InvalidParameter",+ "Invalid parameter: PlatformApplicationArn Reason: no value for required parameter",+ 400)+ app = _platform_applications.get(arn)+ if app is None:+ return _error("NotFound",+ f"PlatformApplication does not exist: {arn}", 404)+ entries = "".join(+ f"<entry><key>{_xml_escape(k)}</key><value>{_xml_escape(v)}</value></entry>"+ for k, v in app.get("attributes", {}).items()+ )+ return _xml(200, "GetPlatformApplicationAttributesResponse",+ f"<GetPlatformApplicationAttributesResult>"+ f"<Attributes>{entries}</Attributes>"+ f"</GetPlatformApplicationAttributesResult>")+++def _set_platform_application_attributes(params):+ # https://docs.aws.amazon.com/sns/latest/api/API_SetPlatformApplicationAttributes.html+ # Both PlatformApplicationArn and Attributes are required; the call merges+ # the supplied entries into the existing attribute map (PlatformCredential,+ # PlatformPrincipal, Event* topic ARNs, *FeedbackRoleArn, Enabled, ...).+ # The response body carries only ResponseMetadata.+ arn = _p(params, "PlatformApplicationArn")+ if not arn:+ return _error("InvalidParameter",+ "Invalid parameter: PlatformApplicationArn Reason: no value for required parameter",+ 400)+ updates = {}+ i = 1+ while _p(params, f"Attributes.entry.{i}.key"):+ updates[_p(params, f"Attributes.entry.{i}.key")] = \+ _p(params, f"Attributes.entry.{i}.value")+ i += 1+ if not updates:+ return _error("InvalidParameter",+ "Invalid parameter: Attributes Reason: no value for required parameter",+ 400)+ app = _platform_applications.get(arn)+ if app is None:+ return _error("NotFound",+ f"PlatformApplication does not exist: {arn}", 404)+ app["attributes"].update(updates)+ return _xml(200, "SetPlatformApplicationAttributesResponse", "")++def _create_platform_endpoint(params):app_arn = _p(params, "PlatformApplicationArn")token = _p(params, "Token")diff --git a/tests/test_sns.py b/tests/test_sns.pyindex 187d8e46..8dc5804d 100644--- a/tests/test_sns.py+++ b/tests/test_sns.py@@ -1594,6 +1594,62 @@ def test_sns_list_platform_applications(sns):sns.delete_platform_application(PlatformApplicationArn=app_arn)+def test_sns_get_platform_application_attributes(sns):+ name = f"intg-sns-get-app-attrs-{_uuid_mod.uuid4().hex[:8]}"+ app_arn = sns.create_platform_application(+ Name=name, Platform="GCM", Attributes={"PlatformCredential": "cred-xyz"},+ )["PlatformApplicationArn"]+ try:+ attrs = sns.get_platform_application_attributes(+ PlatformApplicationArn=app_arn,+ )["Attributes"]+ # AWS reports the application as enabled right after creation.+ assert attrs["Enabled"] == "true"+ finally:+ sns.delete_platform_application(PlatformApplicationArn=app_arn)+++def test_sns_get_platform_application_attributes_not_found(sns):+ missing = (+ f"arn:aws:sns:us-east-1:000000000000:app/GCM/"+ f"intg-sns-missing-{_uuid_mod.uuid4().hex[:8]}"+ )+ with pytest.raises(ClientError) as exc:+ sns.get_platform_application_attributes(PlatformApplicationArn=missing)+ assert exc.value.response["Error"]["Code"] == "NotFound"+++def test_sns_set_platform_application_attributes(sns):+ name = f"intg-sns-set-app-attrs-{_uuid_mod.uuid4().hex[:8]}"+ app_arn = sns.create_platform_application(+ Name=name, Platform="GCM", Attributes={"PlatformCredential": "cred-xyz"},+ )["PlatformApplicationArn"]+ try:+ sns.set_platform_application_attributes(+ PlatformApplicationArn=app_arn,+ Attributes={"Enabled": "false", "EventEndpointCreated": "arn:aws:sns:us-east-1:000000000000:evt"},+ )+ attrs = sns.get_platform_application_attributes(+ PlatformApplicationArn=app_arn,+ )["Attributes"]+ assert attrs["Enabled"] == "false"+ assert attrs["EventEndpointCreated"].endswith(":evt")+ finally:+ sns.delete_platform_application(PlatformApplicationArn=app_arn)+++def test_sns_set_platform_application_attributes_not_found(sns):+ missing = (+ f"arn:aws:sns:us-east-1:000000000000:app/GCM/"+ f"intg-sns-missing-{_uuid_mod.uuid4().hex[:8]}"+ )+ with pytest.raises(ClientError) as exc:+ sns.set_platform_application_attributes(+ PlatformApplicationArn=missing, Attributes={"Enabled": "false"},+ )+ assert exc.value.response["Error"]["Code"] == "NotFound"++def test_sns_platform_applications_and_endpoints_are_region_scoped(sns):west = _regional_client("sns", "us-west-2")name = f"mr-sns-platform-region-{_uuid_mod.uuid4().hex[:8]}"