Skip to content

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

fix(eventbridge): match event patterns the way AWS does (#1404)

t-rech919302339e9c
diff --git a/README.md b/README.md
index 7106a336..00dc31c3 100644
--- a/README.md
+++ b/README.md
@@ -415,7 +415,7 @@ subnet = ec2.create_subnet(
| Service | Operations | Notes |
|---------|-----------|-------|
| **SSM Parameter Store** | PutParameter, GetParameter, GetParameters, GetParametersByPath, DeleteParameter, DeleteParameters, DescribeParameters, GetParameterHistory, LabelParameterVersion, AddTagsToResource, RemoveTagsFromResource, ListTagsForResource | Supports String, SecureString, StringList |
-| **EventBridge** | CreateEventBus, UpdateEventBus, DeleteEventBus, ListEventBuses, DescribeEventBus, PutRule, DeleteRule, ListRules, DescribeRule, EnableRule, DisableRule, PutTargets, RemoveTargets, ListTargetsByRule, ListRuleNamesByTarget, PutEvents, TestEventPattern, TagResource, UntagResource, ListTagsForResource, CreateArchive, DeleteArchive, DescribeArchive, UpdateArchive, ListArchives, PutPermission, RemovePermission, CreateConnection, DescribeConnection, DeleteConnection, UpdateConnection, DeauthorizeConnection, ListConnections, CreateApiDestination, DescribeApiDestination, DeleteApiDestination, UpdateApiDestination, ListApiDestinations, StartReplay, DescribeReplay, ListReplays, CancelReplay, CreateEndpoint, DeleteEndpoint, DescribeEndpoint, ListEndpoints, UpdateEndpoint, ActivateEventSource, DeactivateEventSource, DescribeEventSource, CreatePartnerEventSource, DeletePartnerEventSource, DescribePartnerEventSource, ListPartnerEventSources, ListPartnerEventSourceAccounts, ListEventSources, PutPartnerEvents | Lambda target dispatch on PutEvents; S3 EventBridge notifications; archives capture matching events and `StartReplay` re-dispatches them to the destination bus in a background thread; API destination targets are **invoked over HTTP** on PutEvents — connection auth (Basic, API Key, OAuth client-credentials with token caching and 401/407 refresh), connection/target header/query/body parameter merging with connection precedence, `*` path parameters, and the AWS default headers (`User-Agent: Amazon/EventBridge/ApiDestinations`, default `Content-Type: application/json; charset=utf-8`), which connection and target parameters cannot override; redirects are not followed (a `3xx` is a non-retryable delivery failure), only `http(s)` invocation and OAuth authorization endpoints are accepted, `HttpMethod` and `AuthorizationType` are validated against their enums, and a connection that is not `AUTHORIZED` is not invoked (`DeauthorizeConnection` clears its stored credentials) — the 24h retry pipeline, rate limiting, and DLQs are not modeled; SaaS/partner APIs are otherwise control-plane stubs |
+| **EventBridge** | CreateEventBus, UpdateEventBus, DeleteEventBus, ListEventBuses, DescribeEventBus, PutRule, DeleteRule, ListRules, DescribeRule, EnableRule, DisableRule, PutTargets, RemoveTargets, ListTargetsByRule, ListRuleNamesByTarget, PutEvents, TestEventPattern, TagResource, UntagResource, ListTagsForResource, CreateArchive, DeleteArchive, DescribeArchive, UpdateArchive, ListArchives, PutPermission, RemovePermission, CreateConnection, DescribeConnection, DeleteConnection, UpdateConnection, DeauthorizeConnection, ListConnections, CreateApiDestination, DescribeApiDestination, DeleteApiDestination, UpdateApiDestination, ListApiDestinations, StartReplay, DescribeReplay, ListReplays, CancelReplay, CreateEndpoint, DeleteEndpoint, DescribeEndpoint, ListEndpoints, UpdateEndpoint, ActivateEventSource, DeactivateEventSource, DescribeEventSource, CreatePartnerEventSource, DeletePartnerEventSource, DescribePartnerEventSource, ListPartnerEventSources, ListPartnerEventSourceAccounts, ListEventSources, PutPartnerEvents | Lambda target dispatch on PutEvents; S3 EventBridge notifications; archives capture matching events and `StartReplay` re-dispatches them to the destination bus in a background thread; API destination targets are **invoked over HTTP** on PutEvents — connection auth (Basic, API Key, OAuth client-credentials with token caching and 401/407 refresh), connection/target header/query/body parameter merging with connection precedence, `*` path parameters, and the AWS default headers (`User-Agent: Amazon/EventBridge/ApiDestinations`, default `Content-Type: application/json; charset=utf-8`), which connection and target parameters cannot override; redirects are not followed (a `3xx` is a non-retryable delivery failure), only `http(s)` invocation and OAuth authorization endpoints are accepted, `HttpMethod` and `AuthorizationType` are validated against their enums, and a connection that is not `AUTHORIZED` is not invoked (`DeauthorizeConnection` clears its stored credentials) — the 24h retry pipeline, rate limiting, and DLQs are not modeled; SaaS/partner APIs are otherwise control-plane stubs. Event patterns are **validated** — `PutRule`, `TestEventPattern`, `CreateArchive` and `UpdateArchive` reject a malformed pattern with `InvalidEventPatternException` carrying AWS's own reason text — and evaluate `prefix`/`suffix` (plain or case-insensitive via a nested `equals-ignore-case`), `wildcard` (AWS semantics — only `*` is special, `\` escapes — with catastrophic backtracking ruled out), `equals-ignore-case` (AWS's per-character case alternation), `exactly`, `cidr` (IPv4/IPv6, host bits floored, `/32` and `/128` refused as AWS refuses them), `numeric` (as the grammar it is: one comparison or a lower-then-upper bound), `exists` (leaf nodes only, so an object or an empty array does not exist), `anything-but` (a literal, a list, or a nested `prefix`/`suffix`/`wildcard`/`equals-ignore-case`, singly or as a list), and `$or` at any field position — expanded into flat alternatives at rule creation, so AWS's per-leaf last-write-wins collision rule and its 1000-combination cap both hold. All ten envelope fields are filterable, an unmodelled key is a path the event lacks rather than an error, `resources` is an intersection, array values are matched per element (with AWS's array-consistency rule), and values compare as JSON so a string never equals a number. An operand or key the matcher cannot evaluate never matches, rather than raising or matching everything. Not modeled: the 4096-character pattern limit, the wildcard-complexity refusal, and the 256-leaf rule-size cap |
| **Kinesis** | CreateStream, DeleteStream, DescribeStream, DescribeStreamSummary, ListStreams, ListShards, PutRecord, PutRecords, GetShardIterator, GetRecords, IncreaseStreamRetentionPeriod, DecreaseStreamRetentionPeriod, MergeShards, SplitShard, UpdateShardCount, StartStreamEncryption, StopStreamEncryption, EnableEnhancedMonitoring, DisableEnhancedMonitoring, RegisterStreamConsumer, DeregisterStreamConsumer, ListStreamConsumers, DescribeStreamConsumer, AddTagsToStream, RemoveTagsFromStream, ListTagsForStream | Partition key → shard routing; AWS limits enforced (1 MB/record, 500 records/batch, 5 MB payload, 256-char partition key) |
| **CloudWatch Metrics** | PutMetricData, GetMetricStatistics, GetMetricData, ListMetrics, PutMetricAlarm, PutCompositeAlarm, DescribeAlarms, DescribeAlarmsForMetric, DescribeAlarmHistory, DeleteAlarms, SetAlarmState, EnableAlarmActions, DisableAlarmActions, TagResource, UntagResource, ListTagsForResource, PutDashboard, GetDashboard, DeleteDashboards, ListDashboards | CBOR and JSON protocol |
| **SES** | SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail, VerifyEmailIdentity, VerifyEmailAddress, VerifyDomainIdentity, VerifyDomainDkim, ListIdentities, ListVerifiedEmailAddresses, GetIdentityVerificationAttributes, GetIdentityDkimAttributes, DeleteIdentity, GetSendQuota, GetSendStatistics, SetIdentityNotificationTopic, SetIdentityFeedbackForwardingEnabled, CreateConfigurationSet, DeleteConfigurationSet, DescribeConfigurationSet, ListConfigurationSets, CreateTemplate, GetTemplate, UpdateTemplate, DeleteTemplate, ListTemplates | Emails stored in-memory, not sent |
diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.py
index 99125424..5c0c9447 100644
--- a/ministack/services/eventbridge.py
+++ b/ministack/services/eventbridge.py
@@ -22,10 +22,12 @@ Supports: CreateEventBus, UpdateEventBus, DeleteEventBus, ListEventBuses, Descri
import calendar
import copy
-import fnmatch
+import functools
import hashlib
+import ipaddress
import json
import logging
+import operator
import os
import re
import threading
@@ -515,15 +517,9 @@ def _put_rule(data):
)
event_pattern = data.get("EventPattern", "")
- if event_pattern and isinstance(event_pattern, str):
- try:
- json.loads(event_pattern)
- except json.JSONDecodeError:
- return error_response_json(
- "InvalidEventPatternException",
- "Event pattern is not valid JSON",
- 400,
- )
+ pattern_error = _event_pattern_error(event_pattern)
+ if pattern_error:
+ return _invalid_event_pattern(pattern_error)
arn = _rule_arn(name, bus)
key = _rule_key(name, bus)
@@ -760,23 +756,88 @@ def _list_rule_names_by_target(data):
return json_response(resp)
+
+def _event_pattern_error(pattern_str):
+ """The reason AWS would refuse this event pattern, or ``None`` if it accepts
+ it. Shared by every API that takes one, so they cannot disagree."""
+ if not pattern_str:
+ return None
+ if not isinstance(pattern_str, str):
+ return "Invalid JSON"
+ return _parse_pattern_text(pattern_str)[1]
+
+
+def _invalid_event_pattern(reason: str):
+ return error_response_json(
+ "InvalidEventPatternException", f"Event pattern is not valid. Reason: {reason}", 400)
+
+
[email protected]_cache(maxsize=1024)
+def _iso_time(epoch_seconds) -> str:
+ """The ISO-8601 rendering of an epoch second, or ``""`` when the number is
+ not a time at all. Memoized: every event in the same second renders alike.
+
+ The guard is not decoration — a ``time`` no platform clock can represent
+ (``1e30``) makes ``fromtimestamp`` raise, and this runs while building the
+ view every pattern is matched against, so it would surface as a 500 out of
+ the enclosing PutEvents."""
+ try:
+ return datetime.fromtimestamp(epoch_seconds, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+ except (OverflowError, OSError, ValueError):
+ return ""
+
+
+def _event_time_string(event) -> str:
+ """The event's ``time`` in the form the envelope carries it. ``Time`` is
+ stored as int epoch seconds while a pattern filters on the ISO-8601 string
+ the target receives, so matcher and delivery share this one rendering."""
+ raw = event.get("Time", "")
+ if isinstance(raw, (int, float)) and not isinstance(raw, bool):
+ return _iso_time(raw)
+ return raw if isinstance(raw, str) else ""
+
+
+# The envelope names ``_event_from_test_payload`` models. Anything else a
+# caller puts at the top level of a ``TestEventPattern`` event is carried
+# through as an extra path rather than dropped: AWS compiles a pattern to a set
+# of paths and has no envelope allow-list, so a pattern naming an unmodelled key
+# must be able to match an event that actually carries it. ``PutEvents`` cannot
+# produce one — its entries are a fixed shape — so this only ever fires here.
+_TEST_PAYLOAD_MODELLED_KEYS = frozenset({
+ "detail", "Detail", "source", "Source", "detail-type", "DetailType",
+ "account", "Account", "region", "Region", "resources", "Resources",
+ "id", "EventId", "time", "Time", "version", "Version",
+ "replay-name", "ReplayName",
+})
+
+
def _event_from_test_payload(event_obj: dict) -> dict:
"""Map CloudWatch Events-shaped JSON to internal fields used by _matches_pattern."""
detail = event_obj.get("detail", event_obj.get("Detail", {}))
- if isinstance(detail, dict):
+ if not isinstance(detail, str):
+ # Re-encoded, not ``str()``: repr would render a null as ``None`` and a
+ # list in Python syntax, and a pattern can ask about either.
detail = json.dumps(detail)
- elif detail is None:
- detail = "{}"
- else:
- detail = str(detail)
- return {
+ synthetic = {
"Source": event_obj.get("source", event_obj.get("Source", "")),
"DetailType": event_obj.get("detail-type", event_obj.get("DetailType", "")),
"Detail": detail,
"Account": event_obj.get("account", event_obj.get("Account", get_account_id())),
"Region": event_obj.get("region", event_obj.get("Region", get_region())),
"Resources": event_obj.get("resources", event_obj.get("Resources", [])),
+ "EventId": event_obj.get("id", event_obj.get("EventId", "")),
+ "Time": event_obj.get("time", event_obj.get("Time", "")),
+ "Version": event_obj.get("version", event_obj.get("Version", "0")),
}
+ # Absent rather than empty on a normal event; see ``_pattern_event_view``.
+ replay_name = event_obj.get("replay-name", event_obj.get("ReplayName"))
+ if replay_name is not None:
+ synthetic["ReplayName"] = replay_name
+ extra = {key: value for key, value in event_obj.items()
+ if key not in _TEST_PAYLOAD_MODELLED_KEYS}
+ if extra:
+ synthetic["_ExtraEnvelope"] = extra
+ return synthetic
def _test_event_pattern(data):
@@ -793,6 +854,10 @@ def _test_event_pattern(data):
if not isinstance(event_obj, dict):
return error_response_json("InvalidEventPatternException", "Event must be a JSON object", 400)
+ pattern_error = _event_pattern_error(pattern_str)
+ if pattern_error:
+ return _invalid_event_pattern(pattern_error)
+
synthetic = _event_from_test_payload(event_obj)
matched = _matches_pattern(pattern_str, synthetic)
return json_response({"Result": bool(matched)})
@@ -956,28 +1021,34 @@ def _put_events(data):
results.append({"EventId": event_id})
logger.debug("EventBridge event: %s / %s", entry.get('Source'), entry.get('DetailType'))
- _dispatch_event(event_record)
- _archive_event(event_record)
+ # One view for both walks; rebuilding it re-parses ``Detail``.
+ view = _pattern_event_view(event_record)
+ _dispatch_event(event_record, view)
+ _archive_event(event_record, view)
return json_response({"FailedEntryCount": failed, "Entries": results})
-def _archive_event(event):
+def _archive_event(event, view=None):
bus_name = event.get("EventBusName", "default")
bus_arn = f"arn:aws:events:{get_region()}:{get_account_id()}:event-bus/{bus_name}"
for archive in _archives.values():
if archive.get("EventSourceArn") != bus_arn:
continue
pattern = archive.get("EventPattern", "")
- if pattern and not _matches_pattern(pattern, event):
- continue
+ if pattern:
+ view = view or _pattern_event_view(event)
+ if not _matches_pattern_view(
+ pattern, view, f"archive {archive.get('ArchiveName', '?')}"):
+ continue
archive.setdefault("Events", []).append(event)
archive["EventCount"] = archive.get("EventCount", 0) + 1
-def _dispatch_event(event):
+def _dispatch_event(event, view=None):
bus_name = event.get("EventBusName", "default")
event_path = set(event.get("_DispatchPath") or [])
+ view = view or _pattern_event_view(event)
for key, rule in _rules.items():
if rule.get("EventBusName", "default") != bus_name:
@@ -990,201 +1061,1195 @@ def _dispatch_event(event):
if not rule.get("EventPattern"):
continue
- if _matches_pattern(rule["EventPattern"], event):
+ if _matches_pattern_view(rule["EventPattern"], view, f"rule {key}"):
rule_targets = _targets.get(key, [])
for target in rule_targets:
- _invoke_target(target, event, rule)
+ _invoke_target(target, event, rule, view)
+
+
+def _reject_json_constant(literal: str):
+ """``json.loads(parse_constant=...)`` hook. Raising here is what turns
+ ``NaN``/``Infinity``/``-Infinity`` — extensions Python's decoder allows and
+ JSON does not define — back into the ``Invalid JSON`` refusal AWS gives."""
+ raise ValueError(f"Invalid JSON literal: {literal}")
+
+
+def _parse_pattern_text(pattern_str: str):
+ """``(alternatives, None)`` for a pattern AWS accepts, ``(None, reason)`` for
+ one it refuses. One parse answers both the validator's question and the
+ matcher's, so the two cannot come to disagree on what counts as a refusal.
+ See ``_reject_json_constant`` for the one place this is stricter than
+ Python's decoder.
+
+ ``ValueError``, not ``JSONDecodeError``: an integer literal of more digits
+ than Python will convert raises the plain parent class. A ``RecursionError``
+ is the same refusal, and it happens before any depth bound of ours applies.
+
+ ``parse_constant`` refuses ``NaN``/``Infinity``/``-Infinity``, which Python's
+ decoder accepts by default and JSON does not define. AWS parses a pattern
+ with Jackson, which rejects them unless it is asked not to, so accepting one
+ here would take a pattern that is a `400` in production and leave it matching
+ nothing locally — the silence this whole entry exists to remove."""
+ if isinstance(pattern_str, str) and not pattern_str.strip():
+ return None, "Filter is not an object"
+ try:
+ pattern = json.loads(pattern_str, parse_constant=_reject_json_constant)
+ except (ValueError, TypeError, RecursionError):
+ return None, "Invalid JSON"
+ try:
+ return _compile_pattern(pattern), None
+ except _InvalidPattern as exc:
+ return None, str(exc)
+ except RecursionError:
+ return None, "Event pattern is nested too deeply"
+
+
[email protected]_cache(maxsize=1024)
+def _compiled_pattern(pattern_str: str):
+ """The alternatives a pattern string compiles to, or ``None`` when AWS would
+ refuse it. Cached because rule patterns are stable while events are not, and
+ this runs per rule per event on the dispatch path. The returned lists are
+ shared with every later caller: read them, never mutate them.
+
+ A refusal is cached rather than raised. A pattern only reaches here from a
+ rule restored from persisted state, which is loaded verbatim and never
+ revalidated — and one AWS would have refused matches nothing. So does a
+ pattern whose parse exhausted the stack."""
+ return _parse_pattern_text(pattern_str)[0]
def _matches_pattern(pattern_str, event):
+ """Whether ``event`` matches ``pattern_str`` — the single-shot form; dispatch
+ builds the view once and calls ``_matches_pattern_view`` directly."""
+ return _matches_pattern_view(pattern_str, _pattern_event_view(event))
+
+
+def _matches_pattern_view(pattern_str, view, owner="rule"):
+ """Whether ``view`` matches ``pattern_str``, the pattern as the JSON text the
+ API takes it in and the rule and archive stores keep across a restart.
+
+ A stored pattern that is not text belongs to a record this build's validation
+ never saw; it matches nothing, and is logged rather than dropped in silence.
+ ``owner`` names the record in that log line, so the operator can go and fix
+ the one that is skipping. Handing the pattern to the memoized compiler would
+ be worse than skipping it: ``lru_cache`` answers an unhashable key with
+ ``TypeError``, and dispatch runs inside ``PutEvents``, so that is a 500 on the
+ whole batch instead of one skipped rule."""
+ if not isinstance(pattern_str, str):
+ logger.warning("EventBridge: %s has a pattern that is not JSON text (%s); skipped",
+ owner, type(pattern_str).__name__)
+ return False
+ alternatives = _compiled_pattern(pattern_str)
+ if alternatives is None:
+ return False
+ return any(_matches_alternative(view, alternative) for alternative in alternatives)
+
+
+def _matches_alternative(view, alternative) -> bool:
+ """One compiled alternative against one event, envelope keys before ``detail``,
+ so a rule that fails on ``source`` never decodes the payload. The split is
+ exact because a pattern's top-level keys are independent: ``_matches_detail``
+ ANDs them against the same tree, so asking in two batches asks the same
+ question."""
+ if "detail" not in alternative:
+ return _matches_detail(view.envelope(), alternative)
+ if len(alternative) == 1:
+ return _matches_detail(view.event_with_detail(), alternative)
+ envelope = {key: value for key, value in alternative.items() if key != "detail"}
+ return (_matches_detail(view.envelope(), envelope) and
+ _matches_detail(view.event_with_detail(), {"detail": alternative["detail"]}))
+
+
+def _decoded_detail(raw):
+ """An event's ``Detail`` as a JSON value. One that is not JSON is the leaf it
+ is: an empty object would answer a question about a field the event does not
+ have. Shared by the matcher's view and the delivered envelope, so the two
+ agree on one reading."""
+ if isinstance(raw, str):
+ try:
+ return json.loads(raw)
+ except (ValueError, TypeError, RecursionError):
+ return raw
+ return raw
+
+
+class _EventView:
+ """The event a pattern is matched against and a target is delivered, with
+ ``detail`` decoded only once, and only for the alternatives that ask about it.
+
+ One object serves both because they are the same tree: a rule must not match
+ on a field whose delivered value differs, and the surest way to guarantee
+ that is to have nothing to keep in step.
+
+ The deferral costs nothing because ``_matches_detail`` reads a key only when
+ the pattern names it — and AWS prunes the same way: Event Ruler skips a field
+ no rule uses rather than parsing into it, so a field nothing asks about is
+ absent from the tree a pattern sees, never present as a null.
+
+ Not a ``dict`` subclass holding a placeholder until first read: CPython reads
+ a subclass's own storage for ``dict(view)``, ``{**view}`` and ``items()``, so
+ the placeholder would reach consumers as a ``detail`` of ``null`` — a leaf a
+ pattern can match on."""
+
+ __slots__ = ("_envelope", "_raw_detail", "_with_detail")
+
+ def __init__(self, envelope, raw_detail):
+ self._envelope = envelope
+ self._raw_detail = raw_detail
+ self._with_detail = None
+
+ def envelope(self) -> dict:
+ """The event without ``detail`` — what a pattern naming no ``detail`` is
+ matched against, and what ``<aws.events.event>`` renders."""
+ return self._envelope
+
+ def event_with_detail(self) -> dict:
+ """The whole event: the tree a target is delivered, and the one an
+ alternative naming ``detail`` is matched against."""
+ if self._with_detail is None:
+ self._with_detail = dict(self._envelope, detail=_decoded_detail(self._raw_detail))
+ return self._with_detail
+
+
+def _pattern_event_view(event):
+ """The event as a pattern sees it, which is exactly the envelope a target is
+ delivered — one builder, because two hand-kept copies drift.
+
+ A pattern is matched against one whole tree rather than field by field
+ because that is what AWS does — it compiles a pattern to a set of *paths* and
+ has no notion of which top-level names are legal. Two consequences fall out
+ of that and out of nothing else: an unrecognized top-level key is simply a
+ path the event does not have, so ``{"nonesuch": ["x"]}`` matches nothing while
+ ``{"nonesuch": [{"exists": false}]}`` matches *everything*; and an envelope
+ field may be written as an object path (``{"source": {"x": ["y"]}}`` is the
+ path ``source.x``) without that being an error."""
+ fields = {
+ "version": str(event.get("Version", "0")),
+ "id": event.get("EventId", ""),
+ "source": event.get("Source", ""),
+ "account": event.get("Account", get_account_id()),
+ "time": _event_time_string(event),
+ "region": event.get("Region", get_region()),
+ "resources": event.get("Resources", []),
+ "detail-type": event.get("DetailType", ""),
+ }
+ if event.get("ReplayName") is not None:
+ # Present only on a replayed event, which is what makes AWS's own
+ # ``{"replay-name": [{"exists": false}]}`` mean "live traffic only".
+ fields["replay-name"] = event["ReplayName"]
+ extra = event.get("_ExtraEnvelope")
+ if extra:
+ # Unmodelled top-level keys, which only ``TestEventPattern`` can supply.
+ # Written under the modelled names so a caller cannot shadow one.
+ fields = dict(extra, **fields)
+ return _EventView(fields, event.get("Detail", "{}"))
+
+# Field names AWS reserves inside a ``$or`` branch: a ``$or`` holding any of them
+# is not the OR operator. Wider than SNS's equivalent — it also reserves the bare
+# comparison symbols and the names of operators AWS has not shipped yet, so
+# adding one later cannot change what an existing pattern means.
+_OR_RESERVED_MEMBER_KEYS = frozenset({
+ "anything-but", "prefix", "suffix", "equals-ignore-case", "numeric",
+ "exists", "cidr", "wildcard", "exactly", "=", "<", "<=", ">", ">=",
+ "regex", "not-wildcard", "not-equals-ignore-case", "date-after",
+ "date-on-or-after", "date-before", "date-on-or-before", "in-date-range",
+ "ip-address-in-range", "ip-address-not-in-range",
+})
+
+
+class _InvalidPattern(Exception):
+ """An event pattern AWS refuses at rule creation.
+
+ The message is the one EventBridge reports, which is the underlying
+ Event Ruler text verbatim — a real service response reads
+ ``Event pattern is not valid. Reason: exists match pattern must be either
+ true or false.`` — so the strings here are deliberately AWS's wording
+ rather than our own."""
+
+
+class _PatternTooComplex(_InvalidPattern):
+ """A limit was reached rather than the pattern being malformed: the ``$or``
+ combination cap, or the nesting guard. Kept distinct because neither is
+ retried against the fallback compiler — re-reading ``$or`` as a field name
+ cannot answer a product over the ``$or`` arrays, and for a depth failure it
+ re-descends the same hundred levels the guard exists to bound."""
+
+
+# AWS's cap on the sub-patterns a ``$or`` may expand to. Its own wording is
+# "over 1000 rule combinations".
+_MAX_OR_COMBINATIONS = 1000
+# A guard on pattern nesting, not an AWS rule — AWS documents no depth limit.
+# Compilation and matching both recurse per level, on a pooled worker thread
+# whose remaining stack is nothing like the interpreter's nominal limit, and a
+# RecursionError there does not stay inside its own request. Set above any real
+# pattern and below where the handler's own JSON parse gives out.
+_MAX_PATTERN_DEPTH = 100
+
+
+# ---------------------------------------------------------------------------
+# Event pattern compilation — $or expansion into flat alternatives
+# ---------------------------------------------------------------------------
+
+
+def _compile_pattern(pattern):
+ """Expand an event pattern into the list of flat alternatives AWS compiles
+ it to, raising ``_InvalidPattern`` for anything it would reject.
+
+ ``$or`` is not evaluated at match time on AWS — it is expanded here, into
+ one alternative per branch, and the rule matches if *any* alternative does.
+ That is not merely a different route to the same answer. Because each branch
+ is built by writing leaves into the alternatives accumulated so far, a leaf
+ constrained both inside and outside a ``$or`` keeps only the LAST value
+ written, in document order. So ``{"a":["1"],"$or":[{"a":["2"]},{"b":["3"]}]}``
+ matches ``{"a":"2"}`` and does not match ``{"a":"1"}`` — and writing the two
+ keys the other way round reverses both answers. A recursive evaluator
+ answers order-independently and gets those cases wrong.
+
+ A ``$or`` that is not the operator falls back to being read as an ordinary
+ field name, which is what EventBridge does: it compiles with its ``$or``-aware
+ compiler and on failure retries with its pre-``$or`` one."""
+ # Outside the retry deliberately: AWS counts the product over the ``$or``
+ # arrays the pattern text holds, so a ``$or`` that turns out not to be the
+ # operator still counts toward the cap.
+ product = _or_combination_product(pattern)
+ if product > _MAX_OR_COMBINATIONS:
+ raise _PatternTooComplex(
+ f"Event pattern contains more than {_MAX_OR_COMBINATIONS} rule combinations")
try:
- if isinstance(pattern_str, str):
- pattern = json.loads(pattern_str)
+ return _compile_alternatives(pattern, expand_or=True)
+ except _PatternTooComplex:
+ raise
+ except _InvalidPattern:
+ return _compile_alternatives(pattern, expand_or=False)
+
+
+def _or_combination_product(node, depth: int = 0):
+ """AWS's documented rule-combination count: the product of the lengths of
+ every ``$or`` array. It over-counts what the expansion actually produces for
+ a nested ``$or``, deliberately — counting only the alternatives would accept
+ a pattern AWS refuses, so both are checked."""
+ if not isinstance(node, dict) or depth > _MAX_PATTERN_DEPTH:
+ return 1
+ product = 1
+ for key, value in node.items():
+ if key == "$or" and isinstance(value, list):
+ product *= max(len(value), 1)
+ for member in value:
+ product *= _or_combination_product(member, depth + 1)
+ elif isinstance(value, dict):
+ product *= _or_combination_product(value, depth + 1)
+ if product > _MAX_OR_COMBINATIONS:
+ return product
+ return product
+
+
+def _compile_alternatives(pattern, expand_or: bool):
+ alternatives = []
+ _compile_object(alternatives, [], pattern, expand_or, inside_or=False, depth=0)
+ return alternatives or [{}]
+
+
+def _copy_alternative(alternative):
+ """A copy deep enough to fork on. The value lists are never mutated — a
+ leaf write replaces one wholesale — so only the object spine is copied."""
+ return {key: _copy_alternative(value) if isinstance(value, dict) else value
+ for key, value in alternative.items()}
+
+
+def _compile_object(alternatives, path, obj, expand_or, inside_or, depth):
+ if depth > _MAX_PATTERN_DEPTH:
+ raise _PatternTooComplex("Event pattern is nested too deeply")
+ if not isinstance(obj, dict):
+ raise _InvalidPattern("Filter is not an object")
+ if not obj:
+ raise _InvalidPattern("Empty objects are not allowed")
+ # Document order decides which of two writes to the same leaf survives, so
+ # the keys are walked in the order the JSON carried them and never sorted.
+ for key, value in obj.items():
+ if key == "$or" and expand_or:
+ _compile_or(alternatives, path, value, depth)
+ continue
+ if inside_or and key in _OR_RESERVED_MEMBER_KEYS:
+ raise _InvalidPattern(
+ f"{key} is Ruler reserved fieldName which cannot be used inside $or.")
+ if isinstance(value, dict):
+ _compile_object(alternatives, [*path, key], value, expand_or, inside_or, depth + 1)
+ elif isinstance(value, list):
+ _validate_value_list(value)
+ _write_leaf(alternatives, [*path, key], value)
else:
- pattern = pattern_str
- except (json.JSONDecodeError, TypeError):
- return False
+ raise _InvalidPattern(f'"{key}" must be an object or an array')
+
+
+def _compile_or(alternatives, path, members, depth):
+ prefix = [_copy_alternative(a) for a in alternatives]
+ alternatives.clear()
+ if not isinstance(members, list):
+ raise _InvalidPattern("It must be an Array followed with $or.")
+ for member in members:
+ if not isinstance(member, dict):
+ raise _InvalidPattern("Only JSON object is allowed in array of $or relationship.")
+ forked = [_copy_alternative(a) for a in prefix] or [{}]
+ _compile_object(forked, path, member, True, True, depth + 1)
+ alternatives.extend(forked)
+ if len(alternatives) > _MAX_OR_COMBINATIONS:
+ raise _PatternTooComplex(
+ f"Event pattern contains more than {_MAX_OR_COMBINATIONS} rule combinations")
+ if len(members) < 2:
+ raise _InvalidPattern("There must have at least 2 Objects in $or relationship.")
+
+
+# Marks an alternative no event can satisfy. AWS keys its sub-rules by the full
+# dotted path, so a path constrained both as a leaf and as an object keeps BOTH
+# constraints and matches nothing. Alternatives here are trees, which cannot
+# hold the two at once, so the collision is recorded rather than one side
+# dropped; an ``object()`` key cannot collide with a pattern key.
+_UNSATISFIABLE = object()
+
+
+def _write_leaf(alternatives, path, values):
+ """Record one leaf constraint in every alternative built so far. A leaf
+ already constrained at this path is overwritten, which is where
+ last-write-wins comes from — but only when both writes are leaves."""
+ if not alternatives:
+ alternatives.append({})
+ for alternative in alternatives:
+ node = alternative
+ for part in path[:-1]:
+ child = node.get(part)
+ if child is None:
+ child = {}
+ node[part] = child
+ elif not isinstance(child, dict):
+ # An ancestor is already a leaf; see ``_UNSATISFIABLE``.
+ alternative[_UNSATISFIABLE] = True
+ break
+ node = child
+ else:
+ if isinstance(node.get(path[-1]), dict):
+ alternative[_UNSATISFIABLE] = True
+ else:
+ node[path[-1]] = values
- if "source" in pattern:
- if not _matches_field(event.get("Source", ""), pattern["source"]):
- return False
- if "detail-type" in pattern:
- if not _matches_field(event.get("DetailType", ""), pattern["detail-type"]):
- return False
+# The operators ``anything-but`` may negate, and the ones a ``prefix``/``suffix``
+# operand may itself be written as.
+_ANYTHING_BUT_NESTABLE = frozenset({"prefix", "suffix", "equals-ignore-case", "wildcard"})
+_AFFIX_NESTABLE = frozenset({"equals-ignore-case"})
+# The numeric comparison spelled out, for the operand error messages.
+_NUMERIC_OP_NAMES = {"=": "equals", ">": ">", ">=": ">=", "<": "<", "<=": "<="}
+# A range's lower bound may be followed by an upper bound; every other operator
+# terminates the expression.
+_NUMERIC_RANGE_OPENERS = frozenset({">", ">="})
+_NUMERIC_RANGE_CLOSERS = frozenset({"<", "<="})
+
+
+def _require_type(operand, kind, message: str):
+ """The whole of what several operators ask of their operand: that it is one
+ JSON type, refused with AWS's own wording for that operator when it is not."""
+ if not isinstance(operand, kind):
+ raise _InvalidPattern(message)
+
+
+# ---------------------------------------------------------------------------
+# Event pattern validation — AWS's operand grammar, and its wording
+# ---------------------------------------------------------------------------
+
- if "detail" in pattern:
+def _validate_value_list(values: list):
+ """Validate one field's list of alternatives. AWS rejects the whole pattern
+ for any of these, so this raises rather than returning a verdict."""
+ if not values:
+ raise _InvalidPattern("Empty arrays are not allowed")
+ for item in values:
+ if isinstance(item, dict):
+ _validate_match_expression(item)
+ elif isinstance(item, list):
+ raise _InvalidPattern("Match value must be String, number, true, false, or null")
+
+
+def _validate_match_expression(expression: dict):
+ if not expression:
+ raise _InvalidPattern("Match expression name not found")
+ operator_name = next(iter(expression))
+ if operator_name not in _MATCH_OPERATORS:
+ raise _InvalidPattern(f"Unrecognized match type {operator_name}")
+ # Operand before arity: AWS's parser dispatches on the first key and consumes
+ # its operand before it sees a second, so a two-key expression whose first
+ # operand is also wrong reports the operand, not the arity.
+ _OPERAND_VALIDATORS[operator_name](expression[operator_name])
+ if len(expression) > 1:
+ # These two reach a different guard on AWS, which reports the arity of
+ # the operand it was already reading.
+ if operator_name in ("numeric", "anything-but"):
+ raise _InvalidPattern("Too many elements in numeric expression")
+ raise _InvalidPattern("Only one key allowed in match expression")
+
+
+def _validate_affix(operator_name: str, operand):
+ """``prefix``/``suffix`` take a string, or a nested ``equals-ignore-case``
+ for a case-insensitive affix.
+
+ An empty operand is accepted in both forms and is not the do-nothing rule it
+ looks like: AWS matches an affix against the *quoted* form of the value, so
+ an empty ``prefix`` compiles to the opening quote alone — which every JSON
+ string carries and no number, boolean or null does. It reads "this field has
+ a string value", and ``_matches_affix`` answers it that way.
+ ``Null prefix/suffix not allowed`` is AWS's rule for ``anything-but``'s
+ nested affix alone, so refusing an empty operand here would reject a pattern
+ real AWS compiles.
+
+ The type complaint names the one operator it read where the nested form says
+ ``prefix/suffix``; both are AWS's own wording."""
+ if isinstance(operand, dict):
+ if not operand:
+ raise _InvalidPattern(f"{operator_name.capitalize()} expression name not found")
+ inner = next(iter(operand))
+ if len(operand) > 1:
+ raise _InvalidPattern("Only one key allowed in match expression")
+ if inner not in _AFFIX_NESTABLE:
+ raise _InvalidPattern(f"Unsupported {operator_name} pattern: {inner}")
+ _require_type(operand[inner], str, "equals-ignore-case match pattern must be a string")
+ return
+ _require_type(operand, str, f"{operator_name} match pattern must be a string")
+
+
+def _wildcard_position(pattern: str, index: int) -> int:
+ """AWS reports a wildcard fault as a 1-based offset into the *quoted* form of
+ the operand, counted in UTF-8 bytes — so the opening quote is position 0 and
+ a multi-byte character before the fault shifts it by its encoded length.
+
+ ``errors="replace"`` is load-bearing: a lone surrogate out of a JSON escape
+ cannot be UTF-8 encoded at all, so encoding strictly raises — and this is
+ reached from the matcher as well as the validator. It is also what AWS
+ counts, its encoder substituting one ``?`` for an unpaired surrogate."""
+ return len(pattern[:index].encode("utf-8", errors="replace")) + 1
+
+
+def _validate_wildcard(operand):
+ _require_type(operand, str, "wildcard match pattern must be a string")
+ index = 0
+ while index < len(operand):
+ char = operand[index]
+ if char == "\\":
+ # A trailing backslash escapes the closing quote AWS appends, which
+ # is why it is an invalid escape rather than a dangling one.
+ if index + 1 >= len(operand) or operand[index + 1] not in ("*", "\\"):
+ raise _InvalidPattern(
+ f"Invalid escape character at pos {_wildcard_position(operand, index)}")
+ index += 2
+ continue
+ if char == "*" and index + 1 < len(operand) and operand[index + 1] == "*":
+ raise _InvalidPattern(
+ f"Consecutive wildcard characters at pos {_wildcard_position(operand, index)}")
+ index += 1
+
+
+# A pre-filter for ``ipaddress``, on both the operand and the value side: its
+# job is to reject what ``ipaddress`` accepts and AWS does not — a zone id, a
+# dotted IPv4-mapped IPv6 address, anything not plainly one family. The IPv6
+# form is one character class plus a separate colon test, not the two
+# overlapping classes the shape suggests: those go quadratic on a long
+# colon-only string, on the dispatch path ``_wildcard_to_regex`` protects.
+_CIDR_IPV4_RE = re.compile(r"[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\Z")
+_CIDR_IPV6_RE = re.compile(r"[0-9a-fA-F:]+\Z")
+# What AWS's integer parse of the mask accepts, which is not what Python's
+# ``int()`` accepts: no surrounding space, no underscore separators, no
+# non-ASCII digits, but a leading sign is fine (``/+24`` and ``/-0`` are real).
+_CIDR_MASK_RE = re.compile(r"[+-]?[0-9]+\Z")
+
+
+def _validate_cidr(operand):
+ # The wrong operator in this message is AWS's own copy-paste, kept so the
+ # text a caller sees is the text the service sends.
+ _require_type(operand, str, "prefix match pattern must be a string")
+ address, separator, mask = operand.partition("/")
+ # A trailing slash leaves no mask field at all for AWS's split, so it is the
+ # missing-slash complaint rather than a bad-integer one.
+ if not separator or "/" in mask or not mask:
+ raise _InvalidPattern("Malformed CIDR, one '/' required")
+ if not _CIDR_MASK_RE.match(mask):
+ raise _InvalidPattern("Malformed CIDR, mask bits must be an integer")
+ try:
+ bits = int(mask)
+ except ValueError:
+ raise _InvalidPattern("Malformed CIDR, mask bits must be an integer") from None
+ if not -2 ** 31 <= bits < 2 ** 31:
+ # Outside the width AWS's integer parse accepts, so it never reaches the
+ # mask-width check.
+ raise _InvalidPattern("Malformed CIDR, mask bits must be an integer")
+ if bits < 0:
+ raise _InvalidPattern("Malformed CIDR, mask bits must not be negative")
+ looks_v4 = _CIDR_IPV4_RE.match(address) is not None
+ looks_v6 = ":" in address and _CIDR_IPV6_RE.match(address) is not None
+ if not (looks_v4 or looks_v6):
+ raise _InvalidPattern(f"Nonstandard IP address: {address}")
+ try:
+ parsed = ipaddress.ip_address(_normalized_ipv4(address) if looks_v4 else address)
+ except ValueError:
+ raise _InvalidPattern(f"Invalid IP address: {address}") from None
+ if parsed.version == 4 and bits > 31:
+ raise _InvalidPattern("IPv4 mask bits must be < 32")
+ if parsed.version == 6 and bits > 127:
+ raise _InvalidPattern("IPv6 mask bits must be < 128")
+
+
+def _normalized_ipv4(address: str) -> str:
+ """A dotted quad with its octets read as decimal, which is how AWS reads
+ them: ``0177.0.0.1`` is ``177.0.0.1``, not octal. Python's parser refuses a
+ leading zero outright, so an operand AWS accepts would otherwise be refused."""
+ octets = []
+ for octet in address.split("."):
try:
- detail = json.loads(event.get("Detail", "{}")) if isinstance(event.get("Detail"), str) else event.get("Detail", {})
- except (json.JSONDecodeError, TypeError):
- detail = {}
- if not _matches_detail(detail, pattern["detail"]):
- return False
+ value = int(octet)
+ except ValueError:
+ # Only an octet of more digits than Python will convert; not an
+ # address either way.
+ return address
+ if not 0 <= value <= 255:
+ return address
+ octets.append(str(value))
+ return ".".join(octets)
+
+
+def _numeric_token(value) -> str:
+ """How AWS names an offending token in a numeric operand — the raw JSON
+ text, which is what its streaming parser has to hand."""
+ if value is True:
+ return "true"
+ if value is False:
+ return "false"
+ if value is None:
+ return "null"
+ if isinstance(value, list):
+ return "["
+ if isinstance(value, dict):
+ return "{"
+ return str(value)
+
+
+def _validate_numeric_threshold(operand_name: str, value):
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise _InvalidPattern(f"Value of {operand_name} must be numeric")
+ try:
+ as_double = float(value)
+ except (OverflowError, ValueError):
+ raise _InvalidPattern(f"Cannot compare number : {value}") from None
+ if as_double in (float("inf"), float("-inf")) or as_double != as_double:
+ raise _InvalidPattern(f"Cannot compare number : {value}")
+ if isinstance(value, int) and int(as_double) != value:
+ # AWS refuses a threshold the double conversion would silently move.
+ # Only checkable for an integer: a fractional literal was already
+ # rounded by the JSON parse, so its original text is gone.
+ raise _InvalidPattern(f"Cannot compare number : {value}")
+ return as_double
+
+
+def _validate_numeric(operand):
+ """``numeric`` is a small grammar, not a list of pairs: a single comparison,
+ or a lower bound followed by an upper bound. ``=``, ``<`` and ``<=``
+ terminate the expression, so a range has to be written lower bound first."""
+ _require_type(operand, list, "Value of numeric must be an array.")
+ if not operand:
+ raise _InvalidPattern("Invalid member in numeric match: ]")
+ first = operand[0]
+ _require_type(first, str, f"Invalid member in numeric match: {_numeric_token(first)}")
+ if first not in _NUMERIC_OP_NAMES:
+ raise _InvalidPattern(f"Unrecognized numeric range operator: {first}")
+ if len(operand) < 2:
+ raise _InvalidPattern(f"Value of {_NUMERIC_OP_NAMES[first]} must be numeric")
+ bottom = _validate_numeric_threshold(_NUMERIC_OP_NAMES[first], operand[1])
+ if len(operand) == 2:
+ return
+ if first not in _NUMERIC_RANGE_OPENERS:
+ raise _InvalidPattern("Too many elements in numeric expression")
+ if len(operand) > 4:
+ raise _InvalidPattern("Too many terms in numeric range expression")
+ second = operand[2]
+ _require_type(second, str, f"Bad value in numeric range: {_numeric_token(second)}")
+ if second not in _NUMERIC_RANGE_CLOSERS:
+ raise _InvalidPattern(f"Bad numeric range operator: {second}")
+ if len(operand) < 4:
+ raise _InvalidPattern(f"Value of {_NUMERIC_OP_NAMES[second]} must be numeric")
+ top = _validate_numeric_threshold(_NUMERIC_OP_NAMES[second], operand[3])
+ if not bottom < top:
+ raise _InvalidPattern("Bottom must be less than top")
+
+
+def _validate_anything_but(operand):
+ if isinstance(operand, dict):
+ if not operand:
+ raise _InvalidPattern("Anything-But expression name not found")
+ inner = next(iter(operand))
+ if len(operand) > 1:
+ raise _InvalidPattern("Only one key allowed in match expression")
+ if inner not in _ANYTHING_BUT_NESTABLE:
+ raise _InvalidPattern(f"Unsupported anything-but pattern: {inner}")
+ _validate_anything_but_nested(inner, operand[inner])
+ return
+ if isinstance(operand, list):
+ # The list is walked in order, as AWS's streaming parser walks it, so an
+ # unsupported element is reported before the type-homogeneity check.
+ for value in operand:
+ if isinstance(value, bool) or value is None or isinstance(value, (list, dict)):
+ raise _InvalidPattern(
+ "Inside anything but list, start|null|boolean is not supported.")
+ has_number = any(isinstance(v, (int, float)) for v in operand)
+ has_string = any(isinstance(v, str) for v in operand)
+ if not operand or (has_number and has_string):
+ raise _InvalidPattern(
+ "Inside anything but list, either all values are number or string, "
+ "mixed type is not supported")
+ for value in operand:
+ if isinstance(value, (int, float)):
+ _validate_numeric_threshold("anything-but", value)
+ return
+ if isinstance(operand, bool) or operand is None:
+ raise _InvalidPattern(
+ "Value of anything-but must be an array or single string/number value.")
+ if isinstance(operand, (int, float)):
+ _validate_numeric_threshold("anything-but", operand)
+
+
+def _validate_anything_but_nested(inner: str, operand):
+ """The nested form takes one value or a list of them. AWS's outer type guard
+ fires first, so a boolean or null operand is reported against
+ ``anything-but`` rather than against the nested operator."""
+ candidates = operand if isinstance(operand, list) else [operand]
+ if not candidates:
+ # A deliberate divergence: AWS accepts an empty nested list and then
+ # fails evaluating the rule, so there is no behaviour to copy — and an
+ # ``anything-but`` with nothing to exclude inverts into "every event".
+ raise _InvalidPattern("Empty arrays are not allowed")
+ for candidate in candidates:
+ if isinstance(candidate, bool) or candidate is None:
+ raise _InvalidPattern(
+ "Value of anything-but must be an array or single string/number value.")
+ if inner in ("prefix", "suffix"):
+ for candidate in candidates:
+ _require_type(candidate, str, "prefix/suffix match pattern must be a string")
+ if not candidate:
+ # This position only — ``{"prefix": ""}`` is a pattern AWS
+ # compiles, so do not hoist this into ``_validate_affix``.
+ raise _InvalidPattern("Null prefix/suffix not allowed")
+ elif inner == "equals-ignore-case":
+ for candidate in candidates:
+ _require_type(candidate, str, "Inside anything-but/equals-ignore-case list, "
+ "number|start|null|boolean is not supported.")
+ elif inner == "wildcard":
+ for candidate in candidates:
+ _validate_wildcard(candidate)
+
+
+# Every operator a match expression may name, with the check its operand has to
+# pass. ``exactly`` is Event Ruler's explicit spelling of a plain equality value;
+# the rest are the documented ones.
+_OPERAND_VALIDATORS = {
+ "exactly": functools.partial(
+ _require_type, kind=str, message="exact match pattern must be a string"),
+ "prefix": functools.partial(_validate_affix, "prefix"),
+ "suffix": functools.partial(_validate_affix, "suffix"),
+ "equals-ignore-case": functools.partial(
+ _require_type, kind=str, message="equals-ignore-case match pattern must be a string"),
+ "wildcard": _validate_wildcard,
+ "cidr": _validate_cidr,
+ "numeric": _validate_numeric,
+ "exists": functools.partial(
+ _require_type, kind=bool, message="exists match pattern must be either true or false."),
+ "anything-but": _validate_anything_but,
+}
+_MATCH_OPERATORS = frozenset(_OPERAND_VALIDATORS)
- if "account" in pattern:
- if not _matches_field(event.get("Account", get_account_id()), pattern["account"]):
- return False
- if "region" in pattern:
- if not _matches_field(event.get("Region", get_region()), pattern["region"]):
- return False
+# How deep an event value's arrays are followed when flattening. Generous next to
+# any real event, and small next to the stack a handler has left.
+_MAX_VALUE_DEPTH = 50
- if "resources" in pattern:
- event_resources = event.get("Resources", [])
- for required in pattern["resources"]:
- if required not in event_resources:
- return False
- return True
+# ---------------------------------------------------------------------------
+# Event pattern matching — value-level operators
+# ---------------------------------------------------------------------------
-def _matches_field(value, pattern_values):
- if isinstance(pattern_values, list):
- for item in pattern_values:
- if isinstance(item, dict):
- # Content-based filter (wildcard, prefix, suffix, etc.)
- if _matches_content_filter(value, item):
- return True
- elif value == item:
- return True
+def _flatten(value, objects: bool, depth: int = 0) -> list:
+ """What a pattern is matched against for this event value: the scalars it
+ offers, or — one level of the tree up, for a nested pattern object — the
+ objects. AWS flattens an array value and offers each element to the matcher
+ on its own, recursively, so the field matches when *any* element does.
+
+ Whatever is not the wanted leaf yields nothing and so matches nothing: an
+ object has no scalar to offer, a scalar has no object, and an empty array
+ has neither — including under ``anything-but``, which needs at least one
+ surviving element rather than the absence of a failing one.
+
+ The depth bound is for the event side: an event may nest arrays as deep as
+ its author likes, and past the bound the nesting yields nothing rather than
+ exhausting the stack."""
+ if isinstance(value, list):
+ if depth >= _MAX_VALUE_DEPTH:
+ return []
+ flat = []
+ for element in value:
+ flat.extend(_flatten(element, objects, depth + 1))
+ return flat
+ return [value] if isinstance(value, dict) == objects else []
+
+
+def _json_equal(left, right) -> bool:
+ """JSON equality, which Python's ``==`` is not. AWS compares as JSON, so a
+ string never equals a number and ``true`` never equals ``1`` — where Python
+ holds ``True == 1``. Numbers of different width do still compare equal."""
+ if isinstance(left, bool) != isinstance(right, bool):
return False
- return value == pattern_values
+ return left == right
+
+
+def _matches_alternatives(value, alternatives) -> bool:
+ """Whether one scalar satisfies any alternative in a pattern's value list.
+ ``exists`` is skipped: it is answered from the key's presence, not from the
+ value, and its caller has already dealt with it."""
+ for item in alternatives:
+ if isinstance(item, dict):
+ if "exists" in item:
+ continue
+ if _matches_content_filter(value, item):
+ return True
+ elif _json_equal(value, item):
+ return True
+ return False
def _matches_detail(detail, pattern):
- if not isinstance(pattern, dict):
- return True
+ """Match one ``$or``-free alternative against an object. Every ``$or`` is
+ gone by the time this runs — ``_compile_pattern`` expanded it — so this is a
+ plain AND over the pattern's keys."""
+ if isinstance(pattern, dict) and _UNSATISFIABLE in pattern:
+ return False
+ if not isinstance(pattern, dict) or not pattern:
+ # Both are refused at rule creation; an empty pattern object constrains
+ # nothing, so matching it would be the fail-open answer.
+ return False
for key, expected in pattern.items():
present = isinstance(detail, dict) and key in detail
actual = detail.get(key) if isinstance(detail, dict) else None
if isinstance(expected, list):
- # AWS content-filter: ``[{"exists": true|false}]`` is evaluated
- # against key presence/absence, NOT against the value, so an
- # absent key must NOT short-circuit to False before that check.
- exists_filters = [
- item for item in expected
- if isinstance(item, dict) and "exists" in item
- ]
+ # ``exists`` asks whether the path reaches a LEAF, not whether the
+ # key is there: AWS's operators "only work on leaf nodes", so an
+ # object-valued field, an empty array and an empty object are all
+ # indistinguishable from a missing key, while a null exists — it is
+ # a leaf. ``_flatten`` answers exactly that question. Evaluated
+ # before the value filters, because an absent key must not
+ # short-circuit past it.
+ scalars = _flatten(actual, False) if present else []
+ has_leaf = bool(scalars)
+ exists_filters = [item for item in expected
+ if isinstance(item, dict) and "exists" in item]
if exists_filters:
- if any(item.get("exists") is True for item in exists_filters) and present:
+ # ``is``, not ``==``: a non-bool operand — reachable only from
+ # unrevalidated state — settles nothing and must not be coerced.
+ if any(item["exists"] is has_leaf for item in exists_filters):
continue
- if any(item.get("exists") is False for item in exists_filters) and not present:
- continue
- # No exists branch matched and there are no value-level filters
- # left to try — treat as no match.
- if all(isinstance(item, dict) and "exists" in item for item in expected):
+ if len(exists_filters) == len(expected):
return False
if not present:
return False
- if isinstance(actual, (str, int, float, bool)):
- matched = False
- for item in expected:
- if isinstance(item, dict) and "exists" in item:
- continue # already handled above
- if isinstance(item, dict):
- matched = matched or _matches_content_filter(actual, item)
- elif actual == item or str(actual) == str(item):
- matched = True
- if not matched:
- return False
- elif isinstance(actual, list):
- if not any(a in expected for a in actual):
- return False
- elif isinstance(expected, dict):
- if not isinstance(actual, dict):
+ # Every value shape must be judged: an unjudged key is a matched
+ # key, and a null or object detail used to reach no arm at all, so
+ # a rule guarding on an operator fired on what it excluded.
+ if not any(_matches_alternatives(scalar, expected)
+ for scalar in scalars):
return False
- if not _matches_detail(actual, expected):
+ elif isinstance(expected, dict):
+ # Two pattern fields must come from the SAME array element: each
+ # element is offered the whole nested pattern.
+ #
+ # A non-object value still gets the pattern evaluated, against
+ # nothing — so ``{"detail": {"state": [{"exists": false}]}}`` is
+ # satisfied by an event whose ``detail`` is a string, as on AWS.
+ candidates = _flatten(actual, True) or [{}]
+ if not any(_matches_detail(candidate, expected)
+ for candidate in candidates):
return False
+ else:
+ # A pattern value must be an array of alternatives or a nested
+ # object; a bare scalar is neither, and leaving it unjudged is how a
+ # ``$or`` read as an ordinary field could match every event.
+ return False
return True
-def _matches_content_filter(value, filter_rule):
- if "wildcard" in filter_rule:
- return isinstance(value, str) and fnmatch.fnmatch(value, filter_rule["wildcard"])
- if "prefix" in filter_rule:
- return isinstance(value, str) and value.startswith(filter_rule["prefix"])
- if "suffix" in filter_rule:
- return isinstance(value, str) and value.endswith(filter_rule["suffix"])
- if "anything-but" in filter_rule:
- excluded = filter_rule["anything-but"]
- # Per AWS EventBridge docs, anything-but supports either a literal
- # / list-of-literals OR a single nested content matcher (prefix,
- # suffix, wildcard, equals-ignore-case). Mixing literals and nested
- # matchers in a list is explicitly rejected by AWS at rule
- # creation, so we match the strict form only.
- if isinstance(excluded, dict):
- return not _matches_content_filter(value, excluded)
- if isinstance(excluded, list):
- return value not in excluded
- return value != excluded
- if "numeric" in filter_rule:
- ops = filter_rule["numeric"]
- try:
- num = float(value)
- except (ValueError, TypeError):
+def _wildcard_to_regex(pattern: str) -> str:
+ """Translate an AWS EventBridge wildcard pattern to an anchored regex. Only
+ ``*`` is special (any sequence); ``\\`` escapes the next character, so
+ ``\\*`` is a literal asterisk and ``\\\\`` a literal backslash. Unlike
+ fnmatch, ``?`` and ``[seq]`` are literal — matching AWS exactly.
+
+ The literal run after each interior ``*`` is emitted as fnmatch's
+ ``(?=(?P<gN>.*?lit))(?P=gN)`` rather than a plain ``.*lit``. The lookahead
+ plus backreference commits to the leftmost match — glob semantics anyway —
+ and stops the engine backtracking. A naive ``.*a.*a.*b`` chain is
+ exponential against a long non-matching value: ``*/*/*/*/*.json`` over a
+ 70-character key that just misses takes seconds, per rule per event.
+
+ Anchoring is ``^``/``\\Z``, not ``$``, which would also match just before a
+ trailing newline."""
+ # One token is an escape pair, a bare ``*``, or a run of ordinary characters.
+ # A trailing lone backslash matches nothing after it, so ``\\[\s\S]?`` leaves
+ # it as the escape of an empty string — the same literal backslash the
+ # character walk produced.
+ segments = [""]
+ for token in re.findall(r"\\[\s\S]?|\*|[^\\*]+", pattern):
+ if token == "*":
+ segments.append("")
+ elif token[0] == "\\":
+ segments[-1] += re.escape(token[1:]) if len(token) > 1 else "\\\\"
+ else:
+ segments[-1] += re.escape(token)
+
+ out = ["^", segments[0]]
+ interior = [s for s in segments[1:-1] if s]
+ for n, seg in enumerate(interior):
+ out.append(f"(?=(?P<g{n}>.*?{seg}))(?P=g{n})")
+ if len(segments) > 1:
+ out.append(".*")
+ out.append(segments[-1])
+ out.append(r"\Z")
+ return "".join(out)
+
+
[email protected]_cache(maxsize=1024)
+def _wildcard_regex(pattern: str):
+ """Compiled form of ``pattern``, cached like ``_compiled_pattern``."""
+ return re.compile(_wildcard_to_regex(pattern), re.DOTALL)
+
+
+def _string_operands(operand):
+ """The pattern strings an operand denotes — one, or a list of them, any of
+ which may match — or ``None`` when it is malformed. A malformed operand
+ never matches rather than raising: the matcher runs inside ``PutEvents``, so
+ a raise is a 500 that fails the whole batch, not one skipped rule. An empty
+ list is malformed for this purpose — it has no pattern to match, and
+ answering true would make ``anything-but`` invert it into a rule that fires
+ on every event. The list form is accepted at any depth, where AWS accepts it
+ only under ``anything-but``."""
+ candidates = operand if isinstance(operand, list) else [operand]
+ if not candidates or not all(isinstance(c, str) for c in candidates):
+ return None
+ return candidates
+
+
+def _matches_wildcard(value, pattern) -> bool:
+ """Match ``value`` against an AWS wildcard operand."""
+ if not isinstance(value, str):
+ return False
+ patterns = _string_operands(pattern)
+ return patterns is not None and any(_wildcard_regex(p).match(value) is not None for p in patterns)
+
+
+def _ignore_case_alternatives(char: str) -> tuple:
+ """The forms AWS accepts at one operand position: the character's lower
+ and upper case, deduplicated. Each is taken on the character alone, so a
+ mapping that changes length counts — ``ß`` uppercases to ``SS``."""
+ lower, upper = char.lower(), char.upper()
+ return (lower,) if lower == upper else (lower, upper)
+
+
+def _ignore_case_reach(value: str, operand: str, backwards: bool = False) -> set:
+ """The offsets in ``value`` the operand's alternation can reach — consuming
+ forwards from the start, or backwards from the end when ``backwards``.
+
+ Three questions are the one walk with different anchoring: ``prefix`` asks
+ whether the forward walk reaches anywhere, ``suffix`` whether the backward
+ one does, and ``equals-ignore-case`` whether the forward one reaches the end.
+
+ Carrying the whole reachable set is what keeps it linear: the alternatives at
+ a position differ in length (``ß`` uppercases to ``SS``), so a greedy scan
+ gives the wrong answer and a regex alternation reintroduces the backtracking
+ ``_wildcard_to_regex`` goes out of its way to avoid. The backward walk exists
+ for the same reason — running the forward one from every start offset would
+ be quadratic in the two lengths, on the same dispatch path."""
+ reachable = {len(value) if backwards else 0}
+ for char in reversed(operand) if backwards else operand:
+ moved = set()
+ for alternative in _ignore_case_alternatives(char):
+ width = len(alternative)
+ for offset in reachable:
+ start = offset - width if backwards else offset
+ if start >= 0 and value.startswith(alternative, start):
+ moved.add(start if backwards else offset + width)
+ if not moved:
+ return set()
+ reachable = moved
+ return reachable
+
+
+def _matches_affix(value, operand, at_start: bool) -> bool:
+ """``prefix`` when ``at_start``, ``suffix`` otherwise. Only a string can
+ match: AWS matches an affix against the quoted form of the value, so
+ ``{"prefix": "5"}`` never reaches the number ``5`` (see ``_validate_affix``
+ for what that makes an empty operand mean). A nested ``equals-ignore-case``
+ is AWS's spelling of a case-insensitive affix."""
+ if not isinstance(value, str):
+ return False
+ ignore_case = isinstance(operand, dict)
+ if ignore_case:
+ if len(operand) != 1 or "equals-ignore-case" not in operand:
return False
- i = 0
- while i < len(ops) - 1:
- op, threshold = ops[i], float(ops[i + 1])
- if op == ">" and not (num > threshold):
- return False
- if op == ">=" and not (num >= threshold):
- return False
- if op == "<" and not (num < threshold):
- return False
- if op == "<=" and not (num <= threshold):
- return False
- if op == "=" and not (num == threshold):
- return False
- i += 2
- return True
- if "exists" in filter_rule:
- return filter_rule["exists"] == (value is not None)
+ operand = operand["equals-ignore-case"]
+ candidates = _string_operands(operand)
+ if candidates is None:
+ return False
+ if ignore_case:
+ return any(_ignore_case_reach(value, c, not at_start) for c in candidates)
+ return any(value.startswith(c) if at_start else value.endswith(c) for c in candidates)
+
+
+def _matches_equals_ignore_case(value, operand) -> bool:
+ """Match an ``equals-ignore-case`` operand against the whole value.
+
+ AWS accepts either case of each operand character independently, which is
+ neither ``value.lower() == operand.lower()`` nor ``casefold`` — the two are
+ wrong in opposite directions. ``lower()`` under-matches where the cases
+ differ in length (it rejects ``straße`` against ``STRASSE``) and
+ over-matches by making the relation symmetric, which AWS's is not: the
+ operand ``ẞ`` matches the value ``ß``, the reverse does not.
+ ``casefold()`` over-matches outright, accepting ``strasse`` for that same
+ operand. So the alternation is walked character by character.
+
+ Only a string value can match. One deliberate divergence: an operand
+ character outside the Basic Multilingual Plane matches itself, where AWS
+ mangles it to ``?`` and so fails to match the very value it was written
+ for."""
+ if not isinstance(value, str):
+ return False
+ operands = _string_operands(operand)
+ # Anchored at both ends: the walk must consume the operand AND land exactly on
+ # the end of the value, which is what makes this equality rather than a prefix.
+ return operands is not None and any(
+ len(value) in _ignore_case_reach(value, o) for o in operands)
+
+
+
+def _cidr_address(text: str):
+ """``text`` as an address, or ``None`` if it is not one AWS would read. The
+ same admission test gates the operand and the value, since two sides spelled
+ alike have to agree."""
+ if _CIDR_IPV4_RE.match(text):
+ text = _normalized_ipv4(text)
+ elif not (":" in text and _CIDR_IPV6_RE.match(text)):
+ return None
+ try:
+ return ipaddress.ip_address(text)
+ except ValueError:
+ return None
+
+
[email protected]_cache(maxsize=1024)
+def _cidr_network(operand: str):
+ """The network a ``cidr`` operand denotes, or ``None`` where AWS rejects the
+ operand at rule creation. Cached like ``_compiled_pattern``.
+
+ The grammar is read from ``_validate_cidr`` rather than spelled a second
+ time — the two drifting apart is a rule that fails creation and still
+ matches, or the reverse. ``ipaddress`` cannot stand in for it, being both
+ too permissive (a bare ``10.0.0.1`` read as a ``/32``, a dotted netmask, a
+ zone id) and too strict (it raises on host bits set, which AWS silently
+ floors, so ``10.0.0.5/24`` is the ``10.0.0.0/24`` block)."""
+ try:
+ _validate_cidr(operand)
+ except _InvalidPattern:
+ return None
+ address, _, mask = operand.partition("/")
+ if _CIDR_IPV4_RE.match(address):
+ # Decimal octets, as AWS reads them; see ``_normalized_ipv4``.
+ address = _normalized_ipv4(address)
+ try:
+ return ipaddress.ip_network(f"{address}/{int(mask)}", strict=False)
+ except ValueError:
+ # Unreachable through the validated grammar; a raising matcher fails
+ # the whole batch.
+ return None
+
+
+def _matches_cidr(value, operand) -> bool:
+ """Whether ``value`` is an address inside the ``cidr`` operand's block.
+
+ Both sides must be strings. ``ipaddress`` reads an integer as an address —
+ ``167772161`` is ``10.0.0.1``, and ``True`` is ``0.0.0.1`` — so an
+ unguarded numeric detail value would match a block AWS never matches it
+ against. Only one operand string is read: AWS takes one block per ``cidr``
+ object, several being written as sibling objects in the field's value list.
+
+ An address of the other family does not match. The version is compared
+ before the containment test rather than leaning on ``in`` to answer it,
+ since that behaviour is a property of the stdlib rather than of this
+ matcher's contract."""
+ if not isinstance(value, str) or not isinstance(operand, str):
+ return False
+ network = _cidr_network(operand)
+ if network is None:
+ return False
+ address = _cidr_address(value)
+ if address is None:
+ return False
+ return address.version == network.version and address in network
+
+
+# ``numeric`` comparison operators, in the [op, threshold, ...] operand order.
+_NUMERIC_OPS = {
+ ">": operator.gt,
+ ">=": operator.ge,
+ "<": operator.lt,
+ "<=": operator.le,
+ "=": operator.eq,
+}
+
+
+def _numeric_conditions(ops):
+ """Normalize a ``numeric`` operand into ``[(op, threshold), ...]``, or
+ ``None`` when it is malformed. ``{"numeric": 5}`` and
+ ``{"numeric": [">", "abc"]}`` both used to escape as a 500 InternalError.
+ The operator is type-checked before the lookup because an unhashable one
+ raises from the ``in`` test itself, and the threshold conversion catches
+ OverflowError because that, not ValueError, is what ``float()`` raises for
+ an integer literal too large for a double."""
+ if not isinstance(ops, list) or not ops or len(ops) % 2:
+ return None
+ conditions = []
+ for i in range(0, len(ops), 2):
+ op = ops[i]
+ if not isinstance(op, str) or op not in _NUMERIC_OPS:
+ return None
+ try:
+ conditions.append((op, float(ops[i + 1])))
+ except (TypeError, ValueError, OverflowError):
+ return None
+ return conditions
+
+
+def _matches_numeric(value, operand) -> bool:
+ conditions = _numeric_conditions(operand)
+ if conditions is None:
+ return False
+ if not isinstance(value, (int, float)) or isinstance(value, bool):
+ # A JSON number and nothing else: the text "50" and ``True`` both
+ # convert happily in Python, so without this the rule over-matched.
+ return False
+ try:
+ num = float(value)
+ except (ValueError, TypeError, OverflowError):
+ # OverflowError: an integer too large for a double. Non-match, not 500.
+ return False
+ return all(_NUMERIC_OPS[op](num, threshold) for op, threshold in conditions)
+
+
+def _matches_exactly(value, operand) -> bool:
+ """``exactly``'s operand is a string and nothing else — AWS refuses any other
+ at rule creation — so a stored ``{"exactly": 5}`` matches nothing rather than
+ standing in for the numeric equality it was not written as."""
+ return isinstance(operand, str) and _json_equal(value, operand)
+
+
+def _matches_anything_but(value, operand) -> bool:
+ """``anything-but`` takes a literal or list of literals, OR one nested
+ content matcher (not ``cidr``; see ``_nested_matcher_ok``). AWS rejects a
+ list mixing literals and nested matchers at rule creation, so only the
+ strict form is matched."""
+ if isinstance(operand, dict):
+ return _nested_matcher_ok(operand) and not _matches_content_filter(value, operand)
+ if isinstance(operand, list):
+ return not any(_json_equal(value, item) for item in operand)
+ return not _json_equal(value, operand)
+
+
+# Every operator answered from the *value*, mapped to its matcher. Dict order is
+# the try order, but only ever consulted for one key: AWS refuses a two-operator
+# expression at rule creation, and a pattern is validated before it is matched.
+#
+# ``exists`` has no entry — it asks about the key, not the value, so
+# ``_matches_detail`` settles it before any value gets here.
+_CONTENT_MATCHERS = {
+ "wildcard": _matches_wildcard,
+ "prefix": functools.partial(_matches_affix, at_start=True),
+ "suffix": functools.partial(_matches_affix, at_start=False),
+ "exactly": _matches_exactly,
+ "equals-ignore-case": _matches_equals_ignore_case,
+ "cidr": _matches_cidr,
+ "anything-but": _matches_anything_but,
+ "numeric": _matches_numeric,
+}
+_CONTENT_MATCHER_KEYS = tuple(_CONTENT_MATCHERS)
+# The invertible subset, derived rather than spelled a second time: a gate
+# approving a key the validator refuses is what reopens the inversion.
+_NESTED_MATCHER_KEYS = tuple(k for k in _CONTENT_MATCHER_KEYS if k in _ANYTHING_BUT_NESTABLE)
+
+
+def _nested_matcher_ok(filter_rule) -> bool:
+ """Whether ``anything-but``'s nested operand is one AWS lets it invert and
+ this emulator can evaluate.
+
+ ``cidr`` and ``numeric`` are the interesting exclusions: both are supported
+ as matchers, but AWS nests only ``prefix``, ``suffix``, ``wildcard`` and
+ ``equals-ignore-case``. Inverting an operand that can only answer "no
+ match" — malformed, or not invertible — would turn a bad rule into one that
+ matches *every* event and fans it out to its targets, so ``anything-but``
+ declines instead. Validation refuses these outright now; this is the
+ backstop for a rule restored from persisted state, which is never
+ revalidated.
+
+ Anything other than exactly one invertible key is declined, so the answer
+ cannot depend on which key the dispatch reaches first. The scan is over
+ ``_matches_content_filter``'s own keys, so the key approved here is the key
+ that answers there — and ``exists``, having no registry entry, is invisible
+ to it: ``{"exists": true, "prefix": "a"}`` is approved on the prefix.
+ Validation is what refuses that, reporting "Only one key allowed in match
+ expression" for any operand dict with more than one key, so the gate never
+ sees one."""
+ if not isinstance(filter_rule, dict):
+ return False
+ present = [k for k in _CONTENT_MATCHER_KEYS if k in filter_rule]
+ if len(present) != 1 or present[0] not in _NESTED_MATCHER_KEYS:
+ return False
+ # All four nestable operators take a pattern string or a list of them, so
+ # one arm covers them.
+ return _string_operands(filter_rule[present[0]]) is not None
+
+
+def _matches_content_filter(value, filter_rule):
+ """Whether one scalar satisfies one match expression — the first operator it
+ names in registry order, since AWS allows it only one."""
+ for key, matcher in _CONTENT_MATCHERS.items():
+ if key in filter_rule:
+ return matcher(value, filter_rule[key])
return False
-def _invoke_target(target, event, rule):
+def _invoke_target(target, event, rule, view=None):
arn = target.get("Arn", "")
event_path = set(event.get("_DispatchPath") or [])
- raw_time = event["Time"]
- if isinstance(raw_time, (int, float)):
- iso_time = datetime.fromtimestamp(raw_time, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
- else:
- iso_time = raw_time
-
- event_payload = json.dumps({
- "version": "0",
- "id": event["EventId"],
- "source": event["Source"],
- "account": get_account_id(),
- "time": iso_time,
- "region": get_region(),
- "resources": event.get("Resources", []),
- "detail-type": event["DetailType"],
- "detail": json.loads(event["Detail"]) if isinstance(event["Detail"], str) else event["Detail"],
- })
+ # The tree the rule matched on, so a rule cannot fire on a field whose
+ # delivered value differs. Decoded once for the whole event.
+ view = view or _pattern_event_view(event)
+ event_payload = json.dumps(view.event_with_detail())
+ # An ``InputPath`` that does not resolve leaves the whole event in place.
target_input_payload = None
- input_transformer = target.get("InputTransformer")
- if input_transformer:
- event_payload = _apply_input_transformer(input_transformer, event, rule)
- target_input_payload = event_payload
+ if target.get("InputTransformer"):
+ target_input_payload = _apply_input_transformer(target["InputTransformer"], rule, view)
elif target.get("Input"):
- event_payload = target["Input"]
- target_input_payload = event_payload
+ target_input_payload = target["Input"]
elif target.get("InputPath"):
try:
- full = json.loads(event_payload)
- parts = target["InputPath"].strip("$.").split(".")
- val = full
- for p in parts:
- if p:
- val = val[p]
- event_payload = json.dumps(val)
- target_input_payload = event_payload
+ val = json.loads(event_payload)
+ for part in target["InputPath"].strip("$.").split("."):
+ if part:
+ val = val[part]
+ target_input_payload = json.dumps(val)
except Exception:
pass
+ if target_input_payload is not None:
+ event_payload = target_input_payload
try:
try:
@@ -1257,26 +2322,14 @@ def _dispatch_to_event_bus(spec, event, rule, event_path, target_input_payload=N
logger.info("EventBridge -> Event bus %s: dispatched", spec)
-def _apply_input_transformer(transformer, event, rule=None):
+def _apply_input_transformer(transformer, rule, view):
input_paths = transformer.get("InputPathsMap", {})
template = transformer.get("InputTemplate", "")
- try:
- full = json.loads(event.get("Detail", "{}")) if isinstance(event.get("Detail"), str) else event.get("Detail", {})
- except Exception:
- full = {}
-
- event_envelope = {
- "version": "0",
- "source": event.get("Source", ""),
- "detail-type": event.get("DetailType", ""),
- "detail": full,
- "account": get_account_id(),
- "region": get_region(),
- "time": event.get("Time", ""),
- "id": event.get("EventId", ""),
- "resources": event.get("Resources", []),
- }
+ # The same tree the rule matched on and the target is delivered:
+ # hand-building a third copy here is how ``time`` came to render as a raw
+ # epoch second while the payload alongside it carried the ISO-8601 string.
+ event_envelope = view.event_with_detail()
replacements = {}
for var_name, jpath in input_paths.items():
@@ -1296,7 +2349,7 @@ def _apply_input_transformer(transformer, event, rule=None):
ingestion_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
reserved = {
"aws.events.event.json": json.dumps(event_envelope),
- "aws.events.event": json.dumps({k: v for k, v in event_envelope.items() if k != "detail"}),
+ "aws.events.event": json.dumps(view.envelope()),
"aws.events.event.ingestion-time": ingestion_time,
}
if rule:
@@ -1846,6 +2899,10 @@ def _create_archive(data):
if name in _archives:
return error_response_json("ResourceAlreadyExistsException", f"Archive {name} already exists", 400)
+ pattern_error = _event_pattern_error(data.get("EventPattern", ""))
+ if pattern_error:
+ return _invalid_event_pattern(pattern_error)
+
source_arn = data.get("EventSourceArn", "")
arn = f"arn:aws:events:{get_region()}:{get_account_id()}:archive/{name}"
_archives[name] = {
@@ -1891,15 +2948,9 @@ def _update_archive(data):
archive["Description"] = data["Description"]
if "EventPattern" in data:
ep = data["EventPattern"]
- if isinstance(ep, str) and ep:
- try:
- json.loads(ep)
- except json.JSONDecodeError:
- return error_response_json(
- "InvalidEventPatternException",
- "Event pattern is not valid JSON",
- 400,
- )
+ pattern_error = _event_pattern_error(ep)
+ if pattern_error:
+ return _invalid_event_pattern(pattern_error)
archive["EventPattern"] = ep
if "RetentionDays" in data:
archive["RetentionDays"] = int(data["RetentionDays"])
@@ -2005,6 +3056,10 @@ def _start_replay(data):
continue
replayed = dict(event)
replayed["EventBusName"] = dest_bus_name
+ # AWS stamps a replayed event with the replay's name, which is
+ # how a rule tells replayed traffic from live traffic — either
+ # to act on it or, more often, to filter it out.
+ replayed["ReplayName"] = name
_dispatch_event(replayed)
replay["State"] = "COMPLETED"
replay["ReplayEndTime"] = _now_ts()
@@ -3022,9 +4077,10 @@ def _tick_scheduled_rules():
"Account": account_id,
"Region": get_region(),
}
+ view = _pattern_event_view(event)
for target in targets:
try:
- _invoke_target(target, event, rule)
+ _invoke_target(target, event, rule, view)
except Exception:
logger.exception(
"EventBridge scheduler: dispatch error for rule %s account %s",
@@ -3076,5 +4132,15 @@ def reset():
_rule_last_fired.clear()
with _oauth_tokens_lock:
_oauth_tokens.clear()
+ # These memoize on text a caller sent — a pattern, a wildcard operand, a cidr
+ # block — and on the epoch second an event carries, and nothing else evicts an
+ # entry below the 1024-entry cap, so a reset that skipped them would keep
+ # hundreds of megabytes of compiled regexes and expanded ``$or``s for rules it
+ # just deleted. Clearing cannot change an answer: each is a pure function of
+ # its key.
+ _compiled_pattern.cache_clear()
+ _wildcard_regex.cache_clear()
+ _cidr_network.cache_clear()
+ _iso_time.cache_clear()
# The "default" bus is lazily recreated per-account on next access via
# _ensure_default_bus(), so nothing to re-seed here.
diff --git a/tests/test_eventbridge.py b/tests/test_eventbridge.py
index e7e88db6..cf0e091b 100644
--- a/tests/test_eventbridge.py
+++ b/tests/test_eventbridge.py
@@ -2292,7 +2292,8 @@ def test_scheduler_restores_rule_region_while_dispatching(isolated_scheduler):
]
_eb._rule_last_fired[west_state_key] = _eb._now_ts() - 65
isolated_scheduler.side_effect = (
- lambda _target, event, _rule: observed.append((_eb.get_region(), event["Region"]))
+ lambda _target, event, _rule, _view=None: observed.append(
+ (_eb.get_region(), event["Region"]))
)
_eb._tick_scheduled_rules()
@@ -2561,28 +2562,26 @@ def test_eventbridge_dispatch_to_fifo_sqs_stamps_message_group_id(eb, sqs):
# ── anything-but with nested content filters (#849) ──────────────────
+def _eb_rule_to_queue(eb, sqs, slug, pattern, bus):
+ """Helper: a queue plus an ENABLED rule on ``bus`` filtering on ``pattern``
+ and targeting it. Returns the queue URL."""
+ q_url = sqs.create_queue(QueueName=f"qa-eb-{slug}-q")["QueueUrl"]
+ q_arn = sqs.get_queue_attributes(
+ QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ rule = f"qa-eb-{slug}-rule"
+ eb.put_rule(Name=rule, EventBusName=bus, State="ENABLED",
+ EventPattern=json.dumps(pattern))
+ eb.put_targets(Rule=rule, EventBusName=bus, Targets=[{"Id": "t1", "Arn": q_arn}])
+ return q_url
+
+
def _eb_setup_anybut_rule(eb, sqs, suffix, pattern_value):
"""Helper: create bus + queue + rule with a given anything-but pattern."""
bus = f"qa-eb-anybut-{suffix}-bus"
eb.create_event_bus(Name=bus)
- q_url = sqs.create_queue(QueueName=f"qa-eb-anybut-{suffix}-q")["QueueUrl"]
- q_arn = sqs.get_queue_attributes(
- QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
- eb.put_rule(
- Name=f"qa-eb-anybut-{suffix}-rule",
- EventBusName=bus,
- EventPattern=json.dumps({
- "source": ["myapp"],
- "detail": {"id": [{"anything-but": pattern_value}]},
- }),
- State="ENABLED",
- )
- eb.put_targets(
- Rule=f"qa-eb-anybut-{suffix}-rule",
- EventBusName=bus,
- Targets=[{"Id": "t1", "Arn": q_arn}],
- )
- return bus, q_url
+ return bus, _eb_rule_to_queue(
+ eb, sqs, f"anybut-{suffix}",
+ {"source": ["myapp"], "detail": {"id": [{"anything-but": pattern_value}]}}, bus)
def _eb_send(eb, bus, id_value):
@@ -2719,6 +2718,50 @@ def test_eventbridge_input_transformer_event_escaped(eb, sqs):
assert "detail" not in body["evt"]
+def test_eventbridge_input_transformer_renders_the_event_it_would_have_sent(eb, sqs):
+ """``<aws.events.event.json>`` is the event, not a paraphrase of it: AWS
+ substitutes the same envelope the target would have received without the
+ transformer. Building a second copy for the substitution is how ``time`` came
+ to render as the raw epoch second the entry carried while the plain target
+ beside it received the ISO-8601 string — a difference invisible until a
+ consumer parses the timestamp. Both targets are on one rule, so the two
+ payloads describe the same delivery of the same event."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ bus_name = f"qa-eb-one-envelope-bus-{suffix}"
+ rule_name = f"qa-eb-one-envelope-rule-{suffix}"
+ eb.create_event_bus(Name=bus_name)
+ plain_url = sqs.create_queue(QueueName=f"qa-eb-one-envelope-plain-{suffix}")["QueueUrl"]
+ tr_url = sqs.create_queue(QueueName=f"qa-eb-one-envelope-tr-{suffix}")["QueueUrl"]
+ arn_of = lambda url: sqs.get_queue_attributes( # noqa: E731
+ QueueUrl=url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ eb.put_rule(Name=rule_name, EventBusName=bus_name, State="ENABLED",
+ EventPattern=json.dumps({"source": ["myapp.one-envelope"]}))
+ eb.put_targets(
+ Rule=rule_name,
+ EventBusName=bus_name,
+ Targets=[
+ {"Id": "plain", "Arn": arn_of(plain_url)},
+ {"Id": "transformed", "Arn": arn_of(tr_url),
+ "InputTransformer": {"InputPathsMap": {},
+ "InputTemplate": '{"sent": <aws.events.event.json>}'}},
+ ],
+ )
+ eb.put_events(Entries=[{"Source": "myapp.one-envelope", "DetailType": "T",
+ "Detail": json.dumps({"k": "v"}),
+ "EventBusName": bus_name}])
+ plain = json.loads(sqs.receive_message(
+ QueueUrl=plain_url, MaxNumberOfMessages=1,
+ WaitTimeSeconds=2)["Messages"][0]["Body"])
+ rendered = json.loads(sqs.receive_message(
+ QueueUrl=tr_url, MaxNumberOfMessages=1,
+ WaitTimeSeconds=2)["Messages"][0]["Body"])["sent"]
+ assert rendered == plain, (rendered, plain)
+ # The field the two copies actually disagreed on, named so a regression
+ # reports the cause rather than a whole-envelope inequality.
+ assert rendered["time"] == plain["time"]
+ assert isinstance(plain["time"], str) and plain["time"].endswith("Z")
+
+
def test_eventbridge_input_transformer_rule_name_and_arn(eb, sqs):
"""<aws.events.rule-name> and <aws.events.rule-arn> resolve to the rule's Name and Arn."""
bus_name = "qa-eb-reserved-rn-bus"
@@ -3772,3 +3815,1603 @@ def test_eventbridge_oauth_endpoint_check_tolerates_non_dict_auth_parameters():
200, and adding validation must not turn that into a 500."""
for junk in (None, "oops", ["x"], 5, True, ""):
assert _eb._validate_oauth_authorization_endpoint(junk) is None
+
+
+# ---------------------------------------------------------------------------
+# Content-pattern matcher parity regression tests
+# ---------------------------------------------------------------------------
+
+def _matches_event(eb, event, pattern):
+ """``TestEventPattern`` over a whole event and a whole pattern — the call
+ every narrower helper below ends in."""
+ return eb.test_event_pattern(Event=json.dumps(event),
+ EventPattern=json.dumps(pattern))["Result"]
+
+
+def _pattern_matches(eb, detail_pattern, detail_value):
+ """A ``detail`` pattern fragment against a ``detail`` value."""
+ return _matches_event(eb, {"source": "wc.test", "detail-type": "T", "detail": detail_value},
+ {"source": ["wc.test"], "detail": detail_pattern})
+
+
+def _pattern_refused(eb, pattern):
+ """The reason the service gives for refusing ``pattern``, or ``None`` when it
+ accepts it. AWS validates a pattern at every API that takes one, so a
+ malformed operand is a ``400 InvalidEventPatternException`` rather than a
+ quiet non-match."""
+ try:
+ eb.test_event_pattern(
+ Event=json.dumps({"source": "v.test", "detail-type": "T", "detail": {"k": "x"}}),
+ EventPattern=json.dumps(pattern))
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "InvalidEventPatternException", exc
+ return exc.response["Error"]["Message"]
+ return None
+
+
+def _put_rule_refused(eb, pattern):
+ """The same question asked of PutRule, which must answer identically —
+ TestEventPattern is how you check a pattern before creating the rule, so the
+ two disagreeing would make it useless."""
+ try:
+ eb.put_rule(Name=f"qa-eb-reject-{_uuid_mod.uuid4().hex[:8]}",
+ EventPattern=json.dumps(pattern), State="ENABLED")
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "InvalidEventPatternException", exc
+ return exc.response["Error"]["Message"]
+ return None
+
+
+def _matcher_answer(pattern, detail=None, source="v.test"):
+ """What the matcher answers for a pattern that never went through
+ validation. That is the path a rule restored from persisted state takes —
+ it is loaded verbatim and never revalidated — so the fail-closed guards are
+ the only thing between a malformed operand and either a 500 out of
+ PutEvents or a rule that matches every event."""
+ event = {"Source": source, "DetailType": "T",
+ "Detail": json.dumps({} if detail is None else detail),
+ "Account": "000000000000", "Region": "us-east-1", "Resources": [],
+ "EventId": "id-1", "Time": "2026-08-14T00:00:00Z"}
+ return _eb._matches_pattern(json.dumps(pattern), event)
+
+
+def test_eventbridge_wildcard_matches_aws_semantics(eb):
+ """EventBridge wildcards special-case only '*', with '\\' as the escape
+ char; '?' and '[seq]' are literal (not fnmatch). Rows verified against real
+ AWS test-event-pattern."""
+ # (pattern, value, expected) — backslashes are single in the JSON operand.
+ assert _pattern_matches(eb, {"k": [{"wildcard": "*\\*"}]}, {"k": "zzz\\admin"}) is False
+ assert _pattern_matches(eb, {"k": [{"wildcard": "*\\\\*"}]}, {"k": "zzz\\admin"}) is True
+ assert _pattern_matches(eb, {"k": [{"wildcard": "a?c"}]}, {"k": "abc"}) is False
+ assert _pattern_matches(eb, {"k": [{"wildcard": "a[bc]d"}]}, {"k": "abd"}) is False
+ assert _pattern_matches(eb, {"k": [{"wildcard": "a[bc]d"}]}, {"k": "a[bc]d"}) is True
+ assert _pattern_matches(eb, {"k": [{"wildcard": "*.txt"}]}, {"k": "report.txt"}) is True
+
+
+def test_eventbridge_malformed_operand_is_refused_at_rule_creation(eb):
+ """A malformed operand is a 400 on AWS, from every API that takes a pattern,
+ and this used to be a Python raise surfacing as `500 InternalError` — from
+ TestEventPattern and from dispatch, where it aborted the whole PutEvents
+ rather than failing one rule."""
+ for bad in ({"k": [{"prefix": ["a", "b"]}]},
+ {"k": [{"suffix": 5}]},
+ {"k": [{"wildcard": 5}]},
+ {"k": [{"prefix": True}]}):
+ assert _pattern_refused(eb, {"source": ["v.test"], "detail": bad})
+ assert _put_rule_refused(eb, {"source": ["v.test"], "detail": bad})
+ # The message is the service's own text, not ours.
+ assert "wildcard match pattern must be a string" in _pattern_refused(
+ eb, {"detail": {"k": [{"wildcard": 5}]}})
+ assert "Only one key allowed in match expression" in _pattern_refused(
+ eb, {"detail": {"k": [{"prefix": "a", "suffix": "b"}]}})
+ assert "Unrecognized match type nonesuch" in _pattern_refused(
+ eb, {"detail": {"k": [{"nonesuch": "a"}]}})
+
+ # Behind that front door the matcher still has to fail closed, because a
+ # rule restored from persisted state is loaded verbatim and never
+ # revalidated.
+ for bad in ({"prefix": ["a", "b"]}, {"suffix": 5}, {"wildcard": 5}, {"nonesuch": "a"}):
+ assert _matcher_answer({"detail": {"k": [bad]}}, {"k": "x"}) is False
+
+ # anything-but: {wildcard: [...]} is a valid AWS form and still works.
+ assert _pattern_matches(
+ eb, {"k": [{"anything-but": {"wildcard": ["*/*"]}}]}, {"k": "no-slash"}
+ ) is True
+ assert _pattern_matches(
+ eb, {"k": [{"anything-but": {"wildcard": ["*/*"]}}]}, {"k": "has/slash"}
+ ) is False
+
+ # A non-string value against a string matcher is the other half of the
+ # guard, and it is about the EVENT rather than the pattern — so it stays a
+ # plain non-match, with no 400 anywhere.
+ for rule in ({"n": [{"wildcard": "5*"}]}, {"n": [{"prefix": "5"}]}, {"n": [{"suffix": "5"}]}):
+ assert _pattern_matches(eb, rule, {"n": 5}) is False
+
+
+def test_eventbridge_numeric_operand_grammar_is_enforced(eb):
+ """``numeric`` is a grammar, not a list of pairs: one comparison, or a lower
+ bound followed by an upper one. AWS rejects everything else at rule
+ creation, and each of these used to be either a `500 InternalError` — the
+ operand reached ``len()`` or ``float()`` unguarded — or, worse, a quiet
+ *true*, which made the rule match EVERY event and fan it out to its
+ targets."""
+ for bad in (5, "5", {"=": 5}, # not an array
+ [], [">"], [">", 1, "<"], # truncated
+ ["!!", 1], [[">"], 1], [{"a": 1}, 5], # bad operator slot
+ [">", "abc"], [">", True], [">", None], # non-numeric threshold
+ [">", 1, ">", 10], # second bound must be < or <=
+ ["=", 1, "<", 5], ["<", 10, ">", 1], # =, <, <= are terminal
+ [">", 1, "<", 10, ">", 2], # too many terms
+ [">", 10, "<", 1], [">", 5, "<", 5], # empty range
+ [">", 10 ** 400]): # not representable
+ assert _pattern_refused(eb, {"detail": {"k": [{"numeric": bad}]}})
+ # ...and the matcher declines it too, for a rule that never saw the door.
+ assert _matcher_answer({"detail": {"k": [{"numeric": bad}]}}, {"k": 5}) is False
+ assert "Value of numeric must be an array." in _pattern_refused(
+ eb, {"detail": {"k": [{"numeric": 5}]}})
+ assert "Bottom must be less than top" in _pattern_refused(
+ eb, {"detail": {"k": [{"numeric": [">", 10, "<", 1]}]}})
+ assert "Unrecognized numeric range operator: !!" in _pattern_refused(
+ eb, {"detail": {"k": [{"numeric": ["!!", 1]}]}})
+
+ # The forms AWS does accept.
+ assert _pattern_matches(eb, {"k": [{"numeric": [">", 10, "<=", 20]}]}, {"k": 15}) is True
+ assert _pattern_matches(eb, {"k": [{"numeric": ["=", 3.018e2]}]}, {"k": 301.8}) is True
+ # An oversized value out of the EVENT is not a pattern fault, so it stays a
+ # non-match rather than becoming a 400.
+ assert _pattern_matches(eb, {"k": [{"numeric": [">", 1]}]}, {"k": 10 ** 400}) is False
+
+
+def test_eventbridge_numeric_multi_condition_still_matches(eb):
+ """The guards must not cost the well-formed multi-condition form."""
+ between = {"k": [{"numeric": [">", 10, "<=", 20]}]}
+ assert _pattern_matches(eb, between, {"k": 15}) is True
+ assert _pattern_matches(eb, between, {"k": 20}) is True
+ assert _pattern_matches(eb, between, {"k": 10}) is False
+ assert _pattern_matches(eb, between, {"k": 25}) is False
+
+
+def test_eventbridge_anything_but_never_inverts_what_it_cannot_evaluate(eb):
+ """``anything-but`` inverts its nested matcher, so an operand the matcher can
+ only answer "no match" to becomes a rule matching EVERY event and fanning it
+ out to the rule's targets. The type guards made that strictly worse by
+ turning raises into exactly that "no match". AWS refuses all of these at
+ rule creation; the matcher declines rather than inverting."""
+ for bad in ({"prefix": 5}, {"suffix": ["a", 5]}, {"wildcard": 5}, {"numeric": 5},
+ {"wildcard": []}, {"prefix": ""}, {"equals-ignore-case": 5}):
+ assert _pattern_refused(eb, {"detail": {"k": [{"anything-but": bad}]}})
+ assert _matcher_answer({"detail": {"k": [{"anything-but": bad}]}}, {"k": "x"}) is False
+ assert "Null prefix/suffix not allowed" in _pattern_refused(
+ eb, {"detail": {"k": [{"anything-but": {"prefix": ""}}]}})
+ assert "Anything-But expression name not found" in _pattern_refused(
+ eb, {"detail": {"k": [{"anything-but": {}}]}})
+ # A mixed or empty literal list is refused with AWS's own wording.
+ for bad in (["x", 5], [], [1, "b"]):
+ assert "mixed type is not supported" in _pattern_refused(
+ eb, {"detail": {"k": [{"anything-but": bad}]}})
+ for bad in (["x", None], ["x", True], ["x", ["y"]]):
+ assert "start|null|boolean is not supported." in _pattern_refused(
+ eb, {"detail": {"k": [{"anything-but": bad}]}})
+ assert "Value of anything-but must be an array or single string/number value." in (
+ _pattern_refused(eb, {"detail": {"k": [{"anything-but": True}]}}))
+
+
+def test_eventbridge_anything_but_declines_mixed_nested_matchers(eb):
+ """A nested operand carrying two matcher keys is refused. The gate and the
+ matcher dispatch keys in different orders, so a mixed operand let the gate
+ approve on the well-formed key while the matcher answered on the malformed
+ one — and the inversion turned that back into match-everything."""
+ for mixed in ({"prefix": "x", "wildcard": "a*"}, {"suffix": "x", "numeric": [">", 5]},
+ {"prefix": "a", "equals-ignore-case": "b"},
+ {"anything-but": {"cidr": "10.0.0.0/8"}, "numeric": [">", 5]},
+ {"exists": True, "prefix": "a"}):
+ assert _pattern_refused(eb, {"detail": {"k": [{"anything-but": mixed}]}})
+ assert _matcher_answer({"detail": {"k": [{"anything-but": mixed}]}}, {"k": "zzz"}) is False
+
+
+def test_eventbridge_anything_but_still_inverts_well_formed_nested_operands(eb):
+ """The guard must not cost the forms it is protecting: every nested matcher
+ AWS allows — ``prefix``, ``suffix``, ``wildcard``, ``equals-ignore-case`` —
+ still inverts, in the single and the list form."""
+ assert _pattern_matches(eb, {"k": [{"anything-but": {"prefix": "init"}}]}, {"k": "running"}) is True
+ assert _pattern_matches(eb, {"k": [{"anything-but": {"prefix": "init"}}]}, {"k": "initial"}) is False
+ assert _pattern_matches(eb, {"k": [{"anything-but": {"suffix": ".txt"}}]}, {"k": "a.log"}) is True
+ assert _pattern_matches(eb, {"k": [{"anything-but": {"suffix": ".txt"}}]}, {"k": "a.txt"}) is False
+ listed = {"k": [{"anything-but": {"prefix": ["init", "pend"]}}]}
+ assert _pattern_matches(eb, listed, {"k": "running"}) is True
+ assert _pattern_matches(eb, listed, {"k": "pending"}) is False
+ assert _pattern_matches(eb, {"k": [{"anything-but": {"suffix": [".txt", ".log"]}}]},
+ {"k": "a.log"}) is False
+ # A literal and a list of literals are the plain forms.
+ assert _pattern_matches(eb, {"k": [{"anything-but": "x"}]}, {"k": "y"}) is True
+ assert _pattern_matches(eb, {"k": [{"anything-but": ["x", "y"]}]}, {"k": "y"}) is False
+ assert _pattern_matches(eb, {"k": [{"anything-but": [1, 2]}]}, {"k": 3}) is True
+
+
+def test_eventbridge_anything_but_refuses_operators_aws_will_not_nest(eb):
+ """``anything-but`` nests only ``prefix``, ``suffix``, ``wildcard`` and
+ ``equals-ignore-case``. ``cidr`` and ``numeric`` are evaluable everywhere
+ else, but AWS refuses them here at rule creation, so there is no positive
+ answer to invert — and inverting the "no match" they would otherwise give is
+ what turns a bad rule into one matching every event."""
+ for nested in ({"cidr": "10.0.0.0/8"}, {"numeric": [">", 10]},
+ {"exists": True}, {"anything-but": "x"}, {"exactly": "x"}):
+ reason = _pattern_refused(eb, {"detail": {"k": [{"anything-but": nested}]}})
+ assert "Unsupported anything-but pattern" in reason, reason
+ for value in ("10.1.2.3", "8.8.8.8", 7, 15):
+ assert _matcher_answer({"detail": {"k": [{"anything-but": nested}]}},
+ {"k": value}) is False
+
+
+def test_eventbridge_wildcard_anchors_whole_value(eb):
+ """The translator must anchor on ``\\Z``, not ``$``: Python's ``$`` also
+ matches just before a trailing newline, so ``*.txt`` would match
+ ``"report.txt\\n"``. fnmatch anchored this way too, so this pins a property
+ the emulator already had against a plausible way of losing it."""
+ assert _pattern_matches(eb, {"k": [{"wildcard": "*.txt"}]}, {"k": "report.txt\n"}) is False
+ assert _pattern_matches(eb, {"k": [{"wildcard": "abc"}]}, {"k": "abc\n"}) is False
+ assert _pattern_matches(eb, {"k": [{"wildcard": "abc"}]}, {"k": "abc"}) is True
+
+
+def test_eventbridge_wildcard_rejects_consecutive_stars_and_bad_escapes(eb):
+ """AWS refuses a run of ``*`` at rule creation, and reports the position as a
+ 1-based offset into the *quoted* operand counted in UTF-8 bytes — so the
+ opening quote is 0 and a multi-byte character before the fault shifts it."""
+ assert "Consecutive wildcard characters at pos 1" in _pattern_refused(
+ eb, {"detail": {"k": [{"wildcard": "**"}]}})
+ assert "Consecutive wildcard characters at pos 2" in _pattern_refused(
+ eb, {"detail": {"k": [{"wildcard": "a**z"}]}})
+ assert "Consecutive wildcard characters at pos 5" in _pattern_refused(
+ eb, {"detail": {"k": [{"wildcard": "\U0001f600**"}]}})
+ # A backslash may only escape ``*`` or another backslash. A trailing one
+ # escapes the closing quote AWS appends, which is why it reads as an invalid
+ # escape rather than a dangling one.
+ assert "Invalid escape character at pos 2" in _pattern_refused(
+ eb, {"detail": {"k": [{"wildcard": "a\\"}]}})
+ assert "Invalid escape character at pos 2" in _pattern_refused(
+ eb, {"detail": {"k": [{"wildcard": "a\\nb"}]}})
+ # The escapes that ARE legal stay legal, and a single ``*`` run is fine.
+ for good in ("*", "a*z", "*.txt", "a\\*b", "a\\\\b", ""):
+ assert _pattern_refused(eb, {"detail": {"k": [{"wildcard": good}]}}) is None
+ assert _matcher_answer({"detail": {"k": [{"wildcard": "a**z"}]}}, {"k": "a-mid-z"}) is False
+
+
+def test_eventbridge_wildcard_regex_collapses_star_runs_and_is_cached():
+ """A run of ``*`` translates to a single ``.*``. The compiled form is
+ cached because the translation otherwise reruns per event x rule x pattern
+ on the PutEvents hot path."""
+ assert _eb._wildcard_to_regex("*" * 20 + "x") == _eb._wildcard_to_regex("*x")
+ # An escaped '*' is a literal and must not be swallowed by the collapse.
+ assert _eb._wildcard_regex("a\\**b").match("a*mid-b") is not None
+ assert _eb._wildcard_regex("a\\**b").match("a-mid-b") is None
+
+ _eb._wildcard_regex.cache_clear()
+ _eb._wildcard_regex("qa-collapse-*")
+ _eb._wildcard_regex("qa-collapse-*")
+ assert _eb._wildcard_regex.cache_info().hits == 1
+
+
+def test_eventbridge_wildcard_does_not_backtrack_exponentially():
+ """A pattern of interior ``*``-separated literals against a long value that
+ just misses is the catastrophic-backtracking shape. fnmatch was immune
+ because ``fnmatch.translate`` emits ``(?=(?P<gN>.*?lit))(?P=gN)``; a naive
+ ``.*lit.*lit`` chain is not, and this runs per rule per event on the
+ dispatch path. ``*/*/…/*.json`` over a 165-character key took seconds
+ before the translator emitted the same construct.
+
+ The bound is deliberately loose — it is here to catch an exponential
+ blow-up, not to police constant factors on a busy machine."""
+ pattern = "*/" * 9 + "*.json"
+ value = "/".join(["seg"] * 40) + ".jsonX"
+ _eb._wildcard_regex.cache_clear()
+ _eb._wildcard_regex(pattern) # compile once, outside the measurement
+ started = time.monotonic()
+ assert _eb._matches_wildcard(value, pattern) is False
+ assert time.monotonic() - started < 1.0
+
+
+def _eb_badop_target(eb, sqs, bus, suffix, detail_pattern):
+ """Helper: queue + rule on ``bus`` filtering on ``detail_pattern``."""
+ return _eb_rule_to_queue(eb, sqs, f"badop-{suffix}",
+ {"source": ["myapp.badop"], "detail": detail_pattern}, bus)
+
+
+def test_eventbridge_hostile_event_value_does_not_break_dispatch(eb, sqs):
+ """On the PutEvents path a raising matcher took the whole call down as a
+ `500` — every other rule on the bus with it. Validation cannot help here:
+ these patterns are all valid, and it is the EVENT that is hostile, so the
+ matcher's guards are the only thing holding. An integer too large for a
+ double is the sharpest case, because ``float()`` answers that with
+ ``OverflowError``, which is neither ``TypeError`` nor ``ValueError``."""
+ bus = "qa-eb-badev-bus"
+ eb.create_event_bus(Name=bus)
+ q_numeric = _eb_badop_target(eb, sqs, bus, "numeric", {"n": [{"numeric": [">", 1]}]})
+ q_cidr = _eb_badop_target(eb, sqs, bus, "cidr", {"ip": [{"cidr": "10.0.0.0/24"}]})
+ q_prefix = _eb_badop_target(eb, sqs, bus, "prefix", {"s": [{"prefix": "a"}]})
+ q_ok = _eb_badop_target(eb, sqs, bus, "ok", {"id": [{"prefix": "ID-"}]})
+
+ resp = eb.put_events(Entries=[{
+ "Source": "myapp.badop", "DetailType": "t",
+ "Detail": json.dumps({
+ "id": "ID-1",
+ "n": 10 ** 400, # no double can hold it
+ "ip": 167772161, # the integer form of 10.0.0.1
+ "s": {"nested": "a"}, # an object where a string is expected
+ }),
+ "EventBusName": bus,
+ }])
+ assert resp["FailedEntryCount"] == 0
+
+ # The well-formed rule still delivers, proving the others were evaluated
+ # rather than skipped.
+ ok_msgs = sqs.receive_message(
+ QueueUrl=q_ok, MaxNumberOfMessages=10, WaitTimeSeconds=1).get("Messages") or []
+ assert len(ok_msgs) == 1
+ for q_url in (q_numeric, q_cidr, q_prefix):
+ assert not sqs.receive_message(
+ QueueUrl=q_url, MaxNumberOfMessages=10, WaitTimeSeconds=1).get("Messages")
+
+
+# ---------------------------------------------------------------------------
+# equals-ignore-case, cidr and $or
+# ---------------------------------------------------------------------------
+
+_DETAIL_OMITTED = object()
+
+
+def _event_matches(eb, pattern, detail=_DETAIL_OMITTED, source="op.test", detail_type="T"):
+ """Helper: TestEventPattern over a WHOLE pattern rather than just its
+ ``detail``, since ``$or`` is a top-level construct too. ``detail`` is left
+ out of the event unless given, so passing ``None`` means a JSON null — which
+ is a leaf, and a different answer from an absent or empty detail."""
+ event = {"source": source, "detail-type": detail_type}
+ if detail is not _DETAIL_OMITTED:
+ event["detail"] = detail
+ return _matches_event(eb, event, pattern)
+
+
+def test_eventbridge_equals_ignore_case_matches_whole_value(eb):
+ """``equals-ignore-case`` was accepted and then answered "no match" for
+ everything, so a rule guarding on it filtered out every event. It compares
+ the whole value — not a prefix — and only ever matches a string: a number
+ whose text equals the operand is a different JSON type and does not."""
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": "alice"}]}, {"k": "ALICE"}) is True
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": "alice"}]}, {"k": "Alice"}) is True
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": "aLiCe"}]}, {"k": "alice"}) is True
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": "alice"}]}, {"k": "alicex"}) is False
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": "alice"}]}, {"k": "xalice"}) is False
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": ""}]}, {"k": ""}) is True
+ for value in (123, True, None, ["ALICE"], {"a": "ALICE"}):
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": "123"}]}, {"k": value}) is False
+ # It works on the envelope fields too, not only inside detail.
+ assert _event_matches(eb, {"source": [{"equals-ignore-case": "OP.Test"}]}) is True
+
+
+def test_eventbridge_equals_ignore_case_folds_each_character_independently(eb):
+ """AWS lower- and upper-cases every operand character *on its own* and
+ accepts either form at that position, so a mapping that changes length
+ counts. That makes the relation neither ``lower()`` (which cannot match
+ ``straße`` against ``STRASSE`` at all, and would wrongly make the relation
+ symmetric) nor ``casefold()`` (which would wrongly accept ``strasse``).
+ Rows taken from aws/event-ruler, the engine EventBridge runs."""
+ strasse = {"k": [{"equals-ignore-case": "straße"}]}
+ assert _pattern_matches(eb, strasse, {"k": "STRASSE"}) is True
+ assert _pattern_matches(eb, strasse, {"k": "STRAßE"}) is True
+ assert _pattern_matches(eb, strasse, {"k": "strasse"}) is False
+ # Each position picks a case independently, but the form it picks is then
+ # literal: 'ß' contributes "SS", never "sS".
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": "maße"}]}, {"k": "MAsSE"}) is False
+ # Not symmetric: capital sharp s lowercases to 'ß', but 'ß' uppercases to
+ # "SS" and so never reaches U+1E9E.
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": "ẞ"}]}, {"k": "ß"}) is True
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": "ß"}]}, {"k": "ẞ"}) is False
+ # Same shape for the Kelvin sign, and 'fi' reaches "FI" but never "fi".
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": "K"}]}, {"k": "k"}) is True
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": "k"}]}, {"k": "K"}) is False
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": "fi"}]}, {"k": "FI"}) is True
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": "fi"}]}, {"k": "fi"}) is False
+ # Not even reflexive: a titlecase character is neither its own lower nor
+ # its own upper case.
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": "Dž"}]}, {"k": "Dž"}) is False
+ # Case mapping is locale-independent, so dotless 'ı' reaches 'I' but 'I'
+ # only ever reaches 'i'.
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": "ı"}]}, {"k": "I"}) is True
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": "I"}]}, {"k": "ı"}) is False
+ # A deliberate divergence: AWS walks UTF-16 code units and mangles an
+ # astral character into "?", so its own operand stops matching the value
+ # it was written for. Matching it is the useful answer, not the faithful
+ # one, and this pins which of the two this emulator gives.
+ assert _pattern_matches(eb, {"k": [{"equals-ignore-case": "\U0001f600"}]},
+ {"k": "\U0001f600"}) is True
+
+
+def test_eventbridge_equals_ignore_case_operand_must_be_a_string(eb):
+ """The operand reaches ``str`` methods, so a non-string one has to be turned
+ away before it raises — the class of bug that surfaced the other operators
+ as `500 InternalError`. AWS refuses it at rule creation; a list is legal only
+ under ``anything-but``."""
+ for bad in (5, None, True, {"a": "b"}, [], ["a"], ["a", 5]):
+ assert _pattern_refused(eb, {"detail": {"k": [{"equals-ignore-case": bad}]}})
+ assert _matcher_answer({"detail": {"k": [{"equals-ignore-case": bad}]}},
+ {"k": "a"}) is False
+ assert "equals-ignore-case match pattern must be a string" in _pattern_refused(
+ eb, {"detail": {"k": [{"equals-ignore-case": 5}]}})
+
+
+def test_eventbridge_anything_but_inverts_equals_ignore_case(eb):
+ """``equals-ignore-case`` is one of the four matchers AWS lets
+ ``anything-but`` nest, in both the single and the list form — the list
+ form being the one place AWS accepts a list operand at all."""
+ single = {"k": [{"anything-but": {"equals-ignore-case": "initializing"}}]}
+ assert _pattern_matches(eb, single, {"k": "INITIALIZING"}) is False
+ assert _pattern_matches(eb, single, {"k": "running"}) is True
+ listed = {"k": [{"anything-but": {"equals-ignore-case": ["initializing", "stopped"]}}]}
+ assert _pattern_matches(eb, listed, {"k": "STOPPED"}) is False
+ assert _pattern_matches(eb, listed, {"k": "Initializing"}) is False
+ assert _pattern_matches(eb, listed, {"k": "running"}) is True
+
+
+def test_eventbridge_cidr_matches_addresses_inside_the_block(eb):
+ """``cidr`` was accepted and answered "no match" for every address, so an
+ IP-range guard silently filtered out everything. Host bits in the operand
+ are floored the way AWS floors them, and IPv6 compares as addresses rather
+ than as text, so case and zero-compression do not matter."""
+ v4 = {"ip": [{"cidr": "10.0.0.0/24"}]}
+ assert _pattern_matches(eb, v4, {"ip": "10.0.0.5"}) is True
+ assert _pattern_matches(eb, v4, {"ip": "10.0.0.255"}) is True
+ assert _pattern_matches(eb, v4, {"ip": "10.0.1.5"}) is False
+ # Host bits set: AWS takes the floor of the range rather than rejecting.
+ floored = {"ip": [{"cidr": "10.0.0.5/24"}]}
+ assert _pattern_matches(eb, floored, {"ip": "10.0.0.0"}) is True
+ assert _pattern_matches(eb, floored, {"ip": "10.0.1.0"}) is False
+ assert _pattern_matches(eb, {"ip": [{"cidr": "0.0.0.0/0"}]}, {"ip": "8.8.8.8"}) is True
+ v6 = {"ip": [{"cidr": "2001:0DB8:0000::/32"}]}
+ assert _pattern_matches(eb, v6, {"ip": "2001:db8:0:0:0:0:0:1"}) is True
+ assert _pattern_matches(eb, v6, {"ip": "2001:DB8::1"}) is True
+ assert _pattern_matches(eb, v6, {"ip": "2001:db9::1"}) is False
+ # An address of the other family is not in the block. AWS's own engine
+ # leaks here — it compares the two as hex text, so an IPv4 /24 can match
+ # an IPv6 value whose leading digits fall inside it — and this does not
+ # reproduce that.
+ assert _pattern_matches(eb, v4, {"ip": "0a00:0000::"}) is False
+ assert _pattern_matches(eb, {"ip": [{"cidr": "::/0"}]}, {"ip": "10.0.0.5"}) is False
+ # Several blocks are written as sibling objects in the value list, which
+ # is also the only form AWS accepts.
+ either = {"ip": [{"cidr": "10.0.0.0/24"}, {"cidr": "192.168.0.0/24"}]}
+ assert _pattern_matches(eb, either, {"ip": "192.168.0.7"}) is True
+ assert _pattern_matches(eb, either, {"ip": "172.16.0.7"}) is False
+
+
+def test_eventbridge_cidr_operands_aws_rejects_are_refused(eb):
+ """Every row here fails rule creation on AWS, with the reason AWS gives.
+ ``/32`` and ``/128`` are the surprising ones: AWS caps the mask *below* the
+ address width, a single host being written as a plain equality value.
+ ``ipaddress`` would accept all but two of these, several silently — a bare
+ address as a ``/32``, a dotted netmask, a zone id."""
+ expectations = [
+ ("10.0.0.1/32", "IPv4 mask bits must be < 32"),
+ ("10.0.0.1/33", "IPv4 mask bits must be < 32"),
+ ("::1/128", "IPv6 mask bits must be < 128"),
+ ("10.0.0.1", "Malformed CIDR, one '/' required"),
+ ("", "Malformed CIDR, one '/' required"),
+ # A trailing slash leaves no mask field for AWS's split, so it reads as
+ # the missing-slash complaint rather than a bad-integer one.
+ ("10.0.0.0/", "Malformed CIDR, one '/' required"),
+ ("10.0.0.0/99999999999", "Malformed CIDR, mask bits must be an integer"),
+ ("10.0.0.0//24", "Malformed CIDR, one '/' required"),
+ ("10.0.0.0/xx", "Malformed CIDR, mask bits must be an integer"),
+ ("10.0.0.0/ 24", "Malformed CIDR, mask bits must be an integer"),
+ ("10.0.0.0/-1", "Malformed CIDR, mask bits must not be negative"),
+ ("10.0.0.0/255.255.255.0", "Malformed CIDR, mask bits must be an integer"),
+ ("999.1.1.1/24", "Invalid IP address: 999.1.1.1"),
+ ("example.com/24", "Nonstandard IP address: example.com"),
+ ("/24", "Nonstandard IP address: "),
+ ("10.0.0/24", "Nonstandard IP address: 10.0.0"),
+ ("::ffff:10.0.0.1/24", "Nonstandard IP address: ::ffff:10.0.0.1"),
+ ("fe80::1%eth0/64", "Nonstandard IP address: fe80::1%eth0"),
+ ("10.0.0.0/" + "1" * 4301, "Malformed CIDR, mask bits must be an integer"),
+ ]
+ for operand, reason in expectations:
+ refusal = _pattern_refused(eb, {"detail": {"ip": [{"cidr": operand}]}})
+ assert refusal and reason in refusal, (operand, refusal)
+ assert _matcher_answer({"detail": {"ip": [{"cidr": operand}]}},
+ {"ip": "10.0.0.1"}) is False
+ # A list operand is refused too — AWS takes exactly one block per object,
+ # and reports it against ``prefix``, which is its own copy-paste slip.
+ for bad in (["10.0.0.0/24"], 24, None, True, {"a": "10.0.0.0/24"}):
+ assert "prefix match pattern must be a string" in _pattern_refused(
+ eb, {"detail": {"ip": [{"cidr": bad}]}})
+ # The mask spellings AWS's integer parse does accept.
+ for operand in ("10.0.0.0/+24", "10.0.0.0/024", "1.2.3.4/-0", "10.0.0.0/31"):
+ assert _pattern_refused(eb, {"detail": {"ip": [{"cidr": operand}]}}) is None
+ assert _pattern_matches(eb, {"ip": [{"cidr": "10.0.0.0/+24"}]}, {"ip": "10.0.0.5"}) is True
+ assert _pattern_matches(eb, {"ip": [{"cidr": "1.2.3.4/-0"}]}, {"ip": "8.8.8.8"}) is True
+
+
+def test_eventbridge_cidr_never_reads_a_non_string_value_as_an_address(eb):
+ """``ipaddress`` accepts an integer as an address — ``167772161`` is
+ ``10.0.0.1`` and ``True`` is ``0.0.0.1`` — so an unguarded numeric or
+ boolean detail value would match a block that AWS, which matches only
+ JSON strings, never matches it against. Malformed strings are the other
+ half: they must answer "no match" rather than raise."""
+ for value in (167772161, 0, True, False, 1.5, None, {"ip": "10.0.0.5"}, [167772161]):
+ assert _pattern_matches(eb, {"ip": [{"cidr": "0.0.0.0/0"}]}, {"ip": value}) is False
+ # An array is a different matter — AWS flattens it and offers each element.
+ assert _pattern_matches(eb, {"ip": [{"cidr": "10.0.0.0/24"}]},
+ {"ip": ["8.8.8.8", "10.0.0.5"]}) is True
+ for value in ("not-an-ip", "", "10.0.0.5 ", "10.0.0.5/24", "10.0.0", "999.1.1.1"):
+ assert _pattern_matches(eb, {"ip": [{"cidr": "10.0.0.0/24"}]}, {"ip": value}) is False
+ # A leading-zero octet is decimal, as AWS reads it — not octal, and not a
+ # refusal, which is what Python's own address parser would give.
+ assert _pattern_matches(eb, {"ip": [{"cidr": "10.0.0.0/24"}]}, {"ip": "010.0.0.5"}) is True
+ assert _pattern_matches(eb, {"ip": [{"cidr": "0177.0.0.0/24"}]}, {"ip": "177.0.0.5"}) is True
+ assert _pattern_matches(eb, {"ip": [{"cidr": "0177.0.0.0/24"}]}, {"ip": "127.0.0.5"}) is False
+
+
+def test_eventbridge_or_matches_any_branch_and_ands_siblings(eb):
+ """A top-level ``$or`` was not read at all, so a pattern whose only key is
+ ``$or`` matched EVERY event and fanned it out to the rule's targets — the
+ same match-everything class as an inverted bad operand. Sibling keys still
+ AND with the branches."""
+ only_or = {"$or": [{"source": ["nope"]}, {"source": ["also-nope"]}]}
+ assert _event_matches(eb, only_or) is False
+ assert _event_matches(eb, {"$or": [{"source": ["op.test"]}, {"source": ["x"]}]}) is True
+
+ both = {"source": ["op.test"],
+ "$or": [{"detail": {"x": ["1"]}}, {"detail": {"y": ["2"]}}]}
+ assert _event_matches(eb, both, detail={"x": "1"}) is True
+ assert _event_matches(eb, both, detail={"y": "2"}) is True
+ assert _event_matches(eb, both, detail={"x": "9", "y": "9"}) is False
+ assert _event_matches(eb, both, detail={"x": "1"}, source="other") is False
+
+
+def test_eventbridge_or_inside_detail_matches_aws_documented_example(eb):
+ """``$or`` is a field-position keyword: legal wherever a field name is,
+ including inside ``detail`` and inside objects nested under it. This is
+ AWS's own documented example, verbatim."""
+ pattern = {"detail": {"$or": [
+ {"c-count": [{"numeric": [">", 0, "<=", 5]}]},
+ {"d-count": [{"numeric": ["<", 10]}]},
+ {"x-limit": [{"numeric": ["=", 3.018e2]}]},
+ ]}}
+ assert _event_matches(eb, pattern, detail={"c-count": 3}) is True
+ assert _event_matches(eb, pattern, detail={"d-count": 9}) is True
+ assert _event_matches(eb, pattern, detail={"x-limit": 301.8}) is True
+ assert _event_matches(eb, pattern, detail={"c-count": 9, "d-count": 99, "x-limit": 1}) is False
+ # A sibling of the nested $or still ANDs with it.
+ with_sibling = {"detail": {"$or": [{"a": ["1"]}, {"b": ["2"]}], "c": ["3"]}}
+ assert _event_matches(eb, with_sibling, detail={"a": "1", "c": "3"}) is True
+ assert _event_matches(eb, with_sibling, detail={"a": "1"}) is False
+ # ...and it nests as deep as the objects do.
+ deep = {"detail": {"inner": {"$or": [{"p": ["1"]}, {"q": ["2"]}]}}}
+ assert _event_matches(eb, deep, detail={"inner": {"q": "2"}}) is True
+ assert _event_matches(eb, deep, detail={"inner": {"r": "3"}}) is False
+
+
+def test_eventbridge_or_branches_and_their_own_keys_and_nest(eb):
+ """A branch is a whole pattern fragment: several keys in one branch AND
+ together, and a branch may carry its own ``$or``. Any operator is allowed
+ inside a branch — including ``exists: false``, which is the only one that
+ matches an absent field."""
+ anded = {"$or": [{"detail": {"m": ["1"], "n": ["2"]}}, {"detail": {"z": ["9"]}}]}
+ assert _event_matches(eb, anded, detail={"m": "1", "n": "2"}) is True
+ assert _event_matches(eb, anded, detail={"m": "1"}) is False
+ assert _event_matches(eb, anded, detail={"z": "9"}) is True
+
+ nested = {"$or": [{"$or": [{"source": ["b"]}, {"source": ["c"]}]}, {"source": ["d"]}]}
+ assert _event_matches(eb, nested, source="c") is True
+ assert _event_matches(eb, nested, source="d") is True
+ assert _event_matches(eb, nested, source="z") is False
+
+ operators = {"$or": [{"detail": {"a": [{"anything-but": "x"}]}},
+ {"detail": {"b": [{"exists": False}]}}]}
+ assert _event_matches(eb, operators, detail={"a": "y", "b": "present"}) is True
+ assert _event_matches(eb, operators, detail={"a": "x", "b": "present"}) is False
+ assert _event_matches(eb, operators, detail={"a": "x"}) is True
+
+
+def test_eventbridge_or_that_is_not_the_operator(eb):
+ """AWS reads ``$or`` as the operator only when it holds at least two
+ non-empty objects whose field names are not reserved matcher keywords. Every
+ other shape is retried against its pre-``$or`` compiler, which reads ``$or``
+ as an ordinary field name — so some shapes are refused outright and others
+ are accepted as a field the envelope does not have, which matches nothing.
+ Answering "matches" is the hole being closed here, so neither route may
+ fall back into it."""
+ for bad in ("x", 5, None, True, # not an array or object
+ [{"source": ["op.test"]}], # only one branch
+ [{}, {}], # empty branches
+ [],
+ [{"source": ["op.test"]}, "not-an-object"],
+ [{"prefix": "op."}, {"source": ["op.test"]}]): # reserved field name
+ assert _pattern_refused(eb, {"$or": bad}), bad
+ assert _pattern_refused(eb, {"source": ["op.test"], "$or": bad}), bad
+ assert _matcher_answer({"$or": bad}) is False
+
+ # Accepted, as an ordinary field named "$or" — which the event envelope has
+ # no member for, so it matches nothing.
+ for literal in ({"m": ["1"], "n": ["2"]}, ["a", "b"], [1, 2]):
+ assert _pattern_refused(eb, {"$or": literal}) is None, literal
+ assert _event_matches(eb, {"$or": literal}) is False
+
+ # $or is exactly those three characters. A case variant is an ordinary field
+ # name, which means its array elements are read as match expressions — and
+ # `{"a": [...]}` is not one, so the pattern is refused rather than merely
+ # never matching.
+ assert "Unrecognized match type a" in _pattern_refused(
+ eb, {"detail": {"$OR": [{"a": ["1"]}, {"b": ["2"]}]}})
+ # As a plain field it works like any other.
+ assert _event_matches(eb, {"detail": {"$OR": ["x"]}}, detail={"$OR": "x"}) is True
+ assert _event_matches(eb, {"detail": {"$OR": ["x"]}}, detail={"$OR": "y"}) is False
+
+
+def test_eventbridge_or_is_an_ordinary_field_name_inside_detail(eb):
+ """Inside ``detail`` the fallback means something different from the top
+ level: a detail payload really can carry a field called ``$or``, and AWS
+ matches it as one, so an unrecognized ``$or`` there is a field match
+ rather than an automatic failure."""
+ literal = {"detail": {"$or": ["hello"]}}
+ assert _event_matches(eb, literal, detail={"$or": "hello"}) is True
+ assert _event_matches(eb, literal, detail={"$or": "other"}) is False
+ assert _event_matches(eb, literal, detail={}) is False
+
+
+def test_eventbridge_unjudged_detail_value_does_not_match_every_content_filter(eb):
+ """A null- or object-valued detail field is neither a string, a number nor
+ an array, so it fell through the value-level dispatch entirely and was
+ never judged — and an unjudged key reads as a matched key. Every content
+ filter therefore matched such a field, so a rule guarding on one fired on
+ the events it was written to exclude. AWS matches a null against a literal
+ null and against ``anything-but``, an object against nothing at all."""
+ filters = ({"prefix": "a"}, {"suffix": "a"}, {"wildcard": "a*"}, {"numeric": [">", 1]},
+ {"equals-ignore-case": "null"}, {"cidr": "0.0.0.0/0"})
+ for rule in filters:
+ assert _pattern_matches(eb, {"k": [rule]}, {"k": None}) is False
+ assert _pattern_matches(eb, {"k": [rule]}, {"k": {"nested": "a"}}) is False
+ assert _pattern_matches(eb, {"k": ["a"]}, {"k": {"nested": "a"}}) is False
+ assert _pattern_matches(eb, {"k": [{"anything-but": "x"}]}, {"k": {"nested": "a"}}) is False
+ # A null is still a value: a literal null matches it, and anything-but
+ # inverts against it, both as on AWS.
+ assert _pattern_matches(eb, {"k": [None]}, {"k": None}) is True
+ assert _pattern_matches(eb, {"k": [{"anything-but": "x"}]}, {"k": None}) is True
+ # The well-formed cases these share a code path with are unaffected.
+ assert _pattern_matches(eb, {"k": [{"prefix": "a"}]}, {"k": "abc"}) is True
+ assert _pattern_matches(eb, {"k": ["v"]}, {"k": "v"}) is True
+ assert _pattern_matches(eb, {"k": [{"exists": True}]}, {"k": None}) is True
+ # An object is not a leaf, and AWS's operators only work on leaf nodes, so
+ # it does not "exist" for this purpose — see the dedicated exists test.
+ assert _pattern_matches(eb, {"k": [{"exists": True}]}, {"k": {"nested": "a"}}) is False
+ # A pattern object against an object value is a nested pattern, not a
+ # value-level filter, and still recurses.
+ assert _pattern_matches(eb, {"k": {"nested": ["a"]}}, {"k": {"nested": "a"}}) is True
+
+
+def test_eventbridge_anything_but_gate_approves_only_operands_the_matcher_reads():
+ """``_nested_matcher_ok`` approves a nested operand written as a pattern
+ string or as a list of them, for every operator ``anything-but`` may invert.
+ An operator that was approved here but whose matcher does not read the list
+ form could only answer "no match" to its own operand, and ``anything-but``
+ inverts that into a rule matching every event — the failure the gate exists
+ to prevent. So each nestable operator is exercised in both forms, and the set
+ is checked against the derived tuple so that a fifth operator cannot be added
+ without being exercised too — a name added to ``_ANYTHING_BUT_NESTABLE`` alone
+ would drop straight out of the derived tuple, which is what
+ ``test_eventbridge_every_accepted_operator_has_a_matcher`` refuses."""
+ operands = {"prefix": "ab", "suffix": "bc", "wildcard": "a*c",
+ "equals-ignore-case": "ABC"}
+ assert set(operands) == set(_eb._NESTED_MATCHER_KEYS)
+ for key, operand in operands.items():
+ for form in (operand, [operand]):
+ assert _eb._nested_matcher_ok({key: form}) is True, (key, form)
+ assert _eb._matches_content_filter("abc", {key: form}) is True, (key, form)
+ # And nothing else. Each of these is a "no match" from the matcher — a key
+ # ``anything-but`` cannot nest, an operand with nothing to exclude, a
+ # non-string operand, two keys at once — which the inversion would turn into
+ # a rule matching every event.
+ for declined in ({}, {"cidr": ["10.0.0.0/24"]}, {"cidr": "10.0.0.0/24"},
+ {"numeric": [">", 1]}, {"exactly": "abc"},
+ {"prefix": []}, {"prefix": [5]},
+ {"prefix": "a", "suffix": "b"}):
+ assert _eb._nested_matcher_ok(declined) is False, declined
+ assert _eb._matches_content_filter(
+ "anything at all", {"anything-but": declined}) is False, declined
+
+
+def test_eventbridge_every_accepted_operator_has_a_matcher():
+ """An operator validation accepts but the dispatch cannot answer matches
+ NOTHING for every event — the failure this change set exists to fix for
+ ``cidr``, ``equals-ignore-case``, ``exactly`` and the case-insensitive
+ affixes. ``exists`` is the one legal absence: it is answered from whether the
+ path reaches a leaf, in ``_matches_detail``, before any value reaches the
+ registry."""
+ assert set(_eb._MATCH_OPERATORS) - set(_eb._CONTENT_MATCHERS) == {"exists"}
+ assert set(_eb._CONTENT_MATCHERS) - set(_eb._MATCH_OPERATORS) == set()
+ # The same question for the nested position. ``_validate_anything_but``
+ # accepts whatever ``_ANYTHING_BUT_NESTABLE`` holds, while the gate scans the
+ # registry, so a name in one and not the other is an operand accepted at rule
+ # creation that the matcher can only answer "no match" to — which
+ # ``anything-but`` inverts into a rule matching every event.
+ assert set(_eb._ANYTHING_BUT_NESTABLE) <= set(_eb._CONTENT_MATCHERS)
+ assert set(_eb._AFFIX_NESTABLE) <= set(_eb._CONTENT_MATCHERS)
+
+
+def test_eventbridge_new_operators_dispatch_on_put_events(eb, sqs):
+ """The operators have to work on the PutEvents path too, not just through
+ TestEventPattern — that is where a matcher that raises takes down the
+ whole call, and where one that wrongly matches fans an event out to real
+ targets."""
+ bus = "qa-eb-newops-bus"
+ eb.create_event_bus(Name=bus)
+ q_cidr = _eb_badop_target(eb, sqs, bus, "cidr", {"ip": [{"cidr": "10.0.0.0/24"}]})
+ q_eic = _eb_badop_target(eb, sqs, bus, "eic", {"state": [{"equals-ignore-case": "running"}]})
+ q_miss = _eb_badop_target(eb, sqs, bus, "miss", {"ip": [{"cidr": "192.168.0.0/24"}]})
+
+ q_or_url = _eb_rule_to_queue(
+ eb, sqs, "newops-or",
+ {"source": ["myapp.badop"], "$or": [{"detail": {"state": ["never"]}},
+ {"detail": {"ip": [{"cidr": "10.0.0.0/8"}]}}]}, bus)
+
+ resp = eb.put_events(Entries=[{
+ "Source": "myapp.badop", "DetailType": "t",
+ "Detail": json.dumps({"ip": "10.0.0.7", "state": "RUNNING"}),
+ "EventBusName": bus,
+ }])
+ assert resp["FailedEntryCount"] == 0
+
+ for q_url in (q_cidr, q_eic, q_or_url):
+ msgs = sqs.receive_message(
+ QueueUrl=q_url, MaxNumberOfMessages=10, WaitTimeSeconds=1).get("Messages") or []
+ assert len(msgs) == 1
+ assert not sqs.receive_message(
+ QueueUrl=q_miss, MaxNumberOfMessages=10, WaitTimeSeconds=1).get("Messages")
+
+
+def test_eventbridge_hostile_pattern_never_escapes_the_matcher(eb):
+ """Anything that raises inside the matcher surfaces as `500 InternalError`
+ from TestEventPattern and, worse, aborts the whole `PutEvents` — every other
+ rule on the bus with it. Each shape below did exactly that. They are refused
+ at the door now, and the matcher answers "no match" for the same input,
+ which is the path a rule restored from persisted state takes."""
+ hostile = [
+ {"detail": {"ip": [{"cidr": "10.0.0.0/" + "1" * 4301}]}},
+ {"$or": [{"resources": 5}, {"source": ["never"]}]},
+ {"resources": None},
+ ]
+ for pattern in hostile:
+ assert _pattern_refused(eb, pattern), pattern
+ assert _matcher_answer(pattern) is False
+
+ # Past the depth bound the answer is "no match" rather than a raise. The
+ # innermost branch matches, so an unbounded walk would answer True — which
+ # pins the bound rather than merely surviving it. The deeper row is past what
+ # the handler's remaining stack can even JSON-decode, and has to come back
+ # the same way: the parse runs before any bound of ours, and a
+ # `RecursionError` let out of it damages more than its own request.
+ def nest(depth):
+ pattern = {"source": ["op.test"]}
+ for _ in range(depth):
+ pattern = {"$or": [pattern, {"source": ["other"]}]}
+ return pattern
+ assert _event_matches(eb, nest(5)) is True
+ assert _pattern_refused(eb, nest(60))
+ assert _matcher_answer(nest(60), source="op.test") is False
+ assert _matcher_answer(nest(300), source="op.test") is False
+ # ...and the server is still healthy afterwards, which is the part that
+ # matters: a stack exhausted on a pooled worker thread resurfaces in
+ # whatever that thread handles next.
+ assert _event_matches(eb, {"source": ["op.test"]}) is True
+
+ # A pattern that is not an object at all is not a pattern.
+ for shape in (["source"], "source", 5, None):
+ assert _pattern_refused(eb, shape), shape
+ assert "Filter is not an object" in _pattern_refused(eb, ["source"])
+ # Nor is an empty one, at any depth.
+ assert "Empty objects are not allowed" in _pattern_refused(eb, {})
+ assert "Empty objects are not allowed" in _pattern_refused(eb, {"detail": {}})
+ assert "Empty objects are not allowed" in _pattern_refused(eb, {"detail": {"a": {"b": {}}}})
+ assert "Empty arrays are not allowed" in _pattern_refused(eb, {"source": []})
+ assert '"source" must be an object or an array' in _pattern_refused(eb, {"source": "op.test"})
+
+
+def test_eventbridge_unmodelled_top_level_key_is_a_path_not_an_error(eb):
+ """AWS has no allow-list of top-level pattern fields — it compiles a pattern
+ to paths, so an unrecognized key is simply a path the event does not have.
+ That cuts both ways, and the second half is the part a fail-closed emulator
+ gets wrong: a value list can never be satisfied, but ``exists: false`` on
+ such a key is satisfied by EVERY event."""
+ for key in ("nonesuch", "Detail", "SOURCE", "detail-Type", "$and"):
+ assert _pattern_refused(eb, {key: ["anything"]}) is None, key
+ assert _event_matches(eb, {key: ["anything"]}) is False
+ assert _event_matches(eb, {key: [{"exists": False}]}) is True
+ assert _event_matches(eb, {key: [{"exists": True}]}) is False
+ # Sibling keys still AND, so one unsatisfiable key sinks the pattern.
+ assert _event_matches(eb, {"source": ["op.test"], "nonesuch": ["x"]}) is False
+ assert _event_matches(eb, {"source": ["op.test"], "nonesuch": [{"exists": False}]}) is True
+ # An envelope field may itself be written as an object path.
+ assert _event_matches(eb, {"source": {"x": ["y"]}}) is False
+ assert _event_matches(eb, {"source": {"x": [{"exists": False}]}}) is True
+
+
+def test_eventbridge_every_envelope_field_is_filterable(eb):
+ """All ten envelope fields can be filtered on, including the three the walk
+ used to skip entirely — a skipped key is a matched key, so a pattern
+ filtering on ``id``, ``time`` or ``version`` matched every event."""
+ event = {"version": "0", "id": "abc-123", "source": "op.test",
+ "account": "000000000000", "time": "2026-08-14T12:00:00Z",
+ "region": "us-east-1", "resources": ["arn:aws:x:::a"],
+ "detail-type": "T", "detail": {"k": "v"}}
+
+ assert _matches_event(eb, event, {"version": ["0"]}) is True
+ assert _matches_event(eb, event, {"version": ["9"]}) is False
+ assert _matches_event(eb, event, {"id": ["abc-123"]}) is True
+ assert _matches_event(eb, event, {"id": [{"prefix": "abc-"}]}) is True
+ assert _matches_event(eb, event, {"id": ["nope"]}) is False
+ # `time` is plain lexical text — there is no date handling anywhere.
+ assert _matches_event(eb, event, {"time": [{"prefix": "2026-08"}]}) is True
+ assert _matches_event(eb, event, {"time": [{"prefix": "2026-8"}]}) is False
+ assert _matches_event(eb, event, {"time": ["2026-08-14T12:00:00Z"]}) is True
+ # Values are type-strict: a string pattern does not match a numeric leaf.
+ assert _matches_event(eb, event, {"account": [000000000000]}) is False
+ assert _matches_event(eb, event, {"account": ["000000000000"]}) is True
+ # ...and case-sensitive, which is what equals-ignore-case is for.
+ assert _matches_event(eb, event, {"source": ["OP.TEST"]}) is False
+ assert _matches_event(eb, event, {"source": [{"equals-ignore-case": "OP.TEST"}]}) is True
+ # All ten at once, ANDed.
+ assert _matches_event(eb, event, {
+ "version": ["0"], "id": ["abc-123"], "source": ["op.test"],
+ "account": ["000000000000"], "time": [{"prefix": "2026"}],
+ "region": ["us-east-1"], "resources": ["arn:aws:x:::a"],
+ "detail-type": ["T"], "detail": {"k": ["v"]}}) is True
+
+
+def test_eventbridge_resources_is_an_intersection_not_a_requirement(eb):
+ """``resources`` is an array in the event, and AWS matches it the way it
+ matches any array: the pattern list is an OR and the field matches when the
+ intersection is non-empty. This required every pattern value to be present,
+ so a rule naming two ARNs matched no event carrying only one — and because
+ the check was plain equality, a content filter compared a dict against ARN
+ strings and could never match at all."""
+ event = {"source": "op.test", "detail-type": "T", "detail": {},
+ "resources": ["arn:a", "arn:b"]}
+
+ assert _matches_event(eb, event, {"resources": ["arn:a"]}) is True
+ assert _matches_event(eb, event, {"resources": ["arn:a", "arn:zzz"]}) is True
+ assert _matches_event(eb, event, {"resources": ["arn:zzz", "arn:b"]}) is True
+ assert _matches_event(eb, event, {"resources": ["arn:zzz"]}) is False
+ assert _matches_event(eb, event, {"resources": ["arn:zzz", "arn:yyy"]}) is False
+ # Content filters work on it, OR-ed over the event's elements.
+ assert _matches_event(eb, event, {"resources": [{"prefix": "arn:a"}]}) is True
+ assert _matches_event(eb, event, {"resources": [{"suffix": ":b"}]}) is True
+ assert _matches_event(eb, event, {"resources": [{"wildcard": "arn:*"}]}) is True
+ assert _matches_event(eb, event, {"resources": [{"prefix": "arn:z"}]}) is False
+ assert _matches_event(eb, event, {"resources": [{"exists": True}]}) is True
+ # anything-but is OR-ed over the elements too, so it means "some element is
+ # not this", not "no element is this".
+ assert _matches_event(eb, event, {"resources": [{"anything-but": ["arn:a"]}]}) is True
+ assert _matches_event(eb, event, {"resources": [{"anything-but": ["arn:a", "arn:b"]}]}) is False
+ # An empty array is indistinguishable from an absent field.
+ empty = {"source": "op.test", "detail-type": "T", "detail": {}, "resources": []}
+ assert _matches_event(eb, empty, {"resources": [{"exists": False}]}) is True
+ assert _matches_event(eb, empty, {"resources": [{"exists": True}]}) is False
+ assert _matches_event(eb, empty, {"resources": ["arn:a"]}) is False
+
+
+def test_eventbridge_cidr_admits_only_the_address_forms_aws_reads(eb):
+ """The value side needs the same admission test as the operand side: AWS
+ parses an address with one of two narrow grammars, while ``ipaddress``
+ also accepts a zone id and the dotted IPv4-mapped form, so a value in
+ either of those shapes matched a block AWS would not have read as an
+ address at all."""
+ assert _pattern_matches(eb, {"ip": [{"cidr": "fe80::/16"}]}, {"ip": "fe80::1%eth0"}) is False
+ assert _pattern_matches(eb, {"ip": [{"cidr": "::ffff:0:0/96"}]},
+ {"ip": "::ffff:10.0.0.1"}) is False
+ assert _pattern_matches(eb, {"ip": [{"cidr": "::ffff:0:0/96"}]},
+ {"ip": "::ffff:a00:1"}) is True
+
+
+def test_eventbridge_cidr_operand_admission_does_not_backtrack():
+ """The IPv6 admission pattern reads as two overlapping character classes
+ around a colon, which makes the match quadratic on a long colon-only
+ string — 100k characters took the better part of a minute, inside one
+ request, on the same dispatch hot path ``_wildcard_to_regex`` goes out of
+ its way to protect. The bound is loose on purpose: it is here to catch a
+ return to quadratic, not to police constant factors."""
+ _eb._cidr_network.cache_clear()
+ started = time.monotonic()
+ assert _eb._matches_cidr("10.0.0.1", ":" * 100_000 + "z/24") is False
+ assert time.monotonic() - started < 1.0
+
+
+# ---------------------------------------------------------------------------
+# exists, arrays, $or expansion, and the remaining operator forms
+# ---------------------------------------------------------------------------
+
+def test_eventbridge_exists_asks_whether_the_path_reaches_a_leaf(eb):
+ """AWS's operators "only work on leaf nodes", and ``exists`` is no exception:
+ it asks whether the path reaches a leaf, not whether the key is present. So
+ an object-valued field does not exist for this purpose, and neither does an
+ empty array or an empty object — all three are indistinguishable from a
+ missing key. A null *does* exist; it is a leaf."""
+ has_leaf = ("v", "", 0, False, None, ["a", "b"], [None])
+ no_leaf = ({"a": 1}, [], {}, [{"x": 1}], [[]])
+ for value in has_leaf:
+ assert _pattern_matches(eb, {"k": [{"exists": True}]}, {"k": value}) is True, value
+ assert _pattern_matches(eb, {"k": [{"exists": False}]}, {"k": value}) is False, value
+ for value in no_leaf:
+ assert _pattern_matches(eb, {"k": [{"exists": True}]}, {"k": value}) is False, value
+ assert _pattern_matches(eb, {"k": [{"exists": False}]}, {"k": value}) is True, value
+ # An absent key, and an absent parent chain.
+ assert _pattern_matches(eb, {"k": [{"exists": False}]}, {"other": 1}) is True
+ assert _pattern_matches(eb, {"k": [{"exists": True}]}, {"other": 1}) is False
+ assert _event_matches(eb, {"detail": {"a": {"b": [{"exists": False}]}}}) is True
+ # A nested pattern under a non-object value asks about the PATH, so
+ # exists:false is satisfied — the leaf is absent however malformed the
+ # branch above it is.
+ for detail in ("hello", 42, None, [], ["a"]):
+ assert _event_matches(eb, {"detail": {"state": [{"exists": False}]}},
+ detail=detail) is True
+ assert _event_matches(eb, {"detail": {"state": ["running"]}}, detail=detail) is False
+ # `detail` itself is a leaf when it is a scalar, and an object otherwise.
+ assert _event_matches(eb, {"detail": ["hello"]}, detail="hello") is True
+ assert _event_matches(eb, {"detail": [{"prefix": "hel"}]}, detail="hello") is True
+ assert _event_matches(eb, {"detail": [{"exists": True}]}, detail={"a": 1}) is False
+ assert _event_matches(eb, {"detail": [{"exists": True}]}, detail=None) is True
+
+
+def test_eventbridge_array_values_are_flattened_per_element(eb):
+ """AWS flattens an array value and offers each element to the matcher on its
+ own, so the field matches when ANY element does — and that applies to every
+ content filter, not just to plain literals. This matched arrays by literal
+ intersection only, so no operator was ever applied to their elements."""
+ for rule, value in (({"prefix": "ru"}, ["stopped", "running"]),
+ ({"suffix": "ing"}, ["stopped", "running"]),
+ ({"wildcard": "run*"}, ["x", "running"]),
+ ({"equals-ignore-case": "RUNNING"}, ["x", "running"]),
+ ({"cidr": "10.0.0.0/24"}, ["8.8.8.8", "10.0.0.5"]),
+ ({"numeric": [">", 10]}, [1, 99])):
+ assert _pattern_matches(eb, {"k": [rule]}, {"k": value}) is True, rule
+ assert _pattern_matches(eb, {"k": [{"prefix": "zz"}]}, {"k": ["a", "b"]}) is False
+ # Flattening is recursive, and elements keep their types.
+ assert _pattern_matches(eb, {"k": ["a"]}, {"k": [["a"]]}) is True
+ assert _pattern_matches(eb, {"k": ["123"]}, {"k": [123]}) is False
+ assert _pattern_matches(eb, {"k": [123]}, {"k": [123]}) is True
+ # An empty array offers nothing, so nothing matches it.
+ assert _pattern_matches(eb, {"k": [{"prefix": ""}]}, {"k": []}) is False
+ # anything-but is OR-ed over the elements too: it means "some element is not
+ # this", not "no element is this".
+ assert _pattern_matches(eb, {"k": [{"anything-but": "stopped"}]},
+ {"k": ["stopped", "running"]}) is True
+ assert _pattern_matches(eb, {"k": [{"anything-but": "stopped"}]},
+ {"k": ["stopped", "stopped"]}) is False
+
+
+def test_eventbridge_array_of_objects_matches_per_element(eb):
+ """A pattern object under a field whose value is an array of objects is
+ offered each element — and has to be satisfied by ONE of them. Two pattern
+ fields cannot be answered by two different elements, which is AWS's array
+ consistency rule."""
+ pattern = {"detail": {"items": {"sku": ["A"], "qty": [2]}}}
+ assert _event_matches(eb, pattern, detail={"items": [{"sku": "A", "qty": 2}]}) is True
+ assert _event_matches(eb, pattern,
+ detail={"items": [{"sku": "B", "qty": 9},
+ {"sku": "A", "qty": 2}]}) is True
+ # The two fields satisfied by DIFFERENT elements must not match.
+ assert _event_matches(eb, pattern,
+ detail={"items": [{"sku": "A", "qty": 9},
+ {"sku": "B", "qty": 2}]}) is False
+ single = {"detail": {"items": {"sku": ["A"]}}}
+ assert _event_matches(eb, single, detail={"items": [{"sku": "B"}, {"sku": "A"}]}) is True
+ assert _event_matches(eb, single, detail={"items": [{"sku": "B"}]}) is False
+
+
+def test_eventbridge_or_expands_with_last_write_wins(eb):
+ """``$or`` is expanded at rule creation, not evaluated at match time: each
+ branch is built by writing leaves into the alternatives accumulated so far,
+ so a leaf constrained both inside and outside a ``$or`` keeps only the LAST
+ value written, in document order. Writing the two keys the other way round
+ reverses the answers — which a recursive evaluator, being order-independent,
+ cannot reproduce."""
+ or_last = {"detail": {"a": ["1"], "$or": [{"a": ["2"]}, {"b": ["3"]}]}}
+ assert _event_matches(eb, or_last, detail={"a": "2"}) is True
+ assert _event_matches(eb, or_last, detail={"a": "1"}) is False
+ assert _event_matches(eb, or_last, detail={"a": "1", "b": "3"}) is True
+ assert _event_matches(eb, or_last, detail={"a": "2", "b": "3"}) is True
+
+ or_first = {"detail": {"$or": [{"a": ["2"]}, {"b": ["3"]}], "a": ["1"]}}
+ assert _event_matches(eb, or_first, detail={"a": "2"}) is False
+ assert _event_matches(eb, or_first, detail={"a": "1"}) is True
+ assert _event_matches(eb, or_first, detail={"a": "1", "b": "3"}) is True
+
+ # A DIFFERENT leaf merges rather than overwriting, at leaf granularity.
+ merged = {"detail": {"a": ["1"], "$or": [{"b": ["2"]}, {"c": ["3"]}]}}
+ assert _event_matches(eb, merged, detail={"a": "1", "b": "2"}) is True
+ assert _event_matches(eb, merged, detail={"b": "2"}) is False
+ assert _event_matches(eb, merged, detail={"a": "1", "c": "3"}) is True
+ # A duplicate key without any $or is the same rule, and json keeps the last.
+ assert _event_matches(eb, {"detail": {"a": ["1"], "b": ["2"]}},
+ detail={"a": "1", "b": "2"}) is True
+
+
+def test_eventbridge_or_combination_cap_is_enforced(eb):
+ """AWS refuses a pattern whose ``$or`` arrays multiply out to more than 1000
+ sub-patterns. Parallel ``$or`` at different paths multiply, so eleven of
+ arity two are 2048 — and expanding them is work done per rule per event on
+ the dispatch path, which is why the cap is a refusal and not a shrug."""
+ def parallel(count):
+ return {"detail": {f"f{i}": {"$or": [{"x": ["1"]}, {"y": ["1"]}]}
+ for i in range(count)}}
+ assert _pattern_refused(eb, parallel(9)) is None
+ refusal = _pattern_refused(eb, parallel(11))
+ assert refusal and "1000 rule combinations" in refusal, refusal
+ # A nested $or contributes its own arity rather than multiplying the outer
+ # one, so this stays small and is accepted.
+ nested = {"detail": {"$or": [{"a": ["1"]},
+ {"$or": [{"b": ["2"]}, {"c": ["3"]}]},
+ {"d": ["4"]}]}}
+ assert _pattern_refused(eb, nested) is None
+ assert _event_matches(eb, nested, detail={"c": "3"}) is True
+ assert _event_matches(eb, nested, detail={"z": "9"}) is False
+
+
+def test_eventbridge_case_insensitive_prefix_and_suffix(eb):
+ """``prefix`` and ``suffix`` take a nested ``equals-ignore-case``, which is
+ AWS's spelling of a case-insensitive affix. The same per-character case
+ alternation applies, so a length-changing mapping counts at the edges too."""
+ assert _pattern_matches(eb, {"k": [{"prefix": {"equals-ignore-case": "EventB"}}]},
+ {"k": "eventbridge"}) is True
+ assert _pattern_matches(eb, {"k": [{"prefix": {"equals-ignore-case": "EventB"}}]},
+ {"k": "notevent"}) is False
+ assert _pattern_matches(eb, {"k": [{"suffix": {"equals-ignore-case": ".PNG"}}]},
+ {"k": "photo.png"}) is True
+ assert _pattern_matches(eb, {"k": [{"suffix": {"equals-ignore-case": ".PNG"}}]},
+ {"k": "photo.jpg"}) is False
+ assert _pattern_matches(eb, {"k": [{"prefix": {"equals-ignore-case": "straße"}}]},
+ {"k": "STRASSEN"}) is True
+ # A plain affix stays case-sensitive.
+ assert _pattern_matches(eb, {"k": [{"prefix": "EventB"}]}, {"k": "eventbridge"}) is False
+ # Only equals-ignore-case may nest there.
+ assert "Unsupported prefix pattern: suffix" in _pattern_refused(
+ eb, {"detail": {"k": [{"prefix": {"suffix": "a"}}]}})
+ assert "Prefix expression name not found" in _pattern_refused(
+ eb, {"detail": {"k": [{"prefix": {}}]}})
+
+
+def test_eventbridge_empty_affix_is_refused_only_under_anything_but(eb):
+ """``Null prefix/suffix not allowed`` is AWS's rule for ``anything-but``'s
+ nested affix and for nothing else: a plain ``{"prefix": ""}`` compiles.
+ An affix is matched against the QUOTED form of the value, so the empty operand
+ is the quote itself — the opening one for ``prefix``, the closing one for
+ ``suffix`` — and the rule reads "this field is a string" rather than filtering
+ nothing. Reading the asymmetry as a bug and hoisting
+ the refusal into the shared affix validator would reject a pattern real AWS
+ accepts."""
+ for affix in ({"prefix": ""}, {"suffix": ""},
+ {"prefix": {"equals-ignore-case": ""}},
+ {"suffix": {"equals-ignore-case": ""}}):
+ assert _pattern_refused(eb, {"detail": {"k": [affix]}}) is None, affix
+ # Every string, the empty one included; no number, boolean, null or
+ # object — and an array matches through its string elements.
+ assert _pattern_matches(eb, {"k": [affix]}, {"k": "foo"}) is True, affix
+ assert _pattern_matches(eb, {"k": [affix]}, {"k": ""}) is True, affix
+ for value in (5, True, None, {"n": 1}):
+ assert _pattern_matches(eb, {"k": [affix]}, {"k": value}) is False, (affix, value)
+ assert _pattern_matches(eb, {"k": [affix]}, {"k": ["foo", 5]}) is True, affix
+ # The refusal keeps its own position, and the list form reaches it too.
+ reason = _pattern_refused(eb, {"detail": {"k": [{"anything-but": {"prefix": [""]}}]}})
+ assert reason and "Null prefix/suffix not allowed" in reason, reason
+
+
+def test_eventbridge_affix_type_complaint_names_its_own_position(eb):
+ """AWS reports a non-string affix operand differently depending on where it
+ sits: the top-level branches name the one operator they read, while
+ ``anything-but`` handles both in a single branch and says
+ ``prefix/suffix``. Both wordings are the service's own, so unifying them
+ would send text AWS never sends in either position."""
+ assert "Reason: prefix match pattern must be a string" in _pattern_refused(
+ eb, {"detail": {"k": [{"prefix": 5}]}})
+ assert "Reason: suffix match pattern must be a string" in _pattern_refused(
+ eb, {"detail": {"k": [{"suffix": 5}]}})
+ for bad in ({"prefix": 5}, {"suffix": 5}, {"prefix": [5]}):
+ reason = _pattern_refused(eb, {"detail": {"k": [{"anything-but": bad}]}})
+ assert "prefix/suffix match pattern must be a string" in reason, (bad, reason)
+ # A nested affix operand is reported against ``equals-ignore-case``, whose
+ # operand it actually is.
+ assert "equals-ignore-case match pattern must be a string" in _pattern_refused(
+ eb, {"detail": {"k": [{"prefix": {"equals-ignore-case": 5}}]}})
+
+
+def test_eventbridge_exactly_operator_is_an_explicit_equality(eb):
+ """``exactly`` is Event Ruler's spelling of a plain equality value, and it is
+ a reserved name inside ``$or`` for that reason."""
+ assert _pattern_matches(eb, {"k": [{"exactly": "running"}]}, {"k": "running"}) is True
+ assert _pattern_matches(eb, {"k": [{"exactly": "running"}]}, {"k": "RUNNING"}) is False
+ assert _pattern_matches(eb, {"k": [{"exactly": "5"}]}, {"k": 5}) is False
+ assert "exact match pattern must be a string" in _pattern_refused(
+ eb, {"detail": {"k": [{"exactly": 5}]}})
+
+
+def test_eventbridge_pattern_values_compare_as_json_not_as_text(eb):
+ """AWS compares a pattern value against an event value as JSON, so a string
+ never equals a number and ``true`` never equals ``1`` — where Python holds
+ ``True == 1``. Coercing the two to text instead made a rule match values of
+ a type it never named."""
+ assert _pattern_matches(eb, {"k": ["5"]}, {"k": 5}) is False
+ assert _pattern_matches(eb, {"k": [5]}, {"k": "5"}) is False
+ assert _pattern_matches(eb, {"k": [5]}, {"k": 5}) is True
+ assert _pattern_matches(eb, {"k": [1]}, {"k": True}) is False
+ assert _pattern_matches(eb, {"k": [True]}, {"k": 1}) is False
+ assert _pattern_matches(eb, {"k": [True]}, {"k": True}) is True
+ assert _pattern_matches(eb, {"k": [None]}, {"k": None}) is True
+ assert _pattern_matches(eb, {"k": ["None"]}, {"k": None}) is False
+
+
+def test_eventbridge_replay_name_marks_replayed_events(eb):
+ """AWS stamps a replayed event with the replay's name, and its own archive
+ managed rule — ``{"replay-name": [{"exists": false}]}`` — is how an archive
+ avoids capturing its own replays. The field was never populated, so that
+ rule could not tell replayed traffic from live."""
+ live = {"source": "op.test", "detail-type": "T", "detail": {}}
+ replayed = dict(live, **{"replay-name": "my-replay"})
+
+ assert _matches_event(eb, live, {"replay-name": [{"exists": False}]}) is True
+ assert _matches_event(eb, replayed, {"replay-name": [{"exists": False}]}) is False
+ assert _matches_event(eb, replayed, {"replay-name": [{"exists": True}]}) is True
+ assert _matches_event(eb, replayed, {"replay-name": ["my-replay"]}) is True
+ assert _matches_event(eb, replayed, {"replay-name": ["other"]}) is False
+
+
+def test_eventbridge_replay_name_is_stamped_by_start_replay(eb, sqs):
+ """The assertions above pose the question to ``TestEventPattern`` with the
+ field written by hand, so they pass whether or not anything ever stamps it.
+ This is the one that fails if the stamping regresses: a real archive, a real
+ replay, and AWS's own "live traffic only" rule on the receiving end."""
+ slug = _uuid_mod.uuid4().hex[:8]
+ bus = f"qa-eb-replayname-{slug}-bus"
+ eb.create_event_bus(Name=bus)
+ bus_arn = eb.describe_event_bus(Name=bus)["Arn"]
+ q_url = _eb_rule_to_queue(
+ eb, sqs, f"replayname-{slug}",
+ {"source": ["op.replay"], "replay-name": [{"exists": False}]}, bus)
+
+ archive = f"qa-eb-replayname-{slug}"
+ eb.create_archive(ArchiveName=archive, EventSourceArn=bus_arn)
+ eb.put_events(Entries=[{"Source": "op.replay", "DetailType": "T",
+ "Detail": json.dumps({"n": 1}), "EventBusName": bus}])
+ live = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=10,
+ WaitTimeSeconds=2).get("Messages", [])
+ assert len(live) == 1, "the live event must reach the exists:false rule"
+ sqs.delete_message(QueueUrl=q_url, ReceiptHandle=live[0]["ReceiptHandle"])
+
+ from datetime import datetime, timedelta, timezone
+ now = datetime.now(timezone.utc)
+ eb.start_replay(
+ ReplayName=f"qa-eb-replay-{slug}",
+ EventSourceArn=eb.describe_archive(ArchiveName=archive)["ArchiveArn"],
+ EventStartTime=now - timedelta(days=1),
+ EventEndTime=now + timedelta(days=1),
+ # Must be the archive's own source bus, or StartReplay refuses it.
+ Destination={"Arn": bus_arn})
+
+ # The replayed event carries replay-name, so the rule must decline it. Polling
+ # rather than sleeping: the replay dispatches on a background thread, and an
+ # arrival at any point is the regression.
+ deadline = time.monotonic() + 5
+ while time.monotonic() < deadline:
+ again = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=10,
+ WaitTimeSeconds=1).get("Messages", [])
+ assert not again, f"replayed event reached a live-traffic-only rule: {again}"
+
+
+def test_eventbridge_archive_apis_validate_their_event_pattern(eb):
+ """Every API that takes a pattern validates it, not just PutRule — otherwise
+ a pattern refused at one door gets in through another and the rule that
+ carries it can never be created but can be archived on."""
+ bus = f"qa-eb-archive-validate-{_uuid_mod.uuid4().hex[:8]}"
+ eb.create_event_bus(Name=bus)
+ bus_arn = eb.describe_event_bus(Name=bus)["Arn"]
+ bad = json.dumps({"detail": {"k": [{"numeric": [">"]}]}})
+
+ with pytest.raises(ClientError) as created:
+ eb.create_archive(ArchiveName=f"qa-arch-{_uuid_mod.uuid4().hex[:8]}",
+ EventSourceArn=bus_arn, EventPattern=bad)
+ assert created.value.response["Error"]["Code"] == "InvalidEventPatternException"
+
+ name = f"qa-arch-ok-{_uuid_mod.uuid4().hex[:8]}"
+ eb.create_archive(ArchiveName=name, EventSourceArn=bus_arn,
+ EventPattern=json.dumps({"source": ["op.test"]}))
+ with pytest.raises(ClientError) as updated:
+ eb.update_archive(ArchiveName=name, EventPattern=bad)
+ assert updated.value.response["Error"]["Code"] == "InvalidEventPatternException"
+ # The good pattern survived the failed update.
+ assert json.loads(eb.describe_archive(ArchiveName=name)["EventPattern"]) == {
+ "source": ["op.test"]}
+
+
+def _raw_event(source="op.test", detail='{"k": "v"}', **extra):
+ """A stored event in the shape ``_pattern_event_view`` reads."""
+ return {"Source": source, "DetailType": "T", "Detail": detail,
+ "Resources": [], "Time": 1_760_000_000, **extra}
+
+
+def test_eventbridge_compiled_pattern_is_cached_and_caches_refusals():
+ """A pattern is parsed and expanded once, not once per event: this runs per
+ rule per event on the dispatch path, and expanding a ``$or`` allocates. A
+ refusal is cached too, as ``None`` — a rule restored from persisted state
+ carries its pattern verbatim, so an unacceptable one would otherwise be
+ re-compiled and re-refused for every event on the bus."""
+ _eb._compiled_pattern.cache_clear()
+ good = json.dumps({"source": ["qa.cache"], "detail": {"k": [{"prefix": "a"}]}})
+ assert _eb._compiled_pattern(good) is not None
+ assert _eb._compiled_pattern(good) is not None
+ assert _eb._compiled_pattern.cache_info().hits == 1
+
+ bad = json.dumps({"source": []})
+ assert _eb._compiled_pattern(bad) is None
+ assert _eb._compiled_pattern(bad) is None
+ assert _eb._compiled_pattern.cache_info().hits == 2
+ # Dispatch builds the event view once and reuses it across rules, so the
+ # two halves have to be separable.
+ view = _eb._pattern_event_view(_raw_event("qa.cache", json.dumps({"k": "abc"})))
+ assert _eb._matches_pattern_view(good, view) is True
+ assert _eb._matches_pattern_view(bad, view) is False
+
+
+def test_eventbridge_matcher_takes_the_pattern_as_json_text_only():
+ """The matcher's pattern argument is JSON text — the form the API takes a
+ pattern in and the form the rule and archive stores keep — and anything else
+ is a non-match. Rule records are not all written by PutRule: a CloudFormation
+ template's pattern is only stringified when it is an object, and persisted
+ state is restored without revalidation, so an unhashable EventPattern can
+ reach the matcher, and the compiler is memoized — handing one to lru_cache
+ raises TypeError, which out of dispatch is a 500 on the whole PutEvents batch
+ rather than one skipped rule."""
+ view = _eb._pattern_event_view(_raw_event("qa.nontext", json.dumps({"k": "abc"})))
+ assert _eb._matches_pattern_view(json.dumps({"source": ["qa.nontext"]}), view) is True
+ for not_text in ({"source": ["qa.nontext"]}, ["qa.nontext"], 7, None):
+ assert _eb._matches_pattern_view(not_text, view) is False
+
+
+def test_eventbridge_reset_clears_the_pattern_compilation_caches():
+ """``reset()`` must drop the compilation memos along with the stores. Each is
+ keyed on values a caller sent — a pattern, a wildcard operand, a cidr block,
+ an event ``time`` — and nothing else evicts an entry below the 1024-entry
+ cap, so a run of distinct TestEventPattern calls pins them all: an expanded
+ near-cap ``$or`` retains a few hundred times the bytes of its own source. Reset
+ has already dropped every rule that could want a result, so keeping them is
+ memory that comes back to no one."""
+ caches = (_eb._compiled_pattern, _eb._wildcard_regex,
+ _eb._cidr_network, _eb._iso_time)
+ # One match seeds all four: the view renders the event time, and reaching the
+ # operators is what compiles their operands.
+ assert _eb._matches_pattern(
+ json.dumps({"source": ["qa.reset"],
+ "detail": {"w": [{"wildcard": "a*b"}],
+ "ip": [{"cidr": "10.0.0.0/24"}]}}),
+ _raw_event("qa.reset", json.dumps({"w": "aXb", "ip": "10.0.0.7"})),
+ ) is True
+ seeded = {cache.__name__: cache.cache_info().currsize for cache in caches}
+ assert all(seeded.values()), seeded
+
+ _eb.reset()
+ assert ({cache.__name__: cache.cache_info().currsize for cache in caches}
+ == dict.fromkeys(seeded, 0))
+
+
+def test_eventbridge_numeric_applies_to_json_numbers_only(eb):
+ """A numeric operator applies to a JSON number and nothing else. Python
+ converts the text ``"50"`` and the boolean ``true`` happily, so without a
+ type check a numeric threshold matched values of a type the rule never
+ named — and a rule written to bound an amount fired on a string."""
+ below = {"amount": [{"numeric": ["<", 100]}]}
+ assert _pattern_matches(eb, below, {"amount": 50}) is True
+ assert _pattern_matches(eb, below, {"amount": 50.5}) is True
+ assert _pattern_matches(eb, below, {"amount": "50"}) is False
+ assert _pattern_matches(eb, below, {"amount": True}) is False
+ assert _pattern_matches(eb, below, {"amount": None}) is False
+ assert _pattern_matches(eb, below, {"amount": ["50"]}) is False
+ assert _pattern_matches(eb, below, {"amount": [50]}) is True
+
+
+def test_eventbridge_or_leaf_and_object_at_one_path_cannot_be_satisfied(eb):
+ """AWS keys its expanded sub-patterns by the full path, so a path constrained
+ both as a leaf and as an object keeps BOTH constraints — and no event is
+ both, so that alternative matches nothing. Dropping one side instead would
+ quietly widen the rule."""
+ leaf_then_object = {"detail": {"a": ["1"], "$or": [{"a": {"b": ["2"]}}, {"z": ["9"]}]}}
+ assert _event_matches(eb, leaf_then_object, detail={"a": "1"}) is False
+ assert _event_matches(eb, leaf_then_object, detail={"a": {"b": "2"}}) is False
+ # The other branch is unaffected and still matches.
+ assert _event_matches(eb, leaf_then_object, detail={"a": "1", "z": "9"}) is True
+
+ object_then_leaf = {"detail": {"a": {"b": ["1"]}, "$or": [{"a": ["2"]}, {"c": ["3"]}]}}
+ assert _event_matches(eb, object_then_leaf, detail={"a": "2"}) is False
+ assert _event_matches(eb, object_then_leaf, detail={"a": {"b": "1"}}) is False
+ assert _event_matches(eb, object_then_leaf, detail={"a": {"b": "1"}, "c": "3"}) is True
+
+
+def test_eventbridge_or_cap_counts_aws_documented_product(eb):
+ """AWS documents the cap as the product of every ``$or`` array's length. A
+ nested ``$or`` produces fewer alternatives than that product, so counting
+ only the alternatives would accept a pattern AWS refuses — the direction that
+ costs a surprise in production. Both counts are checked."""
+ def chain(depth):
+ pattern = {"a": ["1"]}
+ for _ in range(depth):
+ pattern = {"$or": [pattern, {"b": ["2"]}]}
+ return {"detail": pattern}
+ assert _pattern_refused(eb, chain(9)) is None
+ refusal = _pattern_refused(eb, chain(10))
+ assert refusal and "1000 rule combinations" in refusal, refusal
+
+
+def test_eventbridge_or_cap_counts_a_field_named_or_too(eb):
+ """AWS states the cap as a product over the ``$or`` arrays the pattern text
+ holds — a question the text answers on its own, without being compiled — so
+ it is counted before the ``$or``-aware compiler runs and outside the retry
+ that re-reads ``$or`` as an ordinary field name. These arrays hold only
+ reserved names, so that retry is the whole reason nine of them are legal, and
+ it would have made ten legal too. Ten are refused anyway: where the two
+ readings disagree, refusing costs a wall here, and accepting risks a rule that
+ passes locally and is refused at ``PutRule`` in production."""
+ def reserved(count):
+ return {"detail": {f"f{i}": {"$or": [{"prefix": "a"}, {"suffix": "b"}]}
+ for i in range(count)}}
+ # Nine multiply out to 512 and are accepted — as nine fields literally called
+ # "$or", which a detail payload really can carry.
+ assert _pattern_refused(eb, reserved(9)) is None
+ one = {"f0": {"$or": [{"prefix": "a"}, {"suffix": "b"}]}}
+ assert _pattern_matches(eb, one, {"f0": {"$or": "abc"}}) is True
+ assert _pattern_matches(eb, one, {"f0": {"$or": "zzb"}}) is True
+ assert _pattern_matches(eb, one, {"f0": {"$or": "zzz"}}) is False
+ # Ten multiply out to 1024 — the first count past the cap, so this is the
+ # boundary itself rather than a number comfortably beyond it. The reason is
+ # the count, not anything the branches contain.
+ refusal = _pattern_refused(eb, reserved(10))
+ assert refusal and "1000 rule combinations" in refusal, refusal
+ assert _pattern_refused(eb, reserved(11)) is not None
+
+
+def test_eventbridge_non_json_numeric_literals_are_refused(eb):
+ """``NaN``/``Infinity``/``-Infinity`` are Python decoder extensions, not JSON.
+ AWS parses a pattern with Jackson, which refuses them, so accepting one here
+ would leave a pattern that is a `400` in production matching nothing locally —
+ the silence this whole change exists to remove. A literal that IS valid JSON
+ and merely overflows a double (``1e400``) stays accepted."""
+ def refusal(pattern_text):
+ """Asked with raw pattern TEXT: ``1e400`` is a JSON literal Python cannot
+ round-trip through a float, so json.dumps of a dict cannot pose this."""
+ try:
+ eb.test_event_pattern(
+ Event=json.dumps({"source": "v.test", "detail-type": "T",
+ "detail": {"a": 1}}),
+ EventPattern=pattern_text)
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "InvalidEventPatternException", exc
+ return exc.response["Error"]["Message"]
+ return None
+
+ for literal in ("NaN", "Infinity", "-Infinity"):
+ reason = refusal('{"detail": {"a": [' + literal + ']}}')
+ assert reason and "Invalid JSON" in reason, (literal, reason)
+ assert refusal('{"detail": {"a": [1e400]}}') is None
+ assert refusal('{"detail": {"a": [1]}}') is None
+
+
+def test_eventbridge_unmodelled_top_level_key_is_matchable_not_dropped(eb):
+ """AWS compiles a pattern to a set of paths and has no envelope allow-list, so
+ a ``TestEventPattern`` event carrying an unmodelled top-level key must be
+ matchable on it. Dropping the key would answer "no match" for a pattern AWS
+ satisfies — and would quietly contradict the ``exists`` reading below, which
+ is the same claim from the other side."""
+ carried = {"source": "v.test", "detail-type": "T", "detail": {}, "nonesuch": "x"}
+ bare = {"source": "v.test", "detail-type": "T", "detail": {}}
+ assert _matches_event(eb, carried, {"nonesuch": ["x"]}) is True
+ assert _matches_event(eb, carried, {"nonesuch": ["y"]}) is False
+ assert _matches_event(eb, bare, {"nonesuch": ["x"]}) is False
+ assert _matches_event(eb, bare, {"nonesuch": [{"exists": False}]}) is True
+ # A modelled name cannot be shadowed by the caller's spelling of it.
+ assert _matches_event(eb, dict(carried, Source="evil"), {"source": ["v.test"]}) is True
+
+
+def test_eventbridge_dotted_pattern_key_is_a_distinct_segment(eb):
+ """A deliberate divergence: AWS resolves ``{"a.b": [...]}`` to the same path as
+ the nested spelling, where a key holding a dot stays one segment here. Pinned
+ so the CHANGELOG's divergence list is self-checking rather than asserted."""
+ dotted = {"a.b": ["v"]}
+ assert _pattern_matches(eb, dotted, {"a": {"b": "v"}}) is False
+ assert _pattern_matches(eb, dotted, {"a.b": "v"}) is True
+ assert _pattern_matches(eb, {"a": {"b": ["v"]}}, {"a": {"b": "v"}}) is True
+
+
+def test_eventbridge_pattern_nesting_bound_clears_real_patterns(eb):
+ """The depth bound is ours, not AWS's — it keeps compilation and matching off
+ the end of a pooled worker thread's stack. It has to sit above anything a
+ real pattern expresses: AWS's documented 4096-character limit allows a few
+ hundred levels of one-character keys, so a few dozen must be fine."""
+ def deep(depth):
+ pattern = {"k": ["v"]}
+ for _ in range(depth):
+ pattern = {"a": pattern}
+ return {"detail": pattern}
+ for depth in (10, 52, 80):
+ assert _pattern_refused(eb, deep(depth)) is None, depth
+ assert _pattern_refused(eb, deep(150))
+
+
+def test_eventbridge_validator_reports_the_reason_aws_reports(eb):
+ """The reason text is the service's own, and which reason it is depends on
+ the order AWS's parser reaches things: it dispatches on the first key of a
+ match expression and consumes that operand before it can see a second key,
+ and it walks an ``anything-but`` list element by element. So a two-key
+ expression whose first operand is also wrong reports the operand."""
+ rows = [
+ ({"k": [{"exists": "x", "y": 1}]}, "exists match pattern must be either true or false."),
+ ({"k": [{"prefix": "a", "suffix": "b"}]}, "Only one key allowed in match expression"),
+ ({"k": [{"anything-but": ["x", 5, True]}]},
+ "Inside anything but list, start|null|boolean is not supported."),
+ ({"k": [{"anything-but": ["x", 5]}]}, "mixed type is not supported"),
+ # A threshold AWS's own double conversion would move is refused. Only an
+ # integer can be checked here — a fractional literal's text is gone by
+ # the time the JSON is parsed.
+ ({"k": [{"numeric": [">", 2 ** 60 + 1]}]}, "Cannot compare number"),
+ ]
+ for detail_pattern, reason in rows:
+ refusal = _pattern_refused(eb, {"detail": detail_pattern})
+ assert refusal and reason in refusal, (detail_pattern, refusal)
+ # A threshold that survives the conversion exactly is fine.
+ assert _pattern_refused(eb, {"detail": {"k": [{"numeric": [">", 2 ** 53]}]}}) is None
+ # A whitespace-only pattern is an attempt at a pattern, not bad JSON.
+ try:
+ eb.test_event_pattern(Event=json.dumps({"source": "v.test"}), EventPattern=" ")
+ raise AssertionError("expected a refusal")
+ except ClientError as exc:
+ assert "Filter is not an object" in exc.response["Error"]["Message"]
+
+
+def test_eventbridge_event_time_that_is_not_a_time_does_not_raise(eb):
+ """The envelope every pattern is matched against renders ``time`` from the
+ stored epoch seconds, so a number no platform clock can represent used to
+ raise while BUILDING the view — before any pattern was even consulted — which
+ surfaced as `500 InternalError` and took the whole PutEvents with it."""
+ for stamp in (10 ** 30, -(10 ** 30), 1e30, 1e300):
+ assert _eb._event_time_string({"Time": stamp}) == ""
+ assert _eb._event_time_string({"Time": 1_760_000_000}).startswith("20")
+ # Reachable through the API, and answered rather than raised.
+ resp = eb.test_event_pattern(
+ Event=json.dumps({"source": "op.test", "detail-type": "T",
+ "time": 10 ** 30, "detail": {}}),
+ EventPattern=json.dumps({"source": ["op.test"]}))
+ assert resp["Result"] is True
+ assert eb.test_event_pattern(
+ Event=json.dumps({"source": "op.test", "detail-type": "T",
+ "time": 10 ** 30, "detail": {}}),
+ EventPattern=json.dumps({"time": [{"prefix": "20"}]}))["Result"] is False
+
+
+def test_eventbridge_detail_is_decoded_only_for_patterns_that_ask_about_it(eb):
+ """``detail`` carries the bulk of an event, and the view is built once per
+ event on the dispatch path — so decoding a payload no rule on the bus looks
+ at is work paid for nothing. An alternative naming no top-level ``detail``
+ never asks the matcher about one, which is what makes the deferral safe."""
+ view = _eb._pattern_event_view(_raw_event())
+ assert _eb._matches_alternative(view, {"source": ["op.test"]}) is True
+ assert view._with_detail is None # nothing decoded yet
+ assert _eb._matches_alternative(view, {"detail": {"k": ["v"]}}) is True
+ assert view._with_detail["detail"] == {"k": "v"}
+ # Decoded once and shared: every rule on the bus matches against this view.
+ decoded = view._with_detail
+ assert _eb._matches_alternative(view, {"detail": {"k": [{"exists": True}]}}) is True
+ assert view._with_detail is decoded
+ # A detail that is not JSON stays the leaf it is rather than becoming {}.
+ other = _eb._pattern_event_view(_raw_event(detail="not json"))
+ assert _eb._matches_alternative(other, {"detail": [{"prefix": "not"}]}) is True
+
+
+def test_eventbridge_one_payload_decode_per_event_however_many_targets(eb, monkeypatch):
+ """Every target of every matching rule is delivered the same event, so the
+ payload is decoded once for the event rather than once per target — the
+ deferral the view exists for is worth little if a fan-out re-parses. Delivery
+ takes the tree the rule matched on, which is also what keeps a rule from
+ firing on a field whose delivered value differs."""
+ decoded = []
+ real = _eb._decoded_detail
+ monkeypatch.setattr(_eb, "_decoded_detail",
+ lambda raw: (decoded.append(raw), real(raw))[1])
+ event = _raw_event("qa.fanout", EventId="id-1", EventBusName="default",
+ Account="000000000000", Region="us-east-1")
+ rule = {"Name": "qa-fanout-rule",
+ "Arn": "arn:aws:events:us-east-1:000000000000:rule/qa-fanout-rule"}
+ view = _eb._pattern_event_view(event)
+ # An ARN no target type claims: delivery stops at the dispatch switch, after
+ # the payload the switch is given has been built.
+ for target_id in ("t1", "t2", "t3"):
+ _eb._invoke_target({"Id": target_id, "Arn": "arn:aws:qa-none:us-east-1:000000000000:x"},
+ event, rule, view)
+ assert len(decoded) == 1, decoded
+
+
+def test_eventbridge_event_view_never_hands_out_an_undecoded_detail(eb):
+ """Every tree the view hands out carries the event's own ``detail`` or no
+ ``detail`` at all — an absent field is what AWS matches against, where a
+ fabricated ``null`` is a leaf a content filter or ``{"exists": true}`` would
+ answer about. Why a ``dict`` subclass cannot keep that promise is in
+ ``_EventView``."""
+ view = _eb._pattern_event_view(_raw_event())
+ assert not isinstance(view, dict)
+ # Whatever a consumer does with a tree the view hands out — walk it, log it,
+ # re-encode it — ``detail`` is the event's own or it is not there at all.
+ envelope_only = json.loads(json.dumps(view.envelope()))
+ assert "detail" not in envelope_only
+ with_detail = json.loads(json.dumps(view.event_with_detail()))
+ assert with_detail["detail"] == {"k": "v"}
+
+
+def test_eventbridge_non_json_detail_is_delivered_not_raised(eb, sqs):
+ """A ``Detail`` that is not JSON is a leaf a pattern can match on, so delivery
+ has to read it the same tolerant way the matcher does. Decoding it there with
+ a bare ``json.loads`` raised out of the target invocation, which surfaces as
+ `500 InternalError` from the enclosing PutEvents and takes every other rule on
+ the bus with it — and the prefix filter below is exactly the pattern that
+ makes such an event reach a target in the first place."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ bus_name = f"qa-eb-raw-detail-bus-{suffix}"
+ eb.create_event_bus(Name=bus_name)
+ q_url = _eb_rule_to_queue(eb, sqs, f"raw-detail-{suffix}",
+ {"detail": [{"prefix": "not"}]}, bus_name)
+ resp = eb.put_events(Entries=[{"Source": "myapp", "DetailType": "t",
+ "Detail": "not json",
+ "EventBusName": bus_name}])
+ assert resp["FailedEntryCount"] == 0
+ msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=2)
+ assert len(msgs.get("Messages", [])) == 1
+ assert json.loads(msgs["Messages"][0]["Body"])["detail"] == "not json"
+
+
+def test_eventbridge_hostile_pattern_and_event_text_never_raises(eb):
+ """Three shapes that escaped the guards as `500 InternalError`, each reachable
+ from a short ASCII request body. A pattern fault must be a 400 and an event
+ fault a non-match — never an exception, which from dispatch takes the whole
+ PutEvents and every other rule on the bus with it."""
+ # A JSON escape may carry a lone surrogate, which survives the parse and
+ # cannot be UTF-8 encoded — and the wildcard fault position is a byte count.
+ surrogate = {"detail": {"k": [{"wildcard": "\ud800**"}]}}
+ refusal = _pattern_refused(eb, surrogate)
+ assert refusal and "Consecutive wildcard characters at pos 2" in refusal, refusal
+ assert _matcher_answer(surrogate, {"k": "x"}) is False
+ # An integer literal of more digits than Python will convert raises a plain
+ # ValueError out of the parse, not a JSONDecodeError.
+ try:
+ eb.test_event_pattern(Event=json.dumps({"source": "v.test"}),
+ EventPattern='{"k":[1' + "0" * 5000 + "]}")
+ raise AssertionError("expected a refusal")
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "InvalidEventPatternException"
+ # An event may nest arrays as deep as its author likes, and flattening
+ # recurses per level while building the view every rule is matched against.
+ assert _eb._flatten(json.loads("[" * 60 + "1" + "]" * 60), False) == []
+ assert _eb._flatten(json.loads("[" * 3 + "1" + "]" * 3), False) == [1]
+
+
+def test_eventbridge_anything_but_compares_literals_as_json(eb):
+ """``anything-but`` excludes literals, and it has to compare them as JSON:
+ Python holds ``True == 1``, so a rule excluding ``1`` also excluded ``true``
+ — a value it never named."""
+ assert _pattern_matches(eb, {"k": [{"anything-but": [1]}]}, {"k": True}) is True
+ assert _pattern_matches(eb, {"k": [{"anything-but": [1]}]}, {"k": 1}) is False
+ assert _pattern_matches(eb, {"k": [{"anything-but": ["x"]}]}, {"k": "x"}) is False
+ assert _pattern_matches(eb, {"k": [{"anything-but": ["x"]}]}, {"k": "y"}) is True
+
+
+def test_eventbridge_case_insensitive_suffix_does_not_scan_quadratically():
+ """A case-insensitive suffix used to run the forward walk from every start
+ offset in the value, which is quadratic in the two lengths — one match could
+ hold a worker thread, on the same dispatch path the wildcard translator is
+ careful about. Walking the operand backwards from the end answers it in one
+ pass. The bound is loose on purpose: it catches a return to quadratic."""
+ value = "x" * 200_000 + ".png"
+ started = time.monotonic()
+ assert _eb._matches_content_filter(
+ value, {"suffix": {"equals-ignore-case": ".PNG" * 200}}) is False
+ assert _eb._matches_content_filter(
+ value, {"suffix": {"equals-ignore-case": ".PNG"}}) is True
+ assert time.monotonic() - started < 1.0