Skip to content

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

Lambda: match Kinesis ESM filter patterns against decoded data and metadata (#2422)

Luke Dutton5c4ad926e19a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d1a7b2ee..58a8c725 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **Lambda — Kinesis event source mapping filters** — a `FilterCriteria` pattern on a Kinesis record's `data` or on its metadata (`partitionKey`, `sequenceNumber`, ...) never matched, so a mapping with filters dropped every record. Patterns are now matched as AWS documents them: metadata fields next to the event fields, and `data` decoded from base64 as JSON. Data that isn't JSON can't match a `data` pattern but still matches metadata patterns.
- **Lambda — two MiniStacks on one host no longer remove each other's function code** — the provided-runtime and Docker-executor extraction caches lived at fixed paths in the shared temp directory, so a second instance on the same host deleted a tree the first was still running from ("leftover from a previous process") and its `reset()` removed the first one's caches; an invocation then failed with `No such file or directory: .../bootstrap`. Both caches are now named for the instance's `GATEWAY_PORT`. Contributed by @skialpine.
### Added
- **OpenSearch — `OPENSEARCH_JAVA_OPTS`** — a small machine could not cap the heap of the engine containers MiniStack starts; the setting is now passed to each of them (per-domain and Serverless collection), and unset passes nothing. Contributed by @skialpine.
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 1ad303f6..ffe9ce2c 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -3776,6 +3776,22 @@ def _match_esm_filter(record: dict, pattern: dict) -> bool:
return True
+def _kinesis_record_for_match(rec: dict) -> dict:
+ """The record a Kinesis filter pattern is matched against. AWS filters on
+ the metadata fields (``partitionKey``, ``sequenceNumber``, ...) next to the
+ event fields and on ``data`` as decoded JSON (AWS Lambda developer guide,
+ "Using event filtering with a Kinesis event source"). Data that isn't JSON
+ is left out, so a ``data`` pattern can't match it but metadata ones still can."""
+ flat = {k: v for k, v in rec.items() if k != "kinesis"}
+ flat.update(rec["kinesis"])
+ flat.pop("data", None)
+ try:
+ flat["data"] = json.loads(base64.b64decode(rec["kinesis"].get("data") or "", validate=True))
+ except (ValueError, TypeError):
+ pass
+ return flat
+
+
def _apply_filter_criteria(records: list[dict], esm: dict) -> list[dict]:
"""Apply an ESM's FilterCriteria.Filters (OR across patterns) to a batch
of records, returning only those matching at least one filter. If no
@@ -3800,7 +3816,7 @@ def _apply_filter_criteria(records: list[dict], esm: dict) -> list[dict]:
for rec in records:
# For SQS records the body is a string; AWS parses JSON bodies
# automatically when the filter pattern targets `body.*` fields.
- rec_for_match = dict(rec)
+ rec_for_match = _kinesis_record_for_match(rec) if isinstance(rec.get("kinesis"), dict) else dict(rec)
body = rec.get("body")
if isinstance(body, str):
try:
diff --git a/tests/test_kinesis.py b/tests/test_kinesis.py
index f0a3f60f..93efde10 100644
--- a/tests/test_kinesis.py
+++ b/tests/test_kinesis.py
@@ -940,3 +940,62 @@ def test_subscription_captures_selection_before_runner_and_pruning(subscription_
assert events[0]["ContinuationSequenceNumber"] == appended
asyncio.run(exercise())
+
+
+_FILTER_HANDLER = """
+import base64
+
+def handler(event, context):
+ for r in event["Records"]:
+ print("XREC " + base64.b64decode(r["kinesis"]["data"]).decode())
+ return len(event["Records"])
+"""
+
+
[email protected]("pattern, expected", [
+ ({"data": {"kind": ["keep"]}}, ['{"kind": "keep"}', '{"kind": "keep", "n": 2}']),
+ ({"data": {"n": [{"numeric": [">", 1]}]}}, ['{"kind": "keep", "n": 2}']),
+ ({"partitionKey": ["pk-b"]}, ['{"kind": "drop"}', "not json"]),
+ ({"partitionKey": [{"prefix": "pk-"}], "data": {"kind": [{"exists": True}]}},
+ ['{"kind": "keep"}', '{"kind": "drop"}', '{"kind": "keep", "n": 2}']),
+], ids=["data-field", "data-numeric", "metadata-only-matches-non-json", "metadata-and-data"])
+def test_kinesis_esm_filter_criteria_match_decoded_data_and_metadata(lam, kin, logs, pattern, expected):
+ """Black box: the function only receives the records the pattern selects."""
+ stream = f"kin-filter-{_uuid_mod.uuid4().hex[:8]}"
+ kin.create_stream(StreamName=stream, ShardCount=1)
+ arn = kin.describe_stream_summary(StreamName=stream)["StreamDescriptionSummary"]["StreamARN"]
+ for data, pk in (('{"kind": "keep"}', "pk-a"), ('{"kind": "drop"}', "pk-b"),
+ ("not json", "pk-b"), ('{"kind": "keep", "n": 2}', "pk-a")):
+ kin.put_record(StreamName=stream, Data=data.encode(), PartitionKey=pk)
+
+ fn = f"kin-filter-fn-{_uuid_mod.uuid4().hex[:8]}"
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", _FILTER_HANDLER)
+ lam.create_function(FunctionName=fn, Runtime="python3.12", Role=_LAMBDA_ROLE,
+ Handler="index.handler", Code={"ZipFile": buf.getvalue()})
+ esm = lam.create_event_source_mapping(
+ FunctionName=fn, EventSourceArn=arn, StartingPosition="TRIM_HORIZON",
+ FilterCriteria={"Filters": [{"Pattern": json.dumps(pattern)}]})["UUID"]
+ try:
+ received = []
+ deadline = time.time() + 30
+ while time.time() < deadline:
+ try:
+ events = logs.filter_log_events(logGroupName=f"/aws/lambda/{fn}")["events"]
+ except ClientError:
+ events = []
+ received = [line[len("XREC "):] for e in events for line in e["message"].splitlines()
+ if line.startswith("XREC ")]
+ if len(received) >= len(expected):
+ break
+ time.sleep(0.5)
+ time.sleep(2) # nothing that should have been filtered turns up later
+ events = logs.filter_log_events(logGroupName=f"/aws/lambda/{fn}")["events"]
+ received = [line[len("XREC "):] for e in events for line in e["message"].splitlines()
+ if line.startswith("XREC ")]
+ assert received == expected
+ finally:
+ lam.delete_event_source_mapping(UUID=esm)
+ lam.delete_function(FunctionName=fn)
+ kin.delete_stream(StreamName=stream)