Skip to content

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

fix(events): add the quotes an input template omits around a string variable (#1507)

ppettitaud1d627fed3a4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e474a72d..58e2731a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Fixed
+- **EventBridge — an input template no longer needs quotes around a string variable** — AWS documents that quotes are optional for a variable holding a string and adds them itself so the transformed input stays valid JSON, quoting neither an object nor an array. MiniStack pasted every value in verbatim, so the documented form `{"detail": <detail>, "groupId": <groupId>}` produced `"groupId": some-value` and the target received a body that would not parse, forcing consumers to hand-quote the placeholder. Substitution is now aware of where the placeholder sits: a string variable in a JSON value position is quoted, a variable inside a string literal is interpolated raw as before, and an object or array spliced into a string has its internal quotes stripped the way AWS does.
+
## [1.5.1] — 2026-08-25
### Added
diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.py
index 4ac7239c..ead12f68 100644
--- a/ministack/services/eventbridge.py
+++ b/ministack/services/eventbridge.py
@@ -2342,7 +2342,7 @@ def _apply_input_transformer(transformer, rule, view):
for p in parts:
if p:
val = val[p]
- replacements[var_name] = val if isinstance(val, str) else json.dumps(val)
+ replacements[var_name] = val
except (KeyError, TypeError, IndexError):
replacements[var_name] = ""
@@ -2351,8 +2351,8 @@ def _apply_input_transformer(transformer, rule, view):
# cannot be overwritten by an InputPathsMap entry.
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(view.envelope()),
+ "aws.events.event.json": event_envelope,
+ "aws.events.event": view.envelope(),
"aws.events.event.ingestion-time": ingestion_time,
}
if rule:
@@ -2363,11 +2363,53 @@ def _apply_input_transformer(transformer, rule, view):
# ingestion-time is reserved and uneditable, even if InputPathsMap declares it.
replacements["aws.events.event.ingestion-time"] = ingestion_time
- result = template
- for var_name, val in replacements.items():
- result = result.replace(f"<{var_name}>", str(val))
+ return _render_input_template(template, replacements)
- return result
+
+def _render_input_template(template, replacements):
+ """Substitute ``<var>`` placeholders the way EventBridge does.
+
+ Quotes around a variable that resolves to a string are optional: AWS adds
+ them when the placeholder sits in a JSON value position, so
+ ``{"groupId": <groupId>}`` and ``{"groupId": "<groupId>"}`` both render
+ valid JSON. Values are never escaped, and a JSON object or array
+ referenced from inside a string literal has its quotes stripped so the
+ surrounding string stays valid.
+ """
+
+ def in_string(match):
+ return _render_placeholder(match.group(1), match.group(0), replacements, True)
+
+ def render(match):
+ token = match.group(0)
+ if token.startswith('"'):
+ return _PLACEHOLDER_RE.sub(in_string, token)
+ return _render_placeholder(token[1:-1], token, replacements, False)
+
+ # A template with no double quotes at all is plain text rather than JSON,
+ # so every placeholder in it is a string interpolation.
+ if '"' not in template:
+ return _PLACEHOLDER_RE.sub(in_string, template)
+ return _STRING_OR_PLACEHOLDER_RE.sub(render, template)
+
+
+# Matching whole string literals alongside placeholders is what tells a
+# placeholder in a JSON value position from one inside a string; consuming the
+# literal in one bite also skips any escaped quote it contains.
+_STRING_OR_PLACEHOLDER_RE = re.compile(r'"(?:\\.|[^"\\])*"|<[^<>]*>')
+_PLACEHOLDER_RE = re.compile(r"<([^<>]*)>")
+
+
+def _render_placeholder(var_name, token, replacements, in_string):
+ if var_name not in replacements:
+ return token
+ value = replacements[var_name]
+ if isinstance(value, str):
+ return value if in_string else json.dumps(value)
+ rendered = json.dumps(value)
+ # AWS drops the internal quotes of an object or array spliced into a
+ # string so that the result is still a single valid JSON string.
+ return rendered.replace('"', "") if in_string else rendered
def _dispatch_to_lambda(arn, payload):
diff --git a/tests/test_eventbridge.py b/tests/test_eventbridge.py
index df2e564e..5540544d 100644
--- a/tests/test_eventbridge.py
+++ b/tests/test_eventbridge.py
@@ -2894,6 +2894,133 @@ def test_eventbridge_input_transformer_ingestion_time(eb, sqs):
assert body["it"] != ""
+# ---------------------------------------------------------------------------
+# Input template quoting
+# ---------------------------------------------------------------------------
+
+def _transform_to_queue(eb, sqs, slug, source, template, paths_map, detail):
+ """Route one event through an input transformer and return the delivered body."""
+ bus_name = f"qa-eb-{slug}-bus"
+ eb.create_event_bus(Name=bus_name)
+ 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"]
+ eb.put_rule(
+ Name=f"qa-eb-{slug}-rule",
+ EventBusName=bus_name,
+ EventPattern=json.dumps({"source": [source]}),
+ State="ENABLED",
+ )
+ eb.put_targets(
+ Rule=f"qa-eb-{slug}-rule",
+ EventBusName=bus_name,
+ Targets=[
+ {
+ "Id": "t1",
+ "Arn": q_arn,
+ "InputTransformer": {"InputPathsMap": paths_map, "InputTemplate": template},
+ }
+ ],
+ )
+ eb.put_events(
+ Entries=[
+ {
+ "Source": source,
+ "DetailType": "TestEvent",
+ "Detail": json.dumps(detail),
+ "EventBusName": bus_name,
+ }
+ ]
+ )
+ msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=1)
+ assert len(msgs.get("Messages", [])) == 1
+ return msgs["Messages"][0]["Body"]
+
+
+def test_eventbridge_input_template_quotes_unquoted_string_variable(eb, sqs):
+ """Quotes around a string variable are optional; AWS adds them in a value position."""
+ body = _transform_to_queue(
+ eb,
+ sqs,
+ "tmpl-unquoted-str",
+ "myapp.tmpl.unquoted",
+ '{"widgetId": <widgetId>, "state": <state>}',
+ {"widgetId": "$.detail.widgetId", "state": "$.detail.state"},
+ {"widgetId": "widget-1", "state": "READY"},
+ )
+ assert json.loads(body) == {"widgetId": "widget-1", "state": "READY"}
+
+
+def test_eventbridge_input_template_mixes_unquoted_object_and_string(eb, sqs):
+ """An unquoted object variable stays raw JSON while a string variable gains quotes."""
+ detail = {"widgetId": "widget-2", "quantity": 3}
+ body = _transform_to_queue(
+ eb,
+ sqs,
+ "tmpl-mixed",
+ "myapp.tmpl.mixed",
+ '{"detail": <detail>, "groupId": <groupId>}',
+ {"groupId": "$.detail.widgetId", "detail": "$.detail"},
+ detail,
+ )
+ assert json.loads(body) == {"detail": detail, "groupId": "widget-2"}
+
+
+def test_eventbridge_input_template_quoted_string_variable_unchanged(eb, sqs):
+ """Explicitly quoting a string variable still yields a single set of quotes."""
+ body = _transform_to_queue(
+ eb,
+ sqs,
+ "tmpl-quoted-str",
+ "myapp.tmpl.quoted",
+ '{"groupId": "<groupId>"}',
+ {"groupId": "$.detail.widgetId"},
+ {"widgetId": "widget-3"},
+ )
+ assert json.loads(body) == {"groupId": "widget-3"}
+
+
+def test_eventbridge_input_template_variable_inside_string_literal(eb, sqs):
+ """A variable embedded in surrounding text is interpolated without added quotes."""
+ body = _transform_to_queue(
+ eb,
+ sqs,
+ "tmpl-inline",
+ "myapp.tmpl.inline",
+ '{"message": "widget <widgetId> is <state>", "state": <state>}',
+ {"widgetId": "$.detail.widgetId", "state": "$.detail.state"},
+ {"widgetId": "widget-4", "state": "READY"},
+ )
+ assert json.loads(body) == {"message": "widget widget-4 is READY", "state": "READY"}
+
+
+def test_eventbridge_input_template_plain_text(eb, sqs):
+ """A template with no JSON quoting is delivered as plain interpolated text."""
+ body = _transform_to_queue(
+ eb,
+ sqs,
+ "tmpl-plain",
+ "myapp.tmpl.plain",
+ "widget <widgetId> is <state>",
+ {"widgetId": "$.detail.widgetId", "state": "$.detail.state"},
+ {"widgetId": "widget-5", "state": "READY"},
+ )
+ assert body == "widget widget-5 is READY"
+
+
+def test_eventbridge_input_template_object_inside_string_literal(eb, sqs):
+ """An object variable used inside a string has its quotes stripped, as AWS does."""
+ body = _transform_to_queue(
+ eb,
+ sqs,
+ "tmpl-obj-in-str",
+ "myapp.tmpl.objinstr",
+ '{"message": "detail is <detail>"}',
+ {"detail": "$.detail"},
+ {"widgetId": "widget-6"},
+ )
+ assert json.loads(body) == {"message": "detail is {widgetId: widget-6}"}
+
+
# ---------------------------------------------------------------------------
# API destination dispatch
# ---------------------------------------------------------------------------