Skip to content

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

fix(sqs, sns): enforce queue and topic policies (#1831)

Adrian-Ryan Acalaa579b4747d5c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 21c06af7..acac654f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,12 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
+- **SNS — `AddPermission` and `RemovePermission`** — they append to and prune the topic's `Policy` attribute with the AWS statement shape (bare account ids, lowercase `sns:` actions), mirroring the long-standing SQS pair, and a duplicate label is `InvalidParameterException`.
+
+### Fixed
+
+- **SQS/SNS — queue and topic policies are enforced under `AUTH=true`** — the `Policy` attributes were stored but never evaluated, so S3→SQS and SNS→SQS deliveries landed and cross-account send/publish failed regardless of the policy. Same-account calls now pass unless the policy carries an explicit Deny; cross-account calls need an explicit Allow (`AccessDenied` for SQS, `AuthorizationError` for SNS); S3 and SNS deliveries are dropped unless the destination policy Allows the calling service with its `aws:SourceArn`/`aws:SourceAccount` conditions, exactly like real AWS — including queues and topics with no policy at all. With auth disabled every path stays permissive. `GetQueueUrl` accepts `QueueOwnerAWSAccountId`.
+- **S3 — notification destinations are validated at PUT time** — configuring an SQS/SNS target whose policy does not let S3 publish now fails the whole `PutBucketNotificationConfiguration` with `InvalidArgument` ("Unable to validate the following destination configurations"), like real S3, when `AUTH=true`; with auth disabled the probe checks existence only. SQS/SNS targets may live in another account when their policy allows the delivery. The `SkipDestinationValidation` option skips the probe (and the test event).
- **Bedrock AgentCore — opt-in Docker runtime** — set `MINISTACK_AGENTCORE_DOCKER=1` to start the declared `containerConfiguration.containerUri` image on first invocation, connect via a localhost port when MiniStack runs on the host or via MiniStack's Docker network when containerized, call `/ping`, and forward `InvokeAgentRuntime` to `/invocations` on port 8080. The container is reused and removed on update, delete, or reset. Container and worker HTTP errors become `RuntimeClientError` (424); caller credentials are not forwarded. Without Docker mode, the existing deterministic echo remains for SDK tests. This covers HTTP only and does not emulate AWS IAM/VPC isolation or model inference.
- **CloudWatch Logs — delivery destination policy** — `PutDeliveryDestinationPolicy`, `GetDeliveryDestinationPolicy`, `DeleteDeliveryDestinationPolicy`. Required by an operator that authorizes `delivery.logs.amazonaws.com` to create deliveries to a `DeliveryDestination` (e.g. CloudFront access-log delivery to a log group) — `PutDeliveryDestinationPolicy` previously had no route, blocking the delivery from ever being created. Contributed by @fabio-andre-rodrigues.
- **S3 — object annotations** — `PutObjectAnnotation`, `GetObjectAnnotation`, `ListObjectAnnotations` (prefix, `max-annotation-results`, continuation tokens) and `DeleteObjectAnnotation`: named UTF-8 payloads of 1 byte to 1 MiB, up to 1,000 per object version, with S3's naming rules (`InvalidAnnotationName`, `AnnotationNameTooLong`), `AnnotationLimitExceeded`, `UnsupportedMediaType` and `x-amz-object-if-match`. Each belongs to one object version: a new version starts with none, deleting a version deletes its annotations, a delete marker keeps them, and an unversioned overwrite or delete drops them; writing one changes neither the object's ETag nor its version. `CopyObject` carries them unless `x-amz-object-annotation-directive: EXCLUDE`, and recomputes their checksums when the copy names a new algorithm. Payload checksums are verified (`BadDigest`) and default to CRC64NVME; CRC32, CRC32C, CRC64NVME, SHA1, SHA256, SHA512, MD5 and XXHASH64 are computed, while XXHASH3 and XXHASH128 are refused rather than stored unverified. Annotations take the object's encryption and are refused on SSE-C objects, replicate with the object (`COMPLETED` / `REPLICA`), respect Object Lock on every write (governance retention needs `x-amz-bypass-governance-retention` to put, overwrite or delete one; compliance retention and a legal hold refuse all three, bypass or not, each as 403 `AccessDenied` naming retention or the legal hold, as observed on AWS), persist per version with `S3_PERSIST=1`, and send `s3:ObjectAnnotation:Put` / `s3:ObjectAnnotation:Delete` events with the record's `objectAnnotation` block; a `CopyObject` event reports `hasObjectAnnotation`. Previously a `PUT ?annotation` fell through to `PutObject` and replaced the object with the payload. The S3 Metadata annotation table (`UpdateBucketMetadataAnnotationTableConfiguration`) is not included: MiniStack has no S3 Metadata configuration for it to belong to. Checked against the S3 API Reference, the S3 User Guide's "Annotating your objects" page and the botocore model; the Object Lock behaviour was validated against AWS (ap-southeast-2).
diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.py
index 1cee45d5..0994c7a3 100644
--- a/ministack/core/iam_evaluator.py
+++ b/ministack/core/iam_evaluator.py
@@ -11,6 +11,7 @@ Evaluation order:
3. No matching Allow → implicit DENY
"""
+import contextvars
import datetime as _dt
import hmac
import ipaddress
@@ -576,15 +577,90 @@ def evaluate(ctx: EvalContext,
"No matching Allow statement")
-def evaluate_resource_policy(doc: str | dict | None, ctx: EvalContext) -> EvalResult:
- """Evaluate a Lambda layer-version policy for the account principal in *ctx*.
+def request_caller_arn(headers: dict, query_params: dict | None = None) -> str:
+ """Best-effort principal ARN for resource-policy evaluation.
+
+ Resolves the request's access key to its IAM user/role ARN when it maps
+ to one, else the caller account's root ARN. Never raises: any failure
+ falls back to the root ARN, which is all account-ID and wildcard
+ principals (everything ``AddPermission`` can express) need.
+ """
+ from ministack.core.responses import get_account_id
+
+ fallback = f"arn:aws:iam::{get_account_id()}:root"
+ try:
+ from ministack.core.router import extract_access_key_id
+ access_key = extract_access_key_id(headers or {}, query_params or {})
+ principal = resolve_principal(access_key, get_account_id()) if access_key else None
+ except Exception:
+ return fallback
+ if (isinstance(principal, AuthError) or principal is None
+ or not getattr(principal, "arn", "")):
+ return fallback
+ return principal.arn
+
+
+_request_caller_arn: contextvars.ContextVar[str] = contextvars.ContextVar(
+ "ministack_request_caller_arn", default="")
+
+
+def pin_request_caller(headers: dict, query_params: dict | None = None) -> None:
+ """Remember the caller's principal ARN for this request's policy checks."""
+ _request_caller_arn.set(request_caller_arn(headers, query_params))
+
+
+def caller_arn() -> str:
+ """The pinned caller ARN, or the caller account's root ARN."""
+ from ministack.core.responses import get_account_id
+
+ return _request_caller_arn.get() or f"arn:aws:iam::{get_account_id()}:root"
+
+
+def resource_policy_allows(raw_policy: str | dict | None, ctx: EvalContext,
+ same_account: bool) -> bool:
+ """Whether a direct API call passes its SQS/SNS resource policy.
+
+ Same-account callers pass unless the policy explicitly denies them;
+ cross-account callers need an explicit Allow. A missing policy allows
+ same-account callers and denies cross-account ones.
+ """
+ if not raw_policy:
+ return same_account
+ decision = evaluate_resource_policy(raw_policy, ctx).decision
+ if same_account:
+ return decision != "Deny"
+ return decision == "Allow"
+
+
+def _service_principal_matches(principal: Any, service: str) -> bool:
+ """Whether a statement Principal names the calling AWS service.
+
+ Compared case-insensitively against the full service principal
+ (``s3.amazonaws.com``), never through the trust-policy matcher, which
+ lets any ``Service`` entry match an account root.
+ """
+ if not isinstance(principal, dict):
+ return False
+ services = principal.get("Service", [])
+ if isinstance(services, str):
+ services = [services]
+ return any(s.lower() == service.lower() for s in services
+ if isinstance(s, str))
+
+
+def evaluate_resource_policy(doc: str | dict | None, ctx: EvalContext,
+ service: str | None = None) -> EvalResult:
+ """Evaluate a resource-based policy for the principal in *ctx*.
Such a document names the principals it applies to, so a statement counts
only when its ``AWS`` principal (or ``*``) matches the caller; action,
resource, conditions and deny-before-allow are then the ordinary
- evaluation. ``Service`` principals are ignored, since the trust-policy
- matcher lets them match any account root. A statement carrying only
- ``NotPrincipal`` never matches, leaving that unsupported form closed."""
+ evaluation. When *service* names the calling AWS service (``s3.amazonaws.com``
+ for an S3 notification delivery), a statement whose ``Service`` principal
+ names it counts too. Without *service*, ``Service`` principals are ignored,
+ since the trust-policy matcher lets them match any account root. A statement
+ carrying only ``NotPrincipal`` never matches, leaving that unsupported form
+ closed."""
if isinstance(doc, str):
try:
doc = json.loads(doc)
@@ -599,8 +675,12 @@ def evaluate_resource_policy(doc: str | dict | None, ctx: EvalContext) -> EvalRe
continue
principal = stmt.get("Principal", {})
if isinstance(principal, dict):
- principal = {"AWS": principal.get("AWS", [])}
- if _principal_matches(principal, ctx.principal_arn):
+ if _principal_matches({"AWS": principal.get("AWS", [])},
+ ctx.principal_arn):
+ applicable.append(stmt)
+ elif service and _service_principal_matches(principal, service):
+ applicable.append(stmt)
+ elif _principal_matches(principal, ctx.principal_arn):
applicable.append(stmt)
return evaluate(ctx, [parse_policy_document({"Statement": applicable})])
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 13e6a57f..bed909ae 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -2010,7 +2010,7 @@ def _dispatch(method: str, bucket: str, key: str, headers: dict, body: bytes, qu
if "policy" in query_params:
return _put_bucket_policy(bucket, body)
if "notification" in query_params:
- return _put_bucket_notification(bucket, body)
+ return _put_bucket_notification(bucket, body, headers)
if "tagging" in query_params:
return _put_bucket_tagging(bucket, body)
if "versioning" in query_params:
@@ -2871,13 +2871,18 @@ def _notification_configs_to_xml(configs, has_eventbridge: bool) -> str:
return tostring(root, encoding="unicode")
-def _put_bucket_notification(name: str, body: bytes):
+def _put_bucket_notification(name: str, body: bytes, headers: dict | None = None):
if name not in _buckets:
return _no_such_bucket(name)
raw = body.decode("utf-8", errors="replace")
configs = _parse_notification_config_raw(raw)
bucket_region = _notification_bucket_region(name)
- validation_error = _validate_notification_configs(configs, bucket_region)
+ # x-amz-skip-destination-validation skips the destination probe below (the
+ # existence + policy check); malformed ARNs and out-of-scope targets are
+ # still rejected as config-shape errors.
+ skip_probe = (headers or {}).get("x-amz-skip-destination-validation", "").lower() == "true"
+ validation_error = _validate_notification_configs(
+ configs, bucket_region, name, skip_probe)
if validation_error:
return validation_error
_bucket_notifications[name] = _notification_configs_to_xml(
@@ -2887,8 +2892,10 @@ def _put_bucket_notification(name: str, body: bytes):
# client polls the destination queue/topic before the background thread has
# delivered the message (also loses the caller's account contextvar across
# threads, which broke multi-tenant tests). Queue and topic destinations only;
- # AWS does not send the test event to Lambda targets.
- _fire_s3_test_event(name)
+ # AWS does not send the test event to Lambda targets. With validation
+ # skipped there is no probe, hence no test event either.
+ if not skip_probe:
+ _fire_s3_test_event(name)
return 200, {}, b""
@@ -3259,7 +3266,11 @@ def _parse_notification_target_arn(target_type: str, arn: str, bucket_region: st
return spec, f"expected {expected_service} ARN, got {spec.service}"
if not spec.account_id:
return spec, "destination ARN must include an account ID"
- if spec.account_id != get_account_id():
+ if target_type == "lambda" and spec.account_id != get_account_id():
+ # SQS/SNS destinations may live in another account: real S3 delivers
+ # to them when their resource policy allows it, and the probe below
+ # verifies exactly that. Lambda stays same-account — function policies
+ # are not modeled, so a foreign function could never be verified.
return spec, "destination account must match bucket owner account"
if not spec.region:
return spec, "destination ARN must include a region"
@@ -3300,20 +3311,55 @@ def _notification_destination_exists(target_type: str, arn: str, bucket_region:
return bool(_queue_name_from_sqs_arn_spec(spec)) and _sqs._queue_by_arn(str(spec)) is not None
from ministack.services import sns as _sns
- return bool(_topic_name_from_sns_arn_spec(spec)) and _sns._topics.get(arn) is not None
+ # The topic may belong to another account, so resolve it in its owner's
+ # scope — a current-scope lookup would reject a cross-account topic whose
+ # policy allows the delivery.
+ return bool(_topic_name_from_sns_arn_spec(spec)) and _sns._topic_by_arn_any_scope(arn) is not None
-def _validate_notification_configs(configs: list[dict], bucket_region: str) -> tuple | None:
+def _notification_destination_allows(target_type: str, arn: str,
+ bucket_name: str, owner: str) -> bool:
+ """Whether the destination's resource policy lets S3 publish to it.
+
+ The Put-time probe half of the AWS verification ("S3 verifies an SNS or
+ SQS destination by sending it a test notification, and if the message
+ fails, the entire PUT action will fail"): no probe message is actually
+ sent here — the delivery-time check answers the same question, and the
+ single test event goes out after the config is stored.
+ """
+ source_arn = f"arn:aws:s3:::{bucket_name}" if bucket_name else ""
+ if target_type == "sqs":
+ from ministack.services import sqs as _sqs
+
+ return _sqs.queue_policy_allows(arn, "s3.amazonaws.com",
+ source_arn, owner)
+ from ministack.services import sns as _sns
+
+ return _sns.topic_policy_allows(arn, "s3.amazonaws.com", source_arn, owner)
+
+
+def _validate_notification_configs(configs: list[dict], bucket_region: str,
+ bucket_name: str = "",
+ skip_destination_validation: bool = False,
+ ) -> tuple | None:
for cfg in configs:
error = _validate_notification_target_arn(cfg["type"], cfg["arn"], bucket_region)
if error:
return error
+ if skip_destination_validation:
+ return None
# The destination check is second: an ARN that does not parse is reported
- # as malformed before anything tries to reach what it names.
+ # as malformed before anything tries to reach what it names. A destination
+ # fails the probe when it does not exist or when its resource policy does
+ # not let S3 publish — either way the whole PUT fails, like real S3. The
+ # policy half is permissive while AUTH is off, leaving the existence check.
+ owner = _bucket_owner_account(bucket_name) if bucket_name else None
unreachable = [
cfg["arn"] for cfg in configs
if cfg["type"] in ("sqs", "sns")
- and not _notification_destination_exists(cfg["type"], cfg["arn"], bucket_region)
+ and (not _notification_destination_exists(cfg["type"], cfg["arn"], bucket_region)
+ or not _notification_destination_allows(cfg["type"], cfg["arn"],
+ bucket_name, owner or ""))
]
if unreachable:
return _invalid_notification_config(
@@ -3503,9 +3549,11 @@ def _fire_s3_event(
payload["Records"][0]["s3"]["configurationId"] = cfg["id"]
if cfg["type"] == "sqs":
- _deliver_event_to_sqs(cfg["arn"], payload, bucket_region)
+ _deliver_event_to_sqs(cfg["arn"], payload, bucket_region,
+ bucket_name=bucket_name)
elif cfg["type"] == "sns":
- _deliver_event_to_sns(cfg["arn"], payload, bucket_region)
+ _deliver_event_to_sns(cfg["arn"], payload, bucket_region,
+ bucket_name=bucket_name)
elif cfg["type"] == "lambda":
_deliver_event_to_lambda(cfg["arn"], payload, bucket_region)
except Exception:
@@ -3570,7 +3618,8 @@ def _parse_delivery_notification_target(target_type: str, arn: str, bucket_regio
return spec
-def _deliver_event_to_sqs(arn: str, event_payload: dict, bucket_region: str) -> None:
+def _deliver_event_to_sqs(arn: str, event_payload: dict, bucket_region: str,
+ bucket_name: str = "") -> None:
from ministack.services import sqs as _sqs
spec = _parse_delivery_notification_target("sqs", arn, bucket_region)
@@ -3584,6 +3633,14 @@ def _deliver_event_to_sqs(arn: str, event_payload: dict, bucket_region: str) ->
if not queue:
logger.warning("S3 notification: SQS queue %s not found", queue_name)
return
+ owner = _bucket_owner_account(bucket_name) if bucket_name else None
+ if not _sqs.queue_policy_allows(
+ str(spec), "s3.amazonaws.com",
+ f"arn:aws:s3:::{bucket_name}" if bucket_name else "",
+ owner or get_account_id()):
+ logger.warning("S3 notification: queue policy denies delivery from %s to %s",
+ bucket_name, queue_name)
+ return
body = json.dumps(event_payload)
now = time.time()
@@ -3601,7 +3658,8 @@ def _deliver_event_to_sqs(arn: str, event_payload: dict, bucket_region: str) ->
logger.info("S3 notification → SQS %s", queue_name)
-def _deliver_event_to_sns(arn: str, event_payload: dict, bucket_region: str) -> None:
+def _deliver_event_to_sns(arn: str, event_payload: dict, bucket_region: str,
+ bucket_name: str = "") -> None:
from ministack.services import sns as _sns
spec = _parse_delivery_notification_target("sns", arn, bucket_region)
@@ -3610,10 +3668,18 @@ def _deliver_event_to_sns(arn: str, event_payload: dict, bucket_region: str) ->
if not _topic_name_from_sns_arn_spec(spec):
logger.warning("S3 notification: invalid SNS topic ARN %s", arn)
return
- topic = _sns._topics.get(arn)
+ topic = _sns._topic_by_arn_any_scope(arn)
if not topic:
logger.warning("S3 notification: SNS topic %s not found", arn)
return
+ owner = _bucket_owner_account(bucket_name) if bucket_name else None
+ if not _sns.topic_policy_allows(
+ arn, "s3.amazonaws.com",
+ f"arn:aws:s3:::{bucket_name}" if bucket_name else "",
+ owner or get_account_id()):
+ logger.warning("S3 notification: topic policy denies delivery from %s to %s",
+ bucket_name, arn)
+ return
message = json.dumps(event_payload)
msg_id = new_uuid()
@@ -3698,9 +3764,11 @@ def _fire_s3_test_event(bucket_name: str) -> None:
for cfg in configs:
try:
if cfg["type"] == "sqs":
- _deliver_event_to_sqs(cfg["arn"], payload, bucket_region)
+ _deliver_event_to_sqs(cfg["arn"], payload, bucket_region,
+ bucket_name=bucket_name)
elif cfg["type"] == "sns":
- _deliver_event_to_sns(cfg["arn"], payload, bucket_region)
+ _deliver_event_to_sns(cfg["arn"], payload, bucket_region,
+ bucket_name=bucket_name)
# No lambda branch: AWS verifies Lambda destinations by checking the
# function's permissions, not by invoking them.
except Exception:
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index d27dfcbc..031834f0 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -35,7 +35,7 @@ _PORT = os.environ.get("GATEWAY_PORT", "4566")
import ministack.services.lambda_svc as _lambda_svc
from ministack.core.arn import ArnParseError, parse_arn
-from ministack.core.responses import AccountRegionScopedDict, get_account_id, get_region, new_uuid
+from ministack.core.responses import AccountRegionScopedDict, get_account_id, get_region, new_uuid, request_scope
from ministack.services import sqs as _sqs
logger = logging.getLogger("sns")
@@ -56,6 +56,132 @@ def _normalize_arn(arn: str) -> str:
return arn
+def _topic_by_arn_any_scope(topic_arn: str) -> dict | None:
+ """Fetch a topic by ARN, reaching into its owner's scope when foreign.
+
+ Only the account may differ: like real SNS, a topic in another region is
+ invisible no matter who asks.
+ """
+ topic = _topics.get(topic_arn)
+ if topic is not None:
+ return topic
+ try:
+ spec = parse_arn(topic_arn)
+ except ArnParseError:
+ return None
+ if not spec.account_id or not spec.region or spec.service != "sns":
+ return None
+ if spec.region != get_region() or spec.account_id == get_account_id():
+ return None
+ return _topics.get_scoped(spec.account_id, spec.region, topic_arn)
+
+
+def _topic_owner(topic: dict) -> str:
+ try:
+ return parse_arn(topic.get("arn", "")).account_id or get_account_id()
+ except ArnParseError:
+ return get_account_id()
+
+
+def _enforce_topic_policy(topic: dict, iam_action: str):
+ """Gate one topic API call on the topic's resource policy.
+
+ Returns an ``AuthorizationError`` (403) response tuple when denied, else
+ ``None``. Only under AUTH=true is anything denied; with auth disabled
+ every call passes, like the rest of the identity layer. Same-account
+ callers then pass unless the Policy carries an explicit Deny for them;
+ cross-account callers need an explicit Allow, like real SNS.
+
+ Known boundary under AUTH=true: a caller with no identity Allow whose
+ access comes from this Policy alone is denied by the app-level identity
+ check before this resource check runs, where real SNS would allow the
+ union (same caveat as the queue check).
+ """
+ from ministack.app import AUTH
+ if not AUTH:
+ return None
+ from ministack.core.iam_evaluator import (
+ EvalContext,
+ caller_arn,
+ resource_policy_allows,
+ )
+
+ topic_arn = topic.get("arn", "")
+ ctx = EvalContext(
+ principal_arn=caller_arn(),
+ principal_type="Root",
+ principal_account=get_account_id(),
+ action=iam_action,
+ resource_arn=topic_arn or "*",
+ region=get_region(),
+ )
+ if resource_policy_allows(topic.get("attributes", {}).get("Policy") or "", ctx,
+ _topic_owner(topic) == get_account_id()):
+ return None
+ return _error("AuthorizationError",
+ f"User: {ctx.principal_arn} is not authorized to perform: "
+ f"{iam_action} on resource: {topic_arn}", 403)
+
+
+def _get_topic(topic_arn: str, action: str | None = None):
+ """Resolve a topic by ARN, enforcing its Policy when *action* is given.
+
+ Returns ``(topic, None)`` on success or ``(None, error_tuple)`` with a
+ ``NotFound`` (404) or ``AuthorizationError`` (403) response.
+ """
+ arn = _normalize_arn(topic_arn)
+ topic = _topic_by_arn_any_scope(arn)
+ if topic is None:
+ return None, _error("NotFound", f"Topic does not exist: {arn}", 404)
+ if action is not None:
+ denied = _enforce_topic_policy(topic, action)
+ if denied is not None:
+ return None, denied
+ return topic, None
+
+
+def topic_policy_allows(topic_arn: str, service: str,
+ source_arn: str, source_account: str) -> bool:
+ """Whether the topic's Policy lets an AWS service publish to it.
+
+ Used by S3 notifications, which publish as the ``s3.amazonaws.com``
+ service principal with the bucket as ``aws:SourceArn``/``aws:SourceAccount``
+ (plus ``aws:SourceOwner`` for older policy samples). Only under AUTH=true
+ is the Policy consulted; with auth disabled every delivery passes. Every
+ topic carries the default policy, whose ``AWS:SourceOwner`` condition then
+ admits same-account service deliveries; a custom Policy without an S3
+ statement — or no Policy at all — blocks them, like real SNS.
+ """
+ from ministack.app import AUTH
+ if not AUTH:
+ return True
+ from ministack.core.iam_evaluator import EvalContext, evaluate_resource_policy
+
+ topic = _topic_by_arn_any_scope(topic_arn)
+ if topic is None:
+ return False
+ raw_policy = topic.get("attributes", {}).get("Policy") or ""
+ if not raw_policy:
+ return False
+ # The caller is the service itself, not an IAM principal in the source
+ # account: an account-ID grant must not authorize it (real AWS keeps the
+ # service principal distinct), while Principal "*" legitimately matches.
+ ctx = EvalContext(
+ principal_arn="*",
+ principal_type="Service",
+ principal_account="",
+ action="sns:Publish",
+ resource_arn=topic_arn,
+ region=get_region(),
+ service_context={
+ "aws:sourcearn": source_arn,
+ "aws:sourceaccount": source_account,
+ "aws:sourceowner": source_account,
+ },
+ )
+ return evaluate_resource_policy(raw_policy, ctx, service=service).decision == "Allow"
+
+
def _sqs_queue_name_from_arn_spec(spec) -> str | None:
if spec.service != "sqs" or not spec.resource or ":" in spec.resource or "/" in spec.resource:
return None
@@ -96,7 +222,7 @@ def _validate_subscription_endpoint(protocol: str, endpoint: str):
return None
-def _resolve_topic_tag_arn(arn: str):
+def _resolve_topic_tag_arn(arn: str, action: str):
arn = _normalize_arn(arn)
try:
spec = parse_arn(arn)
@@ -114,12 +240,15 @@ def _resolve_topic_tag_arn(arn: str):
):
return arn, None, _error("InvalidParameterException", f"Invalid SNS topic ARN: {arn}", 400)
- if spec.region != get_region() or spec.account_id != get_account_id():
+ if spec.region != get_region():
return arn, None, _error("ResourceNotFoundException", "Resource not found", 404)
- topic = _topics.get(arn)
+ topic = _topic_by_arn_any_scope(arn)
if not topic:
return arn, None, _error("ResourceNotFoundException", "Resource not found", 404)
+ denied = _enforce_topic_policy(topic, action)
+ if denied is not None:
+ return arn, None, denied
return arn, topic, None
@@ -175,6 +304,9 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, que
for k, v in form_params.items():
params[k] = v
+ from ministack.core.iam_evaluator import pin_request_caller
+ pin_request_caller(headers, query_params)
+
action = _p(params, "Action")
handlers = {
"CreateTopic": _create_topic,
@@ -182,6 +314,8 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, que
"ListTopics": _list_topics,
"GetTopicAttributes": _get_topic_attributes,
"SetTopicAttributes": _set_topic_attributes,
+ "AddPermission": _add_permission,
+ "RemovePermission": _remove_permission,
"Subscribe": _subscribe,
"ConfirmSubscription": _confirm_subscription,
"Unsubscribe": _unsubscribe,
@@ -315,10 +449,21 @@ def _create_topic(params):
def _delete_topic(params):
arn = _normalize_arn(_p(params, "TopicArn"))
- topic = _topics.pop(arn, None)
- if topic:
- for sub in topic.get("subscriptions", []):
- _sub_arn_to_topic.pop(sub["arn"], None)
+ topic = _topic_by_arn_any_scope(arn)
+ if topic is None:
+ # Idempotent like real SNS: deleting a missing topic still answers 200.
+ return _xml(200, "DeleteTopicResponse", "")
+ denied = _enforce_topic_policy(topic, "sns:DeleteTopic")
+ if denied is not None:
+ return denied
+ owner = _topic_owner(topic)
+ try:
+ region = parse_arn(arn).region or get_region()
+ except ArnParseError:
+ region = get_region()
+ _topics.pop_scoped(owner, region, arn, None)
+ for sub in topic.get("subscriptions", []):
+ _sub_arn_to_topic.pop(sub["arn"], None)
return _xml(200, "DeleteTopicResponse", "")
@@ -343,10 +488,9 @@ def _list_topics(params):
def _get_topic_attributes(params):
- arn = _normalize_arn(_p(params, "TopicArn"))
- topic = _topics.get(arn)
- if not topic:
- return _error("NotFound", f"Topic does not exist: {arn}", 404)
+ topic, err = _get_topic(_p(params, "TopicArn"), "sns:GetTopicAttributes")
+ if err is not None:
+ return err
_refresh_subscription_counts(topic)
attrs = "".join(
f"<entry><key>{k}</key><value>{_xml_escape(v)}</value></entry>"
@@ -357,10 +501,9 @@ def _get_topic_attributes(params):
def _set_topic_attributes(params):
- arn = _normalize_arn(_p(params, "TopicArn"))
- topic = _topics.get(arn)
- if not topic:
- return _error("NotFound", f"Topic does not exist: {arn}", 404)
+ topic, err = _get_topic(_p(params, "TopicArn"), "sns:SetTopicAttributes")
+ if err is not None:
+ return err
attr_name = _p(params, "AttributeName")
attr_val = _p(params, "AttributeValue")
if attr_name:
@@ -368,18 +511,104 @@ def _set_topic_attributes(params):
return _xml(200, "SetTopicAttributesResponse", "")
+def _member_list(params, key: str) -> list:
+ """Collect a query-protocol ``<Key>.member.N`` list."""
+ out = []
+ i = 1
+ while True:
+ v = _p(params, f"{key}.member.{i}")
+ if not v:
+ break
+ out.append(v)
+ i += 1
+ return out
+
+
+def _add_permission(params):
+ topic, err = _get_topic(_p(params, "TopicArn"), "sns:AddPermission")
+ if err is not None:
+ return err
+ topic_arn = topic["arn"]
+ label = _p(params, "Label")
+ if not label:
+ return _error("InvalidParameterException",
+ "Label is required", 400)
+ account_ids = _member_list(params, "AWSAccountId")
+ actions = _member_list(params, "ActionName")
+ if not account_ids:
+ return _error("InvalidParameterException",
+ "AWSAccountId is required", 400)
+ if not actions:
+ return _error("InvalidParameterException",
+ "ActionName is required", 400)
+
+ raw = topic["attributes"].get("Policy") or ""
+ try:
+ policy = json.loads(raw) if raw else {}
+ except (TypeError, json.JSONDecodeError):
+ policy = {}
+ policy.setdefault("Version", "2012-10-17")
+ policy.setdefault("Id", f"{topic_arn}/SNSDefaultPolicy")
+ statements = policy.setdefault("Statement", [])
+ if isinstance(statements, dict):
+ statements = [statements]
+ policy["Statement"] = statements
+
+ if any(s.get("Sid") == label for s in statements):
+ return _error("InvalidParameterException",
+ f"Value {label} for parameter Label is invalid. "
+ f"Reason: Already exists.", 400)
+
+ statements.append({
+ "Sid": label,
+ "Effect": "Allow",
+ "Principal": {"AWS": list(account_ids)},
+ "Action": [a if a.startswith("sns:") else f"sns:{a[4:]}" if a.startswith("SNS:") else f"sns:{a}" for a in actions],
+ "Resource": topic_arn,
+ })
+ topic["attributes"]["Policy"] = json.dumps(policy)
+ return _xml(200, "AddPermissionResponse", "")
+
+
+def _remove_permission(params):
+ topic, err = _get_topic(_p(params, "TopicArn"), "sns:RemovePermission")
+ if err is not None:
+ return err
+ label = _p(params, "Label")
+ if not label:
+ return _error("InvalidParameterException",
+ "Label is required", 400)
+
+ raw = topic["attributes"].get("Policy") or ""
+ if raw:
+ try:
+ policy = json.loads(raw)
+ except (TypeError, json.JSONDecodeError):
+ policy = {}
+ statements = policy.get("Statement") or []
+ if isinstance(statements, dict):
+ statements = [statements]
+ remaining = [s for s in statements if s.get("Sid") != label]
+ if remaining:
+ policy["Statement"] = remaining
+ topic["attributes"]["Policy"] = json.dumps(policy)
+ else:
+ topic["attributes"].pop("Policy", None)
+ return _xml(200, "RemovePermissionResponse", "")
+
+
# ---------------------------------------------------------------------------
# Subscriptions
# ---------------------------------------------------------------------------
def _subscribe(params):
- topic_arn = _normalize_arn(_p(params, "TopicArn"))
protocol = _p(params, "Protocol")
endpoint = _p(params, "Endpoint")
- topic = _topics.get(topic_arn)
- if not topic:
- return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)
+ topic, err = _get_topic(_p(params, "TopicArn"), "sns:Subscribe")
+ if err is not None:
+ return err
+ topic_arn = topic["arn"]
if not protocol:
return _error("InvalidParameterException", "Protocol is required", 400)
@@ -440,12 +669,15 @@ def _subscribe(params):
def _confirm_subscription(params):
- topic_arn = _normalize_arn(_p(params, "TopicArn"))
token = _p(params, "Token")
- topic = _topics.get(topic_arn)
- if not topic:
- return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)
+ # Gated on the confirmation secret, not the topic policy: the
+ # SubscribeURL GET carries no SigV4 identity, so the topic must resolve
+ # outside the caller's scope.
+ topic, err = _get_topic(_p(params, "TopicArn"))
+ if err is not None:
+ return err
+ topic_arn = topic["arn"]
if not token:
return _error("InvalidParameterException", "Token is required", 400)
@@ -466,8 +698,8 @@ def _confirm_subscription(params):
def _unsubscribe(params):
sub_arn = _p(params, "SubscriptionArn")
topic_arn = _sub_arn_to_topic.get(sub_arn)
- if topic_arn and topic_arn in _topics:
- topic = _topics[topic_arn]
+ topic = _topic_by_arn_any_scope(topic_arn) if topic_arn else None
+ if topic is not None:
topic["subscriptions"] = [s for s in topic["subscriptions"] if s["arn"] != sub_arn]
_refresh_subscription_counts(topic)
_sub_arn_to_topic.pop(sub_arn, None)
@@ -506,10 +738,10 @@ def _list_subscriptions(params):
def _list_subscriptions_by_topic(params):
- topic_arn = _normalize_arn(_p(params, "TopicArn"))
- topic = _topics.get(topic_arn)
- if not topic:
- return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)
+ topic, err = _get_topic(_p(params, "TopicArn"), "sns:ListSubscriptionsByTopic")
+ if err is not None:
+ return err
+ topic_arn = topic["arn"]
members = ""
for sub in topic["subscriptions"]:
members += (
@@ -528,7 +760,7 @@ def _list_subscriptions_by_topic(params):
def _get_subscription_attributes(params):
sub_arn = _p(params, "SubscriptionArn")
topic_arn = _sub_arn_to_topic.get(sub_arn)
- if not topic_arn or topic_arn not in _topics:
+ if not topic_arn or _topic_by_arn_any_scope(topic_arn) is None:
return _error("NotFound", f"Subscription does not exist: {sub_arn}", 404)
sub = _find_subscription(topic_arn, sub_arn)
@@ -546,7 +778,7 @@ def _get_subscription_attributes(params):
def _set_subscription_attributes(params):
sub_arn = _p(params, "SubscriptionArn")
topic_arn = _sub_arn_to_topic.get(sub_arn)
- if not topic_arn or topic_arn not in _topics:
+ if not topic_arn or _topic_by_arn_any_scope(topic_arn) is None:
return _error("NotFound", f"Subscription does not exist: {sub_arn}", 404)
sub = _find_subscription(topic_arn, sub_arn)
@@ -655,7 +887,7 @@ def publish_internal(
the topic does not exist. Raises `SnsPublishError` for a publish AWS would
reject — notably a FIFO topic addressed without a MessageGroupId.
"""
- topic = _topics.get(topic_arn)
+ topic = _topic_by_arn_any_scope(topic_arn)
if topic is None:
return None
@@ -762,7 +994,8 @@ def _publish(params):
return _error("InvalidParameterException",
"TopicArn, TargetArn, or PhoneNumber is required", 400)
- if topic_arn not in _topics:
+ topic, err = _get_topic(topic_arn, "sns:Publish")
+ if err is not None:
# Publishing directly to a mobile-push platform endpoint (TargetArn) is
# valid in AWS — https://docs.aws.amazon.com/sns/latest/api/API_Publish.html
# We don't deliver anything, but the call must succeed.
@@ -771,7 +1004,8 @@ def _publish(params):
logger.info("SNS platform-endpoint publish stub to %s", topic_arn)
return _xml(200, "PublishResponse",
f"<PublishResult><MessageId>{msg_id}</MessageId></PublishResult>")
- return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)
+ return err
+ topic_arn = topic["arn"]
try:
result = publish_internal(
@@ -796,8 +1030,10 @@ def _publish_batch(params):
topic_arn = _normalize_arn(_p(params, "TopicArn"))
if not topic_arn:
return _error("InvalidParameterException", "TopicArn is required", 400)
- if topic_arn not in _topics:
- return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)
+ topic, err = _get_topic(topic_arn, "sns:Publish")
+ if err is not None:
+ return err
+ topic_arn = topic["arn"]
entries = _parse_batch_entries(params)
if not entries:
@@ -815,7 +1051,6 @@ def _publish_batch(params):
"Batch entry ids must be distinct", 400)
ids_seen.add(eid)
- topic = _topics[topic_arn]
fifo = _is_fifo_topic(topic)
successful = ""
@@ -951,9 +1186,14 @@ def _publish_batch(params):
def _fanout(topic_arn: str, msg_id: str, message: str, subject: str,
message_structure: str = "", message_attributes: dict | None = None,
message_group_id: str = "", message_dedup_id: str = ""):
- topic = _topics.get(topic_arn)
+ topic = _topic_by_arn_any_scope(topic_arn)
if not topic:
return
+ try:
+ _spec = parse_arn(topic_arn)
+ _owner, _region = _spec.account_id, _spec.region
+ except ArnParseError:
+ _owner, _region = get_account_id(), get_region()
for sub in topic["subscriptions"]:
if not sub.get("confirmed"):
@@ -978,7 +1218,8 @@ def _fanout(topic_arn: str, msg_id: str, message: str, subject: str,
if protocol == "sqs":
_deliver_to_sqs(endpoint, envelope, raw, effective_message,
message_group_id=message_group_id, message_dedup_id=message_dedup_id,
- message_attributes=message_attributes or {})
+ message_attributes=message_attributes or {},
+ topic_arn=topic_arn)
elif protocol in ("http", "https"):
_threading.Thread(
target=asyncio.run,
@@ -991,12 +1232,14 @@ def _fanout(topic_arn: str, msg_id: str, message: str, subject: str,
# subscriber's execution. Deliver on a background thread, mirroring
# the http(s) path above; a slow or failing subscriber Lambda no
# longer stalls the Publish call (or its upstream caller).
- # The publisher's account/region contextvars must travel into the
+ # The topic owner's account/region contextvars must travel into the
# thread: _get_func_record_for_ref rejects an ARN whose account
# differs from get_account_id(), and a fresh thread's empty context
# reads back the default account — dropping every delivery for a
- # non-default tenant.
- _sns_ctx = contextvars.copy_context()
+ # non-default tenant. After a cross-account publish the publisher's
+ # scope would hide the owner's function, so the owner's is pinned.
+ with request_scope(_owner or get_account_id(), _region or get_region()):
+ _sns_ctx = contextvars.copy_context()
_threading.Thread(
target=_sns_ctx.run,
args=(_deliver_to_lambda, endpoint, envelope, topic_arn, sub["arn"], msg_id, effective_message, message_attributes or {}),
@@ -1012,7 +1255,8 @@ def _fanout(topic_arn: str, msg_id: str, message: str, subject: str,
def _deliver_to_sqs(endpoint: str, envelope: str, raw: bool, raw_message: str,
message_group_id: str = "", message_dedup_id: str = "",
- message_attributes: dict | None = None):
+ message_attributes: dict | None = None,
+ topic_arn: str = ""):
try:
spec = parse_arn(endpoint)
except ArnParseError:
@@ -1022,13 +1266,19 @@ def _deliver_to_sqs(endpoint: str, envelope: str, raw: bool, raw_message: str,
if not queue_name:
logger.warning("SNS fanout: invalid SQS endpoint ARN %s", endpoint)
return
- if spec.account_id != get_account_id():
- logger.warning("SNS fanout: SQS queue %s is outside the current account scope", queue_name)
- return
queue = _sqs._queue_by_arn(str(spec))
if not queue:
logger.warning("SNS fanout: SQS queue %s not found", queue_name)
return
+ try:
+ source_account = parse_arn(topic_arn).account_id if topic_arn else ""
+ except ArnParseError:
+ source_account = ""
+ if not _sqs.queue_policy_allows(str(spec), "sns.amazonaws.com", topic_arn,
+ source_account or get_account_id()):
+ logger.warning("SNS fanout: queue policy denies delivery from %s to %s",
+ topic_arn, queue_name)
+ return
body = raw_message if raw else envelope
sqs_attrs = dict(message_attributes) if raw and message_attributes else {}
@@ -1156,7 +1406,8 @@ async def _send_subscription_confirmation(topic_arn: str, sub: dict):
# ---------------------------------------------------------------------------
def _list_tags_for_resource(params):
- arn, topic, err = _resolve_topic_tag_arn(_p(params, "ResourceArn"))
+ arn, topic, err = _resolve_topic_tag_arn(_p(params, "ResourceArn"),
+ "sns:ListTagsForResource")
if err:
return err
tags_xml = ""
@@ -1167,7 +1418,8 @@ def _list_tags_for_resource(params):
def _tag_resource(params):
- _arn, topic, err = _resolve_topic_tag_arn(_p(params, "ResourceArn"))
+ _arn, topic, err = _resolve_topic_tag_arn(_p(params, "ResourceArn"),
+ "sns:TagResource")
if err:
return err
i = 1
@@ -1180,7 +1432,8 @@ def _tag_resource(params):
def _untag_resource(params):
- _arn, topic, err = _resolve_topic_tag_arn(_p(params, "ResourceArn"))
+ _arn, topic, err = _resolve_topic_tag_arn(_p(params, "ResourceArn"),
+ "sns:UntagResource")
if err:
return err
i = 1
@@ -1465,7 +1718,7 @@ def _xml_escape(text: str) -> str:
def _find_subscription(topic_arn: str, sub_arn: str) -> dict | None:
- topic = _topics.get(topic_arn)
+ topic = _topic_by_arn_any_scope(topic_arn)
if not topic:
return None
for sub in topic["subscriptions"]:
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index 74dd989d..653eeb8c 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -97,6 +97,102 @@ _request_host: contextvars.ContextVar[str] = contextvars.ContextVar(
"_request_host", default="")
+def _owner_from_queue_arn(queue_arn: str) -> tuple[str | None, str | None]:
+ """Owner (account, region) parsed from a QueueArn, or (None, None)."""
+ try:
+ spec = parse_arn(queue_arn)
+ except ArnParseError:
+ return None, None
+ if not _ACCOUNT_ID_RE.match(spec.account_id or ""):
+ return None, None
+ return spec.account_id, spec.region or None
+
+
+def _enforce_queue_policy(q: dict, iam_action: str) -> None:
+ """Gate one queue API call on the queue's resource policy.
+
+ Only under AUTH=true; with auth disabled every call passes, like the
+ rest of the identity layer. Same-account callers then pass unless the
+ Policy carries an explicit Deny for them. Cross-account callers need an
+ explicit Allow in the Policy, exactly like real SQS, which answers
+ AccessDenied (403) otherwise.
+
+ Known boundary under AUTH=true: a caller with no identity Allow whose
+ access comes from this Policy alone is denied by the app-level identity
+ check before this resource check runs, where real SQS would allow the
+ union. Lifting that needs the identity layer to defer to the resource
+ layer, which no AUTH=true server harness here can verify.
+ """
+ from ministack.app import AUTH
+ if not AUTH:
+ return
+ from ministack.core.iam_evaluator import (
+ EvalContext,
+ caller_arn,
+ resource_policy_allows,
+ )
+
+ queue_arn = q["attributes"].get("QueueArn", "")
+ owner, _region = _owner_from_queue_arn(queue_arn)
+ caller = get_account_id()
+ ctx = EvalContext(
+ principal_arn=caller_arn(),
+ principal_type="Root",
+ principal_account=caller,
+ action=iam_action,
+ resource_arn=queue_arn or "*",
+ region=get_region(),
+ )
+ if not resource_policy_allows(q["attributes"].get("Policy") or "", ctx,
+ owner is None or owner == caller):
+ raise _Err("AccessDenied",
+ f"User: {ctx.principal_arn} is not authorized to perform: "
+ f"{iam_action} on resource: {queue_arn}", 403)
+
+
+def queue_policy_allows(queue_arn: str, service: str,
+ source_arn: str, source_account: str) -> bool:
+ """Whether the queue's Policy lets an AWS service deliver to it.
+
+ Used by S3 notifications and SNS fan-out, which call SQS as the service
+ principal (``s3.amazonaws.com`` / ``sns.amazonaws.com``) with the
+ producing resource as ``aws:SourceArn``/``aws:SourceAccount``. Only under
+ AUTH=true does the delivery need an explicit Allow in the queue Policy;
+ with auth disabled every delivery passes. Like real SQS, a queue with no
+ Policy then denies service deliveries, exactly as a queue whose Policy is
+ silent on the calling service does.
+ """
+ from ministack.app import AUTH
+ if not AUTH:
+ return True
+ from ministack.core.iam_evaluator import EvalContext, evaluate_resource_policy
+
+ q = _queue_by_arn(queue_arn)
+ if q is None:
+ return False
+ raw_policy = q["attributes"].get("Policy") or ""
+ if not raw_policy:
+ return False
+ # The caller is the service itself, not an IAM principal in the source
+ # account: an account-ID grant must not authorize it (real AWS keeps the
+ # service principal distinct), while Principal "*" legitimately matches.
+ ctx = EvalContext(
+ principal_arn="*",
+ principal_type="Service",
+ principal_account="",
+ action="sqs:SendMessage",
+ resource_arn=queue_arn,
+ region=get_region(),
+ service_context={
+ "aws:sourcearn": source_arn,
+ "aws:sourceaccount": source_account,
+ # Older S3/SNS policy samples condition on AWS:SourceOwner.
+ "aws:sourceowner": source_account,
+ },
+ )
+ return evaluate_resource_policy(raw_policy, ctx, service=service).decision == "Allow"
+
+
def _externalize_url(url: str) -> str:
"""Rewrite a canonical queue URL's host with the caller's Host header.
@@ -250,6 +346,8 @@ async def handle_request(method: str, path: str, headers: dict,
# Record how the caller reached us so responses can echo that host in
# queue URLs (see _externalize_url). Header keys are lowercased upstream.
_request_host.set(headers.get("host", ""))
+ from ministack.core.iam_evaluator import pin_request_caller
+ pin_request_caller(headers, query_params)
target = headers.get("x-amz-target", "")
# JSON protocol (X-Amz-Target: AmazonSQS.*)
@@ -459,9 +557,12 @@ def _act_create_queue(data: dict, _u: str) -> dict:
def _act_delete_queue(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
- q = _get_q(url)
- canonical_url = _queue_name_to_url.pop(q["name"], url)
- _queues.pop(canonical_url, None)
+ q = _get_q(url, "sqs:DeleteQueue")
+ owner, region = _owner_from_queue_arn(q["attributes"].get("QueueArn", ""))
+ owner = owner or get_account_id()
+ region = region or get_region()
+ canonical_url = _queue_name_to_url.pop_scoped(owner, region, q["name"], url)
+ _queues.pop_scoped(owner, region, canonical_url, None)
return {}
@@ -485,10 +586,27 @@ def _act_list_queues(data: dict, _u: str) -> dict:
def _act_get_queue_url(data: dict, _u: str) -> dict:
name = data.get("QueueName", "")
+ owner = data.get("QueueOwnerAWSAccountId") or ""
+ if owner and _ACCOUNT_ID_RE.match(owner) and owner != get_account_id():
+ url = _queue_name_to_url.get_scoped(owner, get_region(), name)
+ if not url:
+ raise _Err("QueueDoesNotExist",
+ "The specified queue does not exist.")
+ q = _queues.get_scoped(owner, get_region(), url)
+ if q is None:
+ raise _Err("QueueDoesNotExist",
+ "The specified queue does not exist.")
+ _enforce_queue_policy(q, "sqs:GetQueueUrl")
+ return {"QueueUrl": url}
url = _queue_name_to_url.get(name)
if not url:
raise _Err("QueueDoesNotExist",
"The specified queue does not exist.")
+ q = _queues.get(url)
+ if q is None:
+ raise _Err("QueueDoesNotExist",
+ "The specified queue does not exist.")
+ _enforce_queue_policy(q, "sqs:GetQueueUrl")
return {"QueueUrl": url}
@@ -496,7 +614,7 @@ def _act_get_queue_url(data: dict, _u: str) -> dict:
def _act_send_message(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
- q = _get_q(url)
+ q = _get_q(url, "sqs:SendMessage")
body_text = data.get("MessageBody", "")
if not body_text:
@@ -606,7 +724,7 @@ def _act_send_message(data: dict, qurl: str) -> dict:
async def _act_receive_message(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
- q = _get_q(url)
+ q = _get_q(url, "sqs:ReceiveMessage")
max_n = min(int(data.get("MaxNumberOfMessages", 1)), 10)
# An explicit request value wins even when it is 0 — a supplied
@@ -656,7 +774,7 @@ async def _act_receive_message(data: dict, qurl: str) -> dict:
def _act_delete_message(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
- q = _get_q(url)
+ q = _get_q(url, "sqs:DeleteMessage")
rh = data.get("ReceiptHandle", "")
if not rh:
raise _Err("MissingParameter",
@@ -688,7 +806,7 @@ def _act_delete_message(data: dict, qurl: str) -> dict:
def _act_change_visibility(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
- q = _get_q(url)
+ q = _get_q(url, "sqs:ChangeMessageVisibility")
rh = data.get("ReceiptHandle", "")
vt = int(data.get("VisibilityTimeout", 30))
found = False
@@ -745,7 +863,7 @@ def _validate_batch_entries(entries: list, entry_name: str) -> None:
def _act_change_visibility_batch(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
- q = _get_q(url)
+ q = _get_q(url, "sqs:ChangeMessageVisibility")
entries = data.get("Entries", [])
_validate_batch_entries(entries, "ChangeMessageVisibilityBatchRequestEntry")
ok: list = []
@@ -776,7 +894,7 @@ def _act_change_visibility_batch(data: dict, qurl: str) -> dict:
def _act_get_queue_attributes(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
- q = _get_q(url)
+ q = _get_q(url, "sqs:GetQueueAttributes")
_refresh_counts(q)
names = data.get("AttributeNames") or ["All"]
want_all = "All" in names
@@ -791,7 +909,7 @@ def _act_get_queue_attributes(data: dict, qurl: str) -> dict:
def _act_set_queue_attributes(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
- q = _get_q(url)
+ q = _get_q(url, "sqs:SetQueueAttributes")
incoming = data.get("Attributes") or {}
if "RedrivePolicy" in incoming:
_validate_redrive_policy(str(incoming["RedrivePolicy"]))
@@ -814,7 +932,7 @@ def _act_set_queue_attributes(data: dict, qurl: str) -> dict:
def _act_add_permission(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
- q = _get_q(url)
+ q = _get_q(url, "sqs:AddPermission")
label = data.get("Label") or ""
if not label:
raise _Err("MissingParameter",
@@ -869,7 +987,7 @@ def _act_add_permission(data: dict, qurl: str) -> dict:
def _act_remove_permission(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
- q = _get_q(url)
+ q = _get_q(url, "sqs:RemovePermission")
label = data.get("Label") or ""
if not label:
raise _Err("MissingParameter",
@@ -902,7 +1020,7 @@ def _act_remove_permission(data: dict, qurl: str) -> dict:
def _act_purge_queue(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
- q = _get_q(url)
+ q = _get_q(url, "sqs:PurgeQueue")
q["messages"].clear()
return {}
@@ -911,7 +1029,7 @@ def _act_purge_queue(data: dict, qurl: str) -> dict:
def _act_send_message_batch(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
- _get_q(url)
+ _get_q(url, "sqs:SendMessage")
entries = data.get("Entries", [])
_validate_batch_entries(entries, "SendMessageBatchRequestEntry")
@@ -957,7 +1075,7 @@ def _act_send_message_batch(data: dict, qurl: str) -> dict:
def _act_delete_message_batch(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
- q = _get_q(url)
+ q = _get_q(url, "sqs:DeleteMessage")
entries = data.get("Entries", [])
_validate_batch_entries(entries, "DeleteMessageBatchRequestEntry")
ok: list = []
@@ -991,13 +1109,13 @@ def _act_delete_message_batch(data: dict, qurl: str) -> dict:
def _act_list_queue_tags(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
- q = _get_q(url)
+ q = _get_q(url, "sqs:ListQueueTags")
return {"Tags": dict(q.get("tags", {}))}
def _act_tag_queue(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
- q = _get_q(url)
+ q = _get_q(url, "sqs:TagQueue")
raw_tags = data.get("Tags") or {}
# Real AWS rejects null tag VALUES (a JSON null in the wire payload) with
# InvalidParameterValue (400). boto3's Python client blocks this at the
@@ -1020,7 +1138,7 @@ def _act_tag_queue(data: dict, qurl: str) -> dict:
def _act_untag_queue(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
- q = _get_q(url)
+ q = _get_q(url, "sqs:UntagQueue")
for k in data.get("TagKeys", []):
q.get("tags", {}).pop(k, None)
return {}
@@ -1055,7 +1173,7 @@ _HANDLERS.update({
# QUEUE / MESSAGE HELPERS
# ────────────────────────────────────────────────────────────
-def _get_q(url: str) -> dict:
+def _get_q(url: str, action: str | None = None) -> dict:
q = _queues.get(url)
if q is None:
# Fallback: extract queue name from URL and look up by name.
@@ -1064,14 +1182,21 @@ def _get_q(url: str) -> dict:
# is passed instead of a full URL (supported by AWS and some SDKs).
account_id, name = _queue_ref_from_urlish(url)
if account_id and _ACCOUNT_ID_RE.match(account_id) and account_id != get_account_id():
- raise _Err("QueueDoesNotExist",
- "The specified queue does not exist for this wsdl version.")
- canonical_url = _queue_name_to_url.get(name)
- if canonical_url:
- q = _queues.get(canonical_url)
+ # A QueueUrl naming another account addresses that account's queue,
+ # like real SQS — resolved here and gated on the queue Policy below
+ # instead of answering NonExistentQueue unconditionally.
+ canonical_url = _queue_name_to_url.get_scoped(account_id, get_region(), name)
+ if canonical_url:
+ q = _queues.get_scoped(account_id, get_region(), canonical_url)
+ else:
+ canonical_url = _queue_name_to_url.get(name)
+ if canonical_url:
+ q = _queues.get(canonical_url)
if q is None:
raise _Err("QueueDoesNotExist",
"The specified queue does not exist for this wsdl version.")
+ if action is not None:
+ _enforce_queue_policy(q, action)
return q
@@ -1610,6 +1735,7 @@ def _normalise(action: str, params: dict) -> dict:
for key in ("QueueName", "QueueUrl", "MessageBody", "ReceiptHandle",
"VisibilityTimeout", "DelaySeconds", "WaitTimeSeconds",
"MaxNumberOfMessages", "MaxResults", "QueueNamePrefix",
+ "QueueOwnerAWSAccountId",
"NextToken", "MessageGroupId", "MessageDeduplicationId",
"ReceiveRequestAttemptId"):
v = _p(params, key)
diff --git a/tests/conftest.py b/tests/conftest.py
index fa347bac..e0648ed2 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -66,6 +66,38 @@ def make_client(service, additional_config_kwargs=None):
return boto3.client(service, **_default_kwargs, config=Config(**_default_config_kwargs, **additional_config_kwargs))
+def sqs_policy_allow_s3(queue_arn, bucket, account):
+ """Queue policy document letting one S3 bucket notify the queue.
+
+ The AWS shape (service principal + SourceArn/SourceAccount conditions);
+ real S3 refuses a notification config whose queue lacks it.
+ """
+ return {
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Sid": "s3-notify", "Effect": "Allow",
+ "Principal": {"Service": "s3.amazonaws.com"},
+ "Action": "sqs:SendMessage", "Resource": queue_arn,
+ "Condition": {
+ "ArnLike": {"aws:SourceArn": f"arn:aws:s3:*:*:{bucket}"},
+ "StringEquals": {"aws:SourceAccount": account}}}]}
+
+
+def sqs_policy_allow_sns(queue_arn, topic_arn):
+ """Queue policy document letting one SNS topic fan out to the queue.
+
+ The AWS shape (service principal + SourceArn condition); without it SNS
+ cannot deliver, even in the same account.
+ """
+ return {
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Sid": "sns-fanout", "Effect": "Allow",
+ "Principal": {"Service": "sns.amazonaws.com"},
+ "Action": "sqs:SendMessage", "Resource": queue_arn,
+ "Condition": {"ArnEquals": {"aws:SourceArn": topic_arn}}}]}
+
+
_SERIAL_TESTS = {
"tests/test_athena.py::test_athena_engine_mock_via_config",
"tests/test_athena.py::test_athena_mixed_glue_and_s3_uri",
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index b1cc7132..6673d751 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -14,6 +14,7 @@ import boto3
import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
+from conftest import sqs_policy_allow_s3
from ministack.services import pipes as _pipes
from ministack.services.cloudformation.provisioners import (
@@ -703,6 +704,10 @@ def test_cfn_s3_bucket_notification_configuration(cfn, s3, sqs):
queue_arn = sqs.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=queue_url,
+ Attributes={"Policy": json.dumps(
+ sqs_policy_allow_s3(queue_arn, "cfn-notif-bucket", "000000000000"))})
def template(with_notif):
props = {"BucketName": "cfn-notif-bucket"}
@@ -7635,6 +7640,24 @@ def test_cfn_pipes_dynamodb_stream_to_sns(cfn, ddb, sqs):
"Endpoint": {"Fn::GetAtt": ["PipeQueue", "Arn"]},
},
},
+ "PipeQueuePolicy": {
+ "Type": "AWS::SQS::QueuePolicy",
+ "Properties": {
+ "Queues": [{"Ref": "PipeQueue"}],
+ "PolicyDocument": {
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Sid": "sns-fanout",
+ "Effect": "Allow",
+ "Principal": {"Service": "sns.amazonaws.com"},
+ "Action": "sqs:SendMessage",
+ "Resource": {"Fn::GetAtt": ["PipeQueue", "Arn"]},
+ "Condition": {"ArnEquals": {
+ "aws:SourceArn": {"Ref": "PipeTopic"}}},
+ }],
+ },
+ },
+ },
"DdbToSnsPipe": {
"Type": "AWS::Pipes::Pipe",
"Properties": {
@@ -7771,6 +7794,24 @@ def test_cfn_sns_topic_subscription_filter_policy_scope(cfn, sns, sqs):
"FilterPolicy": {"color": ["blue"]},
},
},
+ "FilterQueuePolicy": {
+ "Type": "AWS::SQS::QueuePolicy",
+ "Properties": {
+ "Queues": [{"Ref": "FilterQueue"}],
+ "PolicyDocument": {
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Sid": "sns-fanout",
+ "Effect": "Allow",
+ "Principal": {"Service": "sns.amazonaws.com"},
+ "Action": "sqs:SendMessage",
+ "Resource": {"Fn::GetAtt": ["FilterQueue", "Arn"]},
+ "Condition": {"ArnEquals": {
+ "aws:SourceArn": {"Ref": "FilterTopic"}}},
+ }],
+ },
+ },
+ },
},
"Outputs": {
"TopicArn": {"Value": {"Ref": "FilterTopic"}},
@@ -7837,6 +7878,24 @@ def test_cfn_sns_subscription_raw_message_delivery(cfn, sns, sqs):
"RawMessageDelivery": True,
},
},
+ "RawQueuePolicy": {
+ "Type": "AWS::SQS::QueuePolicy",
+ "Properties": {
+ "Queues": [{"Ref": "RawQueue"}],
+ "PolicyDocument": {
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Sid": "sns-fanout",
+ "Effect": "Allow",
+ "Principal": {"Service": "sns.amazonaws.com"},
+ "Action": "sqs:SendMessage",
+ "Resource": {"Fn::GetAtt": ["RawQueue", "Arn"]},
+ "Condition": {"ArnEquals": {
+ "aws:SourceArn": {"Ref": "RawTopic"}}},
+ }],
+ },
+ },
+ },
},
"Outputs": {
"TopicArn": {"Value": {"Ref": "RawTopic"}},
diff --git a/tests/test_cloudwatch.py b/tests/test_cloudwatch.py
index 6c39c3cd..67e9f0cc 100644
--- a/tests/test_cloudwatch.py
+++ b/tests/test_cloudwatch.py
@@ -4,6 +4,7 @@ import uuid as _uuid_mod
import pytest
from botocore.exceptions import ClientError
+from conftest import sqs_policy_allow_sns
def test_cloudwatch_metrics(cw):
@@ -629,6 +630,9 @@ def test_cloudwatch_alarm_actions_publish_to_sns(cw, sns, sqs):
queue_arn = sqs.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=queue_url,
+ Attributes={"Policy": json.dumps(sqs_policy_allow_sns(queue_arn, topic_arn))})
sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=queue_arn)
cw.put_metric_alarm(
diff --git a/tests/test_eventbridge.py b/tests/test_eventbridge.py
index 6c9f2946..80e86418 100644
--- a/tests/test_eventbridge.py
+++ b/tests/test_eventbridge.py
@@ -8,6 +8,7 @@ import zipfile
import boto3
import pytest
from botocore.exceptions import ClientError
+from conftest import sqs_policy_allow_sns
_ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
@@ -342,6 +343,9 @@ def test_eventbridge_same_region_sns_target_dispatches_to_topic(eb, sns, sqs):
QueueUrl=q_url,
AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=q_url,
+ Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)
eb.put_rule(
Name=rule_name,
diff --git a/tests/test_iot_data.py b/tests/test_iot_data.py
index 078ab48c..d3b69177 100644
--- a/tests/test_iot_data.py
+++ b/tests/test_iot_data.py
@@ -31,7 +31,7 @@ import boto3
import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
-from conftest import patch_endpoint_dns
+from conftest import patch_endpoint_dns, sqs_policy_allow_sns
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
@@ -1112,6 +1112,9 @@ def test_iot_rule_sns_action_publishes_to_topic(iot_client, iot_data_client, sns
queue_arn = sqs.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=queue_url,
+ Attributes={"Policy": json.dumps(sqs_policy_allow_sns(queue_arn, topic_arn))})
sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=queue_arn)
rule = _unique("snsrule").replace("-", "_")
diff --git a/tests/test_messaging_policies.py b/tests/test_messaging_policies.py
new file mode 100644
index 00000000..6c5efbae
--- /dev/null
+++ b/tests/test_messaging_policies.py
@@ -0,0 +1,654 @@
+"""SQS queue-policy and SNS topic-policy enforcement.
+
+The Policy attributes were stored (CRUD) but never evaluated. Under AUTH=true
+they are now enforced:
+
+- Same-account API calls pass unless the policy carries an explicit Deny.
+- Cross-account API calls need an explicit Allow (AccessDenied /
+ AuthorizationError otherwise).
+- S3→SQS, S3→SNS and SNS→SQS deliveries need an explicit Allow for the
+ calling service in the destination policy (with its SourceArn/SourceAccount
+ conditions); without one the delivery is dropped, like real AWS.
+- S3 refuses a notification config whose SQS/SNS destination denies it
+ (InvalidArgument), unless SkipDestinationValidation skips the probe.
+
+With AUTH=false every path stays permissive, like the rest of the identity
+layer. The shared CI server runs with auth disabled, so these tests drive the
+service modules in-process with AUTH monkeypatched (the test_cfn capabilities
+pattern) instead of going over HTTP.
+"""
+
+import json
+import re
+import uuid
+
+import pytest
+from conftest import (
+ REGION,
+ sqs_policy_allow_s3,
+ sqs_policy_allow_sns,
+)
+
+from ministack.core.iam_evaluator import (
+ EvalContext,
+ evaluate_resource_policy,
+)
+from ministack.core.responses import request_scope
+from ministack.services import s3 as s3_svc
+from ministack.services import sns as sns_svc
+from ministack.services import sqs as sqs_svc
+
+ACCT_A = "111111111111"
+ACCT_B = "222222222222"
+
+
+def _reset_messaging_state():
+ from ministack.core.iam_evaluator import _request_caller_arn
+
+ sqs_svc.reset()
+ sns_svc.reset()
+ s3_svc.reset()
+ _request_caller_arn.set("")
+
+
+def auth(monkeypatch):
+ """AUTH=true with clean in-process SQS/SNS/S3 state."""
+ import ministack.app as app_mod
+
+ monkeypatch.setattr(app_mod, "AUTH", True)
+ _reset_messaging_state()
+ yield
+ _reset_messaging_state()
+
+
+def noauth(monkeypatch):
+ """AUTH=false with clean in-process SQS/SNS/S3 state."""
+ import ministack.app as app_mod
+
+ monkeypatch.setattr(app_mod, "AUTH", False)
+ _reset_messaging_state()
+ yield
+ _reset_messaging_state()
+
+
+def _uniq(prefix):
+ return f"{prefix}-{uuid.uuid4().hex[:8]}"
+
+
+def _as(account, fn, *args, **kwargs):
+ """Call an in-process service function as *account* in the test region."""
+ with request_scope(account, REGION):
+ return fn(*args, **kwargs)
+
+
+def _resp_detail(resp):
+ """``(status, code, message)`` of an in-process SNS/S3 response tuple."""
+ status, _headers, body = resp
+ text = body.decode("utf-8", errors="replace") if isinstance(body, bytes) else str(body)
+ code = re.search(r"<Code>([^<]*)</Code>", text)
+ msg = re.search(r"<Message>([^<]*)</Message>", text)
+ return (status, code.group(1) if code else "",
+ msg.group(1) if msg else "")
+
+
+def _resp_code(resp):
+ """``(status, code)`` of an in-process SNS/S3 response tuple."""
+ status, code, _ = _resp_detail(resp)
+ return status, code
+
+
+def _qarn(account, name):
+ return f"arn:aws:sqs:{REGION}:{account}:{name}"
+
+
+def _tarn(account, name):
+ return f"arn:aws:sns:{REGION}:{account}:{name}"
+
+
+def _make_queue(account, name, policy=None):
+ url = _as(account, sqs_svc._act_create_queue,
+ {"QueueName": name}, "")["QueueUrl"]
+ if policy is not None:
+ _as(account, sqs_svc._act_set_queue_attributes,
+ {"QueueUrl": url,
+ "Attributes": {"Policy": json.dumps(policy)}}, url)
+ return url
+
+
+def _queue_bodies(arn):
+ q = sqs_svc._queue_by_arn(arn)
+ assert q is not None
+ return [m["body"] for m in q["messages"]]
+
+
+def _deny_all(arn, action):
+ return {"Version": "2012-10-17", "Statement": [{
+ "Sid": "deny", "Effect": "Deny", "Principal": {"AWS": "*"},
+ "Action": action, "Resource": arn}]}
+
+
+def _allow_account(arn, account, action):
+ return {"Version": "2012-10-17", "Statement": [{
+ "Sid": "x", "Effect": "Allow", "Principal": {"AWS": account},
+ "Action": action, "Resource": arn}]}
+
+
+def _make_topic(account, name):
+ assert _resp_code(_as(account, sns_svc._create_topic,
+ {"Name": name})) == (200, "")
+ return _tarn(account, name)
+
+
+def _set_topic_policy(account, arn, policy):
+ assert _resp_code(_as(account, sns_svc._set_topic_attributes, {
+ "TopicArn": arn, "AttributeName": "Policy",
+ "AttributeValue": json.dumps(policy)})) == (200, "")
+
+
+def _topic_policy(arn):
+ topic = sns_svc._topic_by_arn_any_scope(arn)
+ assert topic is not None
+ return json.loads(topic["attributes"]["Policy"])
+
+
+def _make_bucket(account, name):
+ assert _resp_code(_as(account, s3_svc._create_bucket,
+ name, b"", {})) == (200, "")
+
+
+def _notif_xml(kind, arn):
+ tag = "Queue" if kind == "sqs" else "Topic"
+ return (
+ "<NotificationConfiguration>"
+ f"<{tag}Configuration><{tag}>{arn}</{tag}>"
+ "<Event>s3:ObjectCreated:*</Event>"
+ f"</{tag}Configuration>"
+ "</NotificationConfiguration>"
+ ).encode()
+
+
+def _put_notif(account, bucket, kind, arn, skip=False):
+ headers = {"x-amz-skip-destination-validation": "true"} if skip else {}
+ return _as(account, s3_svc._put_bucket_notification,
+ bucket, _notif_xml(kind, arn), headers)
+
+
+# ---------------------------------------------------------------------------
+# Unit: evaluate_resource_policy Service principals
+# ---------------------------------------------------------------------------
+
+def _ctx(action="sqs:SendMessage", resource="arn:aws:sqs:us-east-1:1:q",
+ source_arn="", source_account="", principal="arn:aws:iam::1:root"):
+ return EvalContext(
+ principal_arn=principal,
+ principal_type="Service",
+ principal_account="1",
+ action=action,
+ resource_arn=resource,
+ region="us-east-1",
+ service_context={"aws:sourcearn": source_arn,
+ "aws:sourceaccount": source_account,
+ "aws:sourceowner": source_account},
+ )
+
+
+def _svc_policy():
+ return {
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Effect": "Allow",
+ "Principal": {"Service": "s3.amazonaws.com"},
+ "Action": "sqs:SendMessage",
+ "Resource": "arn:aws:sqs:us-east-1:1:q",
+ "Condition": {"ArnLike": {"aws:SourceArn": "arn:aws:s3:*:*:bkt"}},
+ }],
+ }
+
+
+class TestEvaluateResourcePolicyService:
+ def test_service_principal_allows_matching_service(self):
+ assert evaluate_resource_policy(
+ _svc_policy(), _ctx(source_arn="arn:aws:s3:::bkt"),
+ service="s3.amazonaws.com").decision == "Allow"
+
+ def test_service_principal_ignores_other_service(self):
+ assert evaluate_resource_policy(
+ _svc_policy(), _ctx(source_arn="arn:aws:s3:::bkt"),
+ service="sns.amazonaws.com").decision == "ImplicitDeny"
+
+ def test_service_principal_ignored_without_service_arg(self):
+ # Legacy callers (Lambda layer policies, S3 bucket policies) keep the
+ # old behaviour: Service entries never match.
+ assert evaluate_resource_policy(
+ _svc_policy(), _ctx(source_arn="arn:aws:s3:::bkt")).decision == "ImplicitDeny"
+
+ def test_wrong_source_arn_denies(self):
+ assert evaluate_resource_policy(
+ _svc_policy(), _ctx(source_arn="arn:aws:s3:::other"),
+ service="s3.amazonaws.com").decision == "ImplicitDeny"
+
+ def test_aws_principal_still_matches(self):
+ doc = {"Statement": [{
+ "Effect": "Allow", "Principal": {"AWS": "222222222222"},
+ "Action": "sqs:SendMessage", "Resource": "*"}]}
+ ctx = _ctx(principal="arn:aws:iam::222222222222:root")
+ assert evaluate_resource_policy(doc, ctx).decision == "Allow"
+
+ def test_star_principal_matches(self):
+ doc = {"Statement": [{
+ "Effect": "Allow", "Principal": "*",
+ "Action": "sqs:SendMessage", "Resource": "*"}]}
+ assert evaluate_resource_policy(doc, _ctx()).decision == "Allow"
+
+
+# ---------------------------------------------------------------------------
+# Cross-account SQS
+# ---------------------------------------------------------------------------
+
+class TestCrossAccountSqs:
+ def test_send_denied_without_policy(self, auth):
+ url = _make_queue(ACCT_A, _uniq("xpol-q"))
+ with pytest.raises(sqs_svc._Err) as exc:
+ _as(ACCT_B, sqs_svc._act_send_message,
+ {"QueueUrl": url, "MessageBody": "no-policy"}, url)
+ assert exc.value.code == "AccessDenied"
+ assert exc.value.status == 403
+
+ def test_send_allowed_with_policy(self, auth):
+ name = _uniq("xpol-q")
+ url = _make_queue(ACCT_A, name, _allow_account(
+ _qarn(ACCT_A, name), ACCT_B, "sqs:SendMessage"))
+ _as(ACCT_B, sqs_svc._act_send_message,
+ {"QueueUrl": url, "MessageBody": "with-policy"}, url)
+ assert _queue_bodies(_qarn(ACCT_A, name)) == ["with-policy"]
+
+ def test_send_allowed_via_add_permission(self, auth):
+ name = _uniq("xpol-q")
+ url = _make_queue(ACCT_A, name)
+ _as(ACCT_A, sqs_svc._act_add_permission,
+ {"QueueUrl": url, "Label": "xacct",
+ "AWSAccountIds": [ACCT_B], "Actions": ["SendMessage"]}, url)
+ _as(ACCT_B, sqs_svc._act_send_message,
+ {"QueueUrl": url, "MessageBody": "via-add-permission"}, url)
+ assert _queue_bodies(_qarn(ACCT_A, name)) == ["via-add-permission"]
+
+ def test_explicit_deny_blocks_same_account(self, auth):
+ name = _uniq("xpol-q")
+ url = _make_queue(ACCT_A, name, _deny_all(
+ _qarn(ACCT_A, name), "sqs:SendMessage"))
+ with pytest.raises(sqs_svc._Err) as exc:
+ _as(ACCT_A, sqs_svc._act_send_message,
+ {"QueueUrl": url, "MessageBody": "deny-me"}, url)
+ assert exc.value.code == "AccessDenied"
+
+ def test_get_queue_url_with_owner_account(self, auth):
+ name = _uniq("xpol-q")
+ url = _make_queue(ACCT_A, name, _allow_account(
+ _qarn(ACCT_A, name), ACCT_B, "sqs:GetQueueUrl"))
+ found = _as(ACCT_B, sqs_svc._act_get_queue_url,
+ {"QueueName": name,
+ "QueueOwnerAWSAccountId": ACCT_A}, "")["QueueUrl"]
+ assert found == url
+
+ def test_get_queue_url_cross_account_denied_without_policy(self, auth):
+ name = _uniq("xpol-q")
+ _make_queue(ACCT_A, name)
+ with pytest.raises(sqs_svc._Err) as exc:
+ _as(ACCT_B, sqs_svc._act_get_queue_url,
+ {"QueueName": name,
+ "QueueOwnerAWSAccountId": ACCT_A}, "")
+ assert exc.value.code == "AccessDenied"
+ assert exc.value.status == 403
+
+ def test_get_queue_url_same_account_denied_by_explicit_deny(self, auth):
+ name = _uniq("xpol-q")
+ _make_queue(ACCT_A, name, _deny_all(
+ _qarn(ACCT_A, name), "sqs:GetQueueUrl"))
+ with pytest.raises(sqs_svc._Err) as exc:
+ _as(ACCT_A, sqs_svc._act_get_queue_url,
+ {"QueueName": name}, "")
+ assert exc.value.code == "AccessDenied"
+ assert exc.value.status == 403
+
+ def test_get_queue_url_same_account_passes_without_policy(self, auth):
+ name = _uniq("xpol-q")
+ url = _make_queue(ACCT_A, name)
+ assert _as(ACCT_A, sqs_svc._act_get_queue_url,
+ {"QueueName": name}, "") == {"QueueUrl": url}
+
+
+# ---------------------------------------------------------------------------
+# Cross-account SNS (+ AddPermission/RemovePermission)
+# ---------------------------------------------------------------------------
+
+class TestCrossAccountSns:
+ def test_publish_denied_by_default(self, auth):
+ arn = _make_topic(ACCT_A, _uniq("xpol-t"))
+ assert _resp_code(_as(ACCT_B, sns_svc._publish, {
+ "TopicArn": arn, "Message": "no-grant"})) == (403, "AuthorizationError")
+
+ def test_publish_allowed_with_policy(self, auth):
+ name = _uniq("xpol-t")
+ arn = _make_topic(ACCT_A, name)
+ _set_topic_policy(ACCT_A, arn, _allow_account(
+ arn, ACCT_B, "sns:Publish"))
+ assert _resp_code(_as(ACCT_B, sns_svc._publish, {
+ "TopicArn": arn, "Message": "granted"})) == (200, "")
+ topic = sns_svc._topic_by_arn_any_scope(arn)
+ assert [m["message"] for m in topic["messages"]] == ["granted"]
+
+ def test_explicit_deny_blocks_same_account(self, auth):
+ name = _uniq("xpol-t")
+ arn = _make_topic(ACCT_A, name)
+ _set_topic_policy(ACCT_A, arn, _deny_all(arn, "sns:Publish"))
+ assert _resp_code(_as(ACCT_A, sns_svc._publish, {
+ "TopicArn": arn, "Message": "deny-me"})) == (403, "AuthorizationError")
+
+ def test_add_permission_grants_cross_account_publish(self, auth):
+ arn = _make_topic(ACCT_A, _uniq("xpol-t"))
+ assert _resp_code(_as(ACCT_A, sns_svc._add_permission, {
+ "TopicArn": arn, "Label": "perm-1",
+ "AWSAccountId.member.1": ACCT_B,
+ "ActionName.member.1": "Publish"})) == (200, "")
+ stmt = next(s for s in _topic_policy(arn)["Statement"]
+ if s.get("Sid") == "perm-1")
+ assert ACCT_B in stmt["Principal"]["AWS"]
+ assert "sns:Publish" in stmt["Action"]
+ assert _resp_code(_as(ACCT_B, sns_svc._publish, {
+ "TopicArn": arn,
+ "Message": "via-add-permission"})) == (200, "")
+
+ def test_add_permission_rejects_duplicate_label(self, auth):
+ arn = _make_topic(ACCT_A, _uniq("xpol-t"))
+ params = {"TopicArn": arn, "Label": "dup",
+ "AWSAccountId.member.1": ACCT_B,
+ "ActionName.member.1": "Publish"}
+ assert _resp_code(_as(ACCT_A, sns_svc._add_permission, params)) == (200, "")
+ assert _resp_code(
+ _as(ACCT_A, sns_svc._add_permission, params)) == (
+ 400, "InvalidParameterException")
+
+ def test_cross_account_tag_access_needs_grant(self, auth):
+ name = _uniq("xpol-t")
+ arn = _make_topic(ACCT_A, name)
+ assert _resp_code(_as(ACCT_B, sns_svc._list_tags_for_resource, {
+ "ResourceArn": arn})) == (403, "AuthorizationError")
+ _set_topic_policy(ACCT_A, arn, _allow_account(
+ arn, ACCT_B, ["sns:TagResource", "sns:ListTagsForResource"]))
+ assert _resp_code(_as(ACCT_B, sns_svc._tag_resource, {
+ "ResourceArn": arn, "Tags.member.1.Key": "k",
+ "Tags.member.1.Value": "v"})) == (200, "")
+ assert _resp_code(_as(ACCT_B, sns_svc._list_tags_for_resource, {
+ "ResourceArn": arn})) == (200, "")
+ assert sns_svc._topic_by_arn_any_scope(arn)["tags"] == {"k": "v"}
+
+ def test_remove_permission_drops_statement(self, auth):
+ arn = _make_topic(ACCT_A, _uniq("xpol-t"))
+ _as(ACCT_A, sns_svc._add_permission, {
+ "TopicArn": arn, "Label": "drop",
+ "AWSAccountId.member.1": ACCT_B,
+ "ActionName.member.1": "Publish"})
+ assert _resp_code(_as(ACCT_B, sns_svc._publish, {
+ "TopicArn": arn, "Message": "before"})) == (200, "")
+ assert _resp_code(_as(ACCT_A, sns_svc._remove_permission, {
+ "TopicArn": arn, "Label": "drop"})) == (200, "")
+ assert all(s.get("Sid") != "drop"
+ for s in _topic_policy(arn)["Statement"])
+ assert _resp_code(_as(ACCT_B, sns_svc._publish, {
+ "TopicArn": arn, "Message": "after"})) == (403, "AuthorizationError")
+
+
+# ---------------------------------------------------------------------------
+# S3 notifications gated on the destination policy
+# ---------------------------------------------------------------------------
+
+def _bucket_and_queue(tag):
+ bucket, qname = _uniq(f"{tag}-bkt"), _uniq(f"{tag}-q")
+ _make_bucket(ACCT_A, bucket)
+ url = _make_queue(ACCT_A, qname)
+ return bucket, url, _qarn(ACCT_A, qname)
+
+
+def _assert_put_rejected(bucket, kind, arn):
+ status, code, msg = _resp_detail(_put_notif(ACCT_A, bucket, kind, arn))
+ assert status == 400
+ assert code == "InvalidArgument"
+ assert "Unable to validate the following destination configurations" in msg
+
+
+def _bucket_topic_queue(tag):
+ bucket = _uniq(f"{tag}-bkt")
+ _make_bucket(ACCT_A, bucket)
+ topic = _make_topic(ACCT_A, _uniq(f"{tag}-t"))
+ qname = _uniq(f"{tag}-q")
+ qurl = _make_queue(ACCT_A, qname,
+ sqs_policy_allow_sns(_qarn(ACCT_A, qname), topic))
+ assert _resp_code(_as(ACCT_A, sns_svc._subscribe, {
+ "TopicArn": topic, "Protocol": "sqs",
+ "Endpoint": _qarn(ACCT_A, qname)})) == (200, "")
+ return bucket, topic, qurl, _qarn(ACCT_A, qname)
+
+
+class TestS3NotificationPolicies:
+ def test_s3_put_rejected_without_queue_policy(self, auth):
+ bucket, _url, arn = _bucket_and_queue("xpol")
+ _assert_put_rejected(bucket, "sqs", arn)
+
+ def test_s3_put_rejected_by_unrelated_policy(self, auth):
+ bucket, url, arn = _bucket_and_queue("xpol")
+ _as(ACCT_A, sqs_svc._act_set_queue_attributes,
+ {"QueueUrl": url, "Attributes": {"Policy": json.dumps(
+ _allow_account(arn, ACCT_B, "sqs:SendMessage"))}}, url)
+ _assert_put_rejected(bucket, "sqs", arn)
+
+ def test_s3_put_rejected_by_wrong_source_arn(self, auth):
+ bucket, url, arn = _bucket_and_queue("xpol")
+ _as(ACCT_A, sqs_svc._act_set_queue_attributes,
+ {"QueueUrl": url, "Attributes": {"Policy": json.dumps(
+ sqs_policy_allow_s3(arn, "no-such-bucket", ACCT_A))}}, url)
+ _assert_put_rejected(bucket, "sqs", arn)
+
+ def test_s3_to_sqs_delivered_with_policy(self, auth):
+ bucket, url, arn = _bucket_and_queue("xpol")
+ _as(ACCT_A, sqs_svc._act_set_queue_attributes,
+ {"QueueUrl": url, "Attributes": {"Policy": json.dumps(
+ sqs_policy_allow_s3(arn, bucket, ACCT_A))}}, url)
+ assert _resp_code(_put_notif(ACCT_A, bucket, "sqs", arn)) == (200, "")
+ bodies = _queue_bodies(arn)
+ assert len(bodies) == 1
+ assert "s3:TestEvent" in bodies[0]
+
+ def test_s3_skip_validation_stores_but_delivery_blocked(self, auth):
+ bucket, _url, arn = _bucket_and_queue("xpol")
+ assert _resp_code(
+ _put_notif(ACCT_A, bucket, "sqs", arn, skip=True)) == (200, "")
+ assert _queue_bodies(arn) == []
+ _as(ACCT_A, s3_svc._deliver_event_to_sqs,
+ arn, {"Records": []}, REGION, bucket_name=bucket)
+ assert _queue_bodies(arn) == []
+
+ def test_s3_to_sns_default_policy_delivers(self, auth):
+ bucket, topic, _qurl, qarn = _bucket_topic_queue("xpol")
+ assert _resp_code(_put_notif(ACCT_A, bucket, "sns", topic)) == (200, "")
+ bodies = _queue_bodies(qarn)
+ assert len(bodies) == 1
+ assert "s3:TestEvent" in bodies[0]
+
+ def test_s3_put_rejected_by_topic_policy_without_s3(self, auth):
+ bucket, topic, _qurl, _qarn = _bucket_topic_queue("xpol")
+ _set_topic_policy(ACCT_A, topic, _allow_account(
+ topic, ACCT_A, "sns:Publish"))
+ _assert_put_rejected(bucket, "sns", topic)
+
+ def test_s3_to_sns_skip_validation_delivery_blocked(self, auth):
+ bucket, topic, _qurl, qarn = _bucket_topic_queue("xpol")
+ _set_topic_policy(ACCT_A, topic, _allow_account(
+ topic, ACCT_A, "sns:Publish"))
+ assert _resp_code(
+ _put_notif(ACCT_A, bucket, "sns", topic, skip=True)) == (200, "")
+ _as(ACCT_A, s3_svc._deliver_event_to_sns,
+ topic, {"Records": []}, REGION, bucket_name=bucket)
+ assert _queue_bodies(qarn) == []
+
+ def test_s3_to_cross_account_sns_topic_delivered_with_policy(self, auth):
+ bucket = _uniq("xpol-xbkt")
+ _make_bucket(ACCT_A, bucket)
+ topic = _make_topic(ACCT_B, _uniq("xpol-xt"))
+ _set_topic_policy(ACCT_B, topic, {
+ "Version": "2012-10-17", "Statement": [{
+ "Sid": "s3-xacct", "Effect": "Allow",
+ "Principal": {"Service": "s3.amazonaws.com"},
+ "Action": "sns:Publish", "Resource": topic,
+ "Condition": {
+ "ArnLike": {"aws:SourceArn": f"arn:aws:s3:::{bucket}"},
+ "StringEquals": {"aws:SourceAccount": ACCT_A}}}]})
+ qname = _uniq("xpol-xq")
+ _make_queue(ACCT_B, qname, sqs_policy_allow_sns(
+ _qarn(ACCT_B, qname), topic))
+ assert _resp_code(_as(ACCT_B, sns_svc._subscribe, {
+ "TopicArn": topic, "Protocol": "sqs",
+ "Endpoint": _qarn(ACCT_B, qname)})) == (200, "")
+ # The topic lives in another account, but its policy allows this
+ # bucket's deliveries, so the PUT validates instead of failing.
+ assert _resp_code(_put_notif(ACCT_A, bucket, "sns", topic)) == (200, "")
+ bodies = _queue_bodies(_qarn(ACCT_B, qname))
+ assert len(bodies) == 1
+ assert "s3:TestEvent" in bodies[0]
+
+ def test_s3_to_cross_account_sqs_queue_delivered_with_policy(self, auth):
+ bucket = _uniq("xpol-xbkt")
+ _make_bucket(ACCT_A, bucket)
+ qname = _uniq("xpol-xq")
+ _make_queue(ACCT_B, qname, sqs_policy_allow_s3(
+ _qarn(ACCT_B, qname), bucket, ACCT_A))
+ assert _resp_code(
+ _put_notif(ACCT_A, bucket, "sqs", _qarn(ACCT_B, qname))) == (200, "")
+ bodies = _queue_bodies(_qarn(ACCT_B, qname))
+ assert len(bodies) == 1
+ assert "s3:TestEvent" in bodies[0]
+
+ def test_s3_to_cross_account_topic_rejected_without_policy(self, auth):
+ bucket = _uniq("xpol-xbkt")
+ _make_bucket(ACCT_A, bucket)
+ topic = _make_topic(ACCT_B, _uniq("xpol-xt"))
+ _assert_put_rejected(bucket, "sns", topic)
+
+
+# ---------------------------------------------------------------------------
+# SNS→SQS fanout gated on the queue policy
+# ---------------------------------------------------------------------------
+
+def _topic_and_queue(tag):
+ topic = _make_topic(ACCT_A, _uniq(f"{tag}-t"))
+ qname = _uniq(f"{tag}-q")
+ qurl = _make_queue(ACCT_A, qname)
+ assert _resp_code(_as(ACCT_A, sns_svc._subscribe, {
+ "TopicArn": topic, "Protocol": "sqs",
+ "Endpoint": _qarn(ACCT_A, qname)})) == (200, "")
+ return topic, qurl, _qarn(ACCT_A, qname)
+
+
+class TestSnsFanoutPolicies:
+ def test_fanout_blocked_without_policy(self, auth):
+ topic, _qurl, qarn = _topic_and_queue("xpol-fan")
+ assert _resp_code(_as(ACCT_A, sns_svc._publish, {
+ "TopicArn": topic, "Message": "no-policy"})) == (200, "")
+ assert _queue_bodies(qarn) == []
+
+ def test_fanout_blocked_by_wrong_source_arn(self, auth):
+ topic, qurl, qarn = _topic_and_queue("xpol-fan")
+ _as(ACCT_A, sqs_svc._act_set_queue_attributes,
+ {"QueueUrl": qurl, "Attributes": {"Policy": json.dumps(
+ sqs_policy_allow_sns(
+ qarn, f"arn:aws:sns:{REGION}:{ACCT_A}:wrong-topic"))}},
+ qurl)
+ assert _resp_code(_as(ACCT_A, sns_svc._publish, {
+ "TopicArn": topic, "Message": "wrong-source"})) == (200, "")
+ assert _queue_bodies(qarn) == []
+
+ def test_fanout_delivered_with_policy(self, auth):
+ topic, qurl, qarn = _topic_and_queue("xpol-fan")
+ _as(ACCT_A, sqs_svc._act_set_queue_attributes,
+ {"QueueUrl": qurl, "Attributes": {"Policy": json.dumps(
+ sqs_policy_allow_sns(qarn, topic))}}, qurl)
+ assert _resp_code(_as(ACCT_A, sns_svc._publish, {
+ "TopicArn": topic, "Message": "with-policy"})) == (200, "")
+ bodies = _queue_bodies(qarn)
+ assert len(bodies) == 1
+ assert "with-policy" in bodies[0]
+
+ def test_cross_account_fanout_needs_queue_policy(self, auth):
+ topic = _make_topic(ACCT_A, _uniq("xpol-xfan"))
+ _set_topic_policy(ACCT_A, topic, _allow_account(
+ topic, ACCT_B, "sns:Subscribe"))
+ qname = _uniq("xpol-xfanq")
+ qurl = _make_queue(ACCT_B, qname)
+ assert _resp_code(_as(ACCT_B, sns_svc._subscribe, {
+ "TopicArn": topic, "Protocol": "sqs",
+ "Endpoint": _qarn(ACCT_B, qname)})) == (200, "")
+ assert _resp_code(_as(ACCT_A, sns_svc._publish, {
+ "TopicArn": topic, "Message": "no-queue-policy"})) == (200, "")
+ assert _queue_bodies(_qarn(ACCT_B, qname)) == []
+
+ _as(ACCT_B, sqs_svc._act_set_queue_attributes,
+ {"QueueUrl": qurl, "Attributes": {"Policy": json.dumps(
+ sqs_policy_allow_sns(_qarn(ACCT_B, qname), topic))}}, qurl)
+ assert _resp_code(_as(ACCT_A, sns_svc._publish, {
+ "TopicArn": topic, "Message": "with-queue-policy"})) == (200, "")
+ bodies = _queue_bodies(_qarn(ACCT_B, qname))
+ assert len(bodies) == 1
+ assert "with-queue-policy" in bodies[0]
+
+ def test_cross_account_subscribe_denied_without_policy(self, auth):
+ topic = _make_topic(ACCT_A, _uniq("xpol-xfan"))
+ assert _resp_code(_as(ACCT_B, sns_svc._subscribe, {
+ "TopicArn": topic, "Protocol": "email",
+ "Endpoint": "[email protected]"})) == (403, "AuthorizationError")
+
+
+# ---------------------------------------------------------------------------
+# AUTH=false stays permissive
+# ---------------------------------------------------------------------------
+
+class TestAuthDisabledIsPermissive:
+ def test_cross_account_send_passes_without_policy(self, noauth):
+ name = _uniq("xpol-q")
+ url = _make_queue(ACCT_A, name)
+ _as(ACCT_B, sqs_svc._act_send_message,
+ {"QueueUrl": url, "MessageBody": "open"}, url)
+ assert _queue_bodies(_qarn(ACCT_A, name)) == ["open"]
+
+ def test_cross_account_publish_passes_without_policy(self, noauth):
+ arn = _make_topic(ACCT_A, _uniq("xpol-t"))
+ assert _resp_code(_as(ACCT_B, sns_svc._publish, {
+ "TopicArn": arn, "Message": "open"})) == (200, "")
+
+ def test_explicit_deny_ignored(self, noauth):
+ name = _uniq("xpol-q")
+ url = _make_queue(ACCT_A, name, _deny_all(
+ _qarn(ACCT_A, name), "sqs:SendMessage"))
+ _as(ACCT_A, sqs_svc._act_send_message,
+ {"QueueUrl": url, "MessageBody": "deny-ignored"}, url)
+ assert _queue_bodies(_qarn(ACCT_A, name)) == ["deny-ignored"]
+
+ def test_get_queue_url_ignores_deny(self, noauth):
+ name = _uniq("xpol-q")
+ url = _make_queue(ACCT_A, name, _deny_all(
+ _qarn(ACCT_A, name), "sqs:GetQueueUrl"))
+ assert _as(ACCT_A, sqs_svc._act_get_queue_url,
+ {"QueueName": name}, "") == {"QueueUrl": url}
+
+ def test_s3_put_and_delivery_without_policy(self, noauth):
+ bucket, _url, arn = _bucket_and_queue("xpol")
+ assert _resp_code(_put_notif(ACCT_A, bucket, "sqs", arn)) == (200, "")
+ bodies = _queue_bodies(arn)
+ assert len(bodies) == 1
+ assert "s3:TestEvent" in bodies[0]
+
+ def test_fanout_without_policy(self, noauth):
+ topic, _qurl, qarn = _topic_and_queue("xpol-fan")
+ assert _resp_code(_as(ACCT_A, sns_svc._publish, {
+ "TopicArn": topic, "Message": "open"})) == (200, "")
+ assert len(_queue_bodies(qarn)) == 1
diff --git a/tests/test_s3.py b/tests/test_s3.py
index 3cbca048..b161593e 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -8,7 +8,7 @@ from urllib.parse import urlparse
import pytest
from botocore.exceptions import ClientError
-from conftest import make_client, patch_endpoint_dns
+from conftest import make_client, patch_endpoint_dns, sqs_policy_allow_s3
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
@@ -1637,6 +1637,10 @@ def test_s3_event_notification_to_sqs(s3, sqs):
QueueUrl=queue_url,
AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=queue_url,
+ Attributes={"Policy": json.dumps(
+ sqs_policy_allow_s3(queue_arn, "s3-evt-bkt", "000000000000"))})
s3.put_bucket_notification_configuration(
Bucket="s3-evt-bkt",
NotificationConfiguration={
@@ -1659,6 +1663,10 @@ def test_s3_event_notification_filter(s3, sqs):
QueueUrl=queue_url,
AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=queue_url,
+ Attributes={"Policy": json.dumps(
+ sqs_policy_allow_s3(queue_arn, "s3-evt-filter-bkt", "000000000000"))})
s3.put_bucket_notification_configuration(
Bucket="s3-evt-filter-bkt",
NotificationConfiguration={
@@ -1686,6 +1694,10 @@ def test_s3_event_notification_delete(s3, sqs):
QueueUrl=queue_url,
AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=queue_url,
+ Attributes={"Policy": json.dumps(
+ sqs_policy_allow_s3(queue_arn, "s3-evt-del-bkt", "000000000000"))})
s3.put_bucket_notification_configuration(
Bucket="s3-evt-del-bkt",
NotificationConfiguration={
@@ -1709,6 +1721,10 @@ def test_s3_put_notification_sends_test_event(s3, sqs):
QueueUrl=queue_url,
AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=queue_url,
+ Attributes={"Policy": json.dumps(
+ sqs_policy_allow_s3(queue_arn, bkt, "000000000000"))})
s3.put_bucket_notification_configuration(
Bucket=bkt,
NotificationConfiguration={
@@ -1780,7 +1796,13 @@ def test_s3_notification_validates_target_region_against_bucket_region(s3):
)
# The destination has to exist: AWS verifies an SQS or SNS target by sending
# it a test notification and fails the whole PUT when that does not arrive.
- _regional_client("sqs", "us-west-2").create_queue(QueueName="s3-west-region-q")
+ _west_sqs = _regional_client("sqs", "us-west-2")
+ _west_q_url = _west_sqs.create_queue(QueueName="s3-west-region-q")["QueueUrl"]
+ _west_sqs.set_queue_attributes(
+ QueueUrl=_west_q_url,
+ Attributes={"Policy": json.dumps(sqs_policy_allow_s3(
+ "arn:aws:sqs:us-west-2:000000000000:s3-west-region-q",
+ bkt, "000000000000"))})
s3.put_bucket_notification_configuration(
Bucket=bkt,
@@ -1809,15 +1831,11 @@ def test_s3_notification_validates_target_region_against_bucket_region(s3):
assert exc.value.response["Error"]["Code"] == "InvalidArgument"
- "target_arn",
- [
- "arn:aws:sqs:us-east-1:000000000001:shared-q",
- "arn:aws:sqs:us-west-2:000000000000:shared-q",
- ],
-)
+# A same-region queue in another account is in scope: S3 delivers to it when
+# its policy allows (see test_messaging_policies.py). Only a wrong-region ARN
+# stays out of scope here.
def test_s3_notification_sqs_delivery_rejects_out_of_scope_arns_without_name_fallback(
- monkeypatch, target_arn,
+ monkeypatch,
):
from ministack.services import s3 as s3mod
from ministack.services import sqs as sqsmod
@@ -1828,24 +1846,22 @@ def test_s3_notification_sqs_delivery_rejects_out_of_scope_arns_without_name_fal
monkeypatch.setattr(sqsmod, "_queues", {"url/shared-q": {"messages": messages}})
monkeypatch.setattr(sqsmod, "_ensure_msg_fields", lambda msg: None)
- s3mod._deliver_event_to_sqs(target_arn, {"Records": []}, "us-east-1")
+ s3mod._deliver_event_to_sqs(
+ "arn:aws:sqs:us-west-2:000000000000:shared-q", {"Records": []}, "us-east-1")
assert messages == []
- "target_arn",
- [
- "arn:aws:sns:us-east-1:000000000001:shared-topic",
- "arn:aws:sns:us-west-2:000000000000:shared-topic",
- ],
-)
+# A same-region topic in another account is in scope: S3 delivers to it when
+# its policy allows (see test_messaging_policies.py). Only a wrong-region ARN
+# stays out of scope here.
def test_s3_notification_sns_delivery_rejects_out_of_scope_arns_before_fanout(
- monkeypatch, target_arn,
+ monkeypatch,
):
from ministack.services import s3 as s3mod
from ministack.services import sns as snsmod
+ target_arn = "arn:aws:sns:us-west-2:000000000000:shared-topic"
fanouts = []
monkeypatch.setattr(s3mod, "get_account_id", lambda: "000000000000")
monkeypatch.setattr(snsmod, "_topics", {target_arn: {"subscriptions": []}})
@@ -1913,6 +1929,10 @@ def test_s3_event_notification_cross_account():
)["Attributes"]["QueueArn"]
# Confirm the clients really resolve to the non-default account.
assert f":{account}:" in queue_arn
+ sqsc.set_queue_attributes(
+ QueueUrl=queue_url,
+ Attributes={"Policy": json.dumps(
+ sqs_policy_allow_s3(queue_arn, "s3-evt-xacct-bkt", account))})
s3c.put_bucket_notification_configuration(
Bucket="s3-evt-xacct-bkt",
@@ -4669,6 +4689,10 @@ def test_s3_event_to_sqs(s3, sqs):
queue_arn = sqs.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=queue_url,
+ Attributes={"Policy": json.dumps(
+ sqs_policy_allow_s3(queue_arn, bucket, "000000000000"))})
s3.put_bucket_notification_configuration(
Bucket=bucket,
@@ -6402,6 +6426,10 @@ def test_s3_restore_notifications_to_sqs(s3, sqs):
queue_arn = sqs.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=queue_url,
+ Attributes={"Policy": json.dumps(
+ sqs_policy_allow_s3(queue_arn, "qa-s3-restore-evt", "000000000000"))})
s3.put_bucket_notification_configuration(
Bucket="qa-s3-restore-evt",
NotificationConfiguration={
@@ -6931,6 +6959,10 @@ def test_s3_notification_auto_generates_a_base64_uuid_id(s3, sqs):
queue = sqs.create_queue(QueueName=f"notif-id-{_uuid_mod.uuid4().hex[:8]}")["QueueUrl"]
queue_arn = sqs.get_queue_attributes(
QueueUrl=queue, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=queue,
+ Attributes={"Policy": json.dumps(
+ sqs_policy_allow_s3(queue_arn, bucket, "000000000000"))})
s3.put_bucket_notification_configuration(
Bucket=bucket,
NotificationConfiguration={"QueueConfigurations": [
@@ -6955,6 +6987,10 @@ def test_s3_notification_keeps_an_explicit_id(s3, sqs):
queue = sqs.create_queue(QueueName=f"notif-expl-{_uuid_mod.uuid4().hex[:8]}")["QueueUrl"]
queue_arn = sqs.get_queue_attributes(
QueueUrl=queue, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=queue,
+ Attributes={"Policy": json.dumps(
+ sqs_policy_allow_s3(queue_arn, bucket, "000000000000"))})
s3.put_bucket_notification_configuration(
Bucket=bucket,
NotificationConfiguration={"QueueConfigurations": [
diff --git a/tests/test_signer.py b/tests/test_signer.py
index 5192afde..13a7885c 100644
--- a/tests/test_signer.py
+++ b/tests/test_signer.py
@@ -18,7 +18,7 @@ import uuid
import pytest
from botocore.exceptions import ClientError
-from conftest import ENDPOINT, make_client
+from conftest import ENDPOINT, make_client, sqs_policy_allow_s3
_IOT_PLATFORM = "AWSIoTDeviceManagement-SHA256-ECDSA"
_LAMBDA_PLATFORM = "AWSLambda-SHA384-ECDSA"
@@ -255,6 +255,10 @@ def test_signer_marker_write_fires_s3_object_created_notification(
queue_arn = sqs.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=queue_url,
+ Attributes={"Policy": json.dumps(
+ sqs_policy_allow_s3(queue_arn, dst, "000000000000"))})
s3.put_bucket_notification_configuration(
Bucket=dst,
NotificationConfiguration={
diff --git a/tests/test_sns.py b/tests/test_sns.py
index 2018f00a..73ca60ed 100644
--- a/tests/test_sns.py
+++ b/tests/test_sns.py
@@ -13,6 +13,8 @@ import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
+from conftest import sqs_policy_allow_sns
+
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
@@ -201,6 +203,9 @@ def test_sns_sqs_fanout(sns, sqs):
QueueUrl=q_url,
AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=q_url,
+ Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)
sns.publish(TopicArn=topic_arn, Message="fanout msg", Subject="Fan")
@@ -256,6 +261,9 @@ def test_sns_sqs_fanout_delivers_to_matching_cross_region_queue_arn(sns):
)["Attributes"]["QueueArn"]
assert ":us-west-2:" in q_arn
topic_arn = sns.create_topic(Name=f"intg-sns-cross-region-ok-{_uuid_mod.uuid4().hex[:8]}")["TopicArn"]
+ west_sqs.set_queue_attributes(
+ QueueUrl=q_url,
+ Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)
sns.publish(TopicArn=topic_arn, Message="cross-region-delivery")
@@ -417,6 +425,9 @@ def test_sns_sqs_fanout_raw_message_delivery(sns, sqs):
QueueUrl=q_url,
AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=q_url,
+ Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sns.subscribe(
TopicArn=topic_arn,
@@ -580,6 +591,9 @@ def test_sns_filter_policy_blocks_non_matching(sns, sqs):
topic_arn = sns.create_topic(Name="qa-sns-filter")["TopicArn"]
q_url = sqs.create_queue(QueueName="qa-sns-filter-q")["QueueUrl"]
q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=q_url,
+ Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sub_arn = sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)["SubscriptionArn"]
sns.set_subscription_attributes(
SubscriptionArn=sub_arn,
@@ -609,6 +623,9 @@ def test_sns_filter_policy_or_operator(sns, sqs):
topic_arn = sns.create_topic(Name="qa-sns-or")["TopicArn"]
q_url = sqs.create_queue(QueueName="qa-sns-or-q")["QueueUrl"]
q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=q_url,
+ Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sub_arn = sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)["SubscriptionArn"]
sns.set_subscription_attributes(
SubscriptionArn=sub_arn,
@@ -647,6 +664,9 @@ def test_sns_raw_message_delivery(sns, sqs):
topic_arn = sns.create_topic(Name="qa-sns-raw")["TopicArn"]
q_url = sqs.create_queue(QueueName="qa-sns-raw-q")["QueueUrl"]
q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=q_url,
+ Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sub_arn = sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)["SubscriptionArn"]
sns.set_subscription_attributes(
SubscriptionArn=sub_arn,
@@ -685,6 +705,9 @@ def test_sns_fifo_dedup_passthrough(sns, sqs):
q_arn = sqs.get_queue_attributes(
QueueUrl=q_url, AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=q_url,
+ Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)
@@ -716,6 +739,10 @@ def test_sns_to_sqs_fanout(sns, sqs):
q2_url = sqs.create_queue(QueueName="intg-fanout-q2")["QueueUrl"]
q1_arn = sqs.get_queue_attributes(QueueUrl=q1_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
q2_arn = sqs.get_queue_attributes(QueueUrl=q2_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ for _q_url, _q_arn in ((q1_url, q1_arn), (q2_url, q2_arn)):
+ sqs.set_queue_attributes(
+ QueueUrl=_q_url,
+ Attributes={"Policy": json.dumps(sqs_policy_allow_sns(_q_arn, topic_arn))})
sub1 = sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q1_arn)
sub2 = sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q2_arn)
@@ -926,6 +953,9 @@ def test_sns_fifo_cbd_dedup_subscriber_gets_one_message(sns, sqs):
q_arn = sqs.get_queue_attributes(
QueueUrl=q_url, AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=q_url,
+ Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)
@@ -1369,6 +1399,9 @@ def test_sns_fifo_e2e_fanout_with_dedup(sns, sqs):
q_arn = sqs.get_queue_attributes(
QueueUrl=q_url, AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=q_url,
+ Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index b7ed657b..9b991439 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -12,7 +12,7 @@ import boto3
import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
-from conftest import ENDPOINT, LoopProbe, concurrent_burst
+from conftest import ENDPOINT, LoopProbe, concurrent_burst, sqs_policy_allow_sns
def _make_zip(code: str) -> bytes:
@@ -3547,6 +3547,9 @@ def test_sfn_integration_sns_publish_structured_payload(sfn, sns, sqs):
QueueUrl=q_url,
AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(
+ QueueUrl=q_url,
+ Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)
definition = json.dumps(