Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(cloudwatch): page DescribeAlarms and DescribeAlarmHistory (#2197)
iot-rocket49063c1785fe
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 95c9ec9e..001f64fa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **CloudWatch — `DescribeAlarms` and `DescribeAlarmHistory` paging** — both returned at most `MaxRecords` items (default 100) and never a `NextToken`, so a paginator stopped after the first page; they now return a `NextToken` while more items match, default to 50 items and refuse a `MaxRecords` outside 1 to 100 with `ValidationError`. `DescribeAlarms` now lists metric and composite alarms in one name-ordered sequence that `MaxRecords` counts together, and `DescribeAlarmHistory` lists the newest items first unless `ScanBy` is `TimestampAscending`. `DescribeAlarms` without `AlarmTypes` now returns metric alarms only, as on AWS; composite alarms need `AlarmTypes=["CompositeAlarm"]`. Contributed by @iot-rocket.- **CloudWatch Logs — a log group's resource policy by `resourceArn` alone** — `PutResourcePolicy` and `DeleteResourcePolicy` refused a `resourceArn` without `policyName`; they now take it, store the group's policy without a name and with a counting `revisionId`, and answer a request with neither field or a revision conflict with AWS's errors. `AWS::Logs::LogGroup` now creates, rewrites and removes the group's own policy from `ResourcePolicyDocument`. Contributed by @iot-rocket.- **CloudTrail — trail read-backs and recording switched on at runtime** — `GetTrail` and `DescribeTrails` returned the stored `IsLogging`, `_StartedAt` and `_StoppedAt` keys and empty `S3KeyPrefix` and `SnsTopicName` members, and `GetTrailStatus` left out the six deprecated string members and moved `StopLoggingTime` when a stopped trail was stopped again; they now answer in AWS's shapes, with the start and stop times in milliseconds, and keep the last stop time. Recording switched on through `/_ministack/config` began only after the first CloudTrail API call and now starts with the next request. Contributed by @iot-rocket.- **ACM / Signer — certificate key and in-use refusals** — `ImportCertificate` accepted a call without a `PrivateKey` and now answers AWS's `ValidationException`; `DeleteCertificate` removed a certificate an Active Signer signing profile uses and now answers `ResourceInUseException`, with those profiles listed in `DescribeCertificate`'s `InUseBy`; `CancelSigningProfile` answered 200 with `{}` and now answers 204 with an empty body, as on AWS. Contributed by @iot-rocket.diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.pyindex 1c730d08..186a7e2b 100644--- a/ministack/services/cloudwatch.py+++ b/ministack/services/cloudwatch.py@@ -12,6 +12,7 @@ Operations: PutMetricData, GetMetricStatistics, GetMetricData, ListMetrics,PutDashboard, GetDashboard, DeleteDashboards, ListDashboards."""+import base64import copyimport jsonimport logging@@ -1142,13 +1143,41 @@ def _put_composite_alarm(params, cbor_data, is_cbor, is_json=False):# ---------------------------------------------------------------------------+def _max_records_error(raw):+ """ValidationError message for a MaxRecords outside 1..100, else None."""+ if raw in (None, ""):+ return None+ value = int(raw)+ if value < 1:+ bound = "greater than or equal to 1"+ elif value > 100:+ bound = "less than or equal to 100"+ else:+ return None+ return (f"1 validation error detected: Value '{value}' at 'maxRecords' failed to satisfy constraint: "+ f"Member must have value {bound}")+++def _encode_page_token(position):+ return base64.urlsafe_b64encode(position.encode()).decode().rstrip("=")+++def _decode_page_token(token):+ """Position carried by a token from _encode_page_token, or None for any other string."""+ try:+ return base64.urlsafe_b64decode(token + "=" * (-len(token) % 4)).decode()+ except ValueError:+ return None++def _describe_alarms(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:names = cbor_data.get("AlarmNames", [])prefix = cbor_data.get("AlarmNamePrefix")state = cbor_data.get("StateValue")- alarm_types = cbor_data.get("AlarmTypes", ["MetricAlarm", "CompositeAlarm"])- max_records = cbor_data.get("MaxRecords", 100)+ alarm_types = cbor_data.get("AlarmTypes") or ["MetricAlarm"]+ max_records = cbor_data.get("MaxRecords")+ next_token = cbor_data.get("NextToken")else:names = [_p(params, f"AlarmNames.member.{i}")@@ -1161,8 +1190,14 @@ def _describe_alarms(params, cbor_data, is_cbor, is_json=False):_p(params, f"AlarmTypes.member.{i}")for i in range(1, 11)if _p(params, f"AlarmTypes.member.{i}")- ] or ["MetricAlarm", "CompositeAlarm"]- max_records = int(_p(params, "MaxRecords") or "100")+ ] or ["MetricAlarm"]+ max_records = _p(params, "MaxRecords")+ next_token = _p(params, "NextToken")++ invalid = _max_records_error(max_records)+ if invalid:+ return _error("ValidationError", invalid, 400, use_json=is_json, use_cbor=is_cbor)+ max_records = int(max_records or 50)metric_alarms = []composite_results = []@@ -1187,19 +1222,33 @@ def _describe_alarms(params, cbor_data, is_cbor, is_json=False):continuecomposite_results.append(alarm)- metric_alarms = metric_alarms[:max_records]+ # One listing in name order across both types; MaxRecords counts them together.+ listing = sorted(+ [(a["AlarmName"], 0, a) for a in metric_alarms] + [(a["AlarmName"], 1, a) for a in composite_results],+ key=lambda entry: entry[:2],+ )+ # As on AWS, the token is the name of the next page's first alarm and a page starts at the first name at or+ # after it, so any string is a valid token and alarms created or deleted between pages shift nothing.+ if next_token:+ listing = [entry for entry in listing if entry[0] >= next_token]+ page = listing[:max_records]+ token = listing[max_records][0] if len(listing) > max_records else None+ metric_alarms = [a for _, kind, a in page if kind == 0]+ composite_results = [a for _, kind, a in page if kind == 1]if is_cbor:- return _cbor_ok(- {- "MetricAlarms": [_cbor_alarm(a) for a in metric_alarms],- "CompositeAlarms": [_cbor_alarm(a) for a in composite_results],- }- )+ result = {+ "MetricAlarms": [_cbor_alarm(a) for a in metric_alarms],+ "CompositeAlarms": [_cbor_alarm(a) for a in composite_results],+ }+ if token:+ result["NextToken"] = token+ return _cbor_ok(result)if is_json:- return _json_ok(- {"MetricAlarms": metric_alarms, "CompositeAlarms": composite_results}- )+ result = {"MetricAlarms": metric_alarms, "CompositeAlarms": composite_results}+ if token:+ result["NextToken"] = token+ return _json_ok(result)metric_members = "".join(f"<member><AlarmName>{a['AlarmName']}</AlarmName><AlarmArn>{a['AlarmArn']}</AlarmArn>"@@ -1225,6 +1274,7 @@ def _describe_alarms(params, cbor_data, is_cbor, is_json=False):f"<DescribeAlarmsResult>"f"<MetricAlarms>{metric_members}</MetricAlarms>"f"<CompositeAlarms>{comp_members}</CompositeAlarms>"+ f"{f'<NextToken>{token}</NextToken>' if token else ''}"f"</DescribeAlarmsResult>",)@@ -1277,29 +1327,60 @@ def _describe_alarm_history(params, cbor_data, is_cbor, is_json=False):history_type = cbor_data.get("HistoryItemType")start_date = _parse_ts(cbor_data.get("StartDate"))end_date = _parse_ts(cbor_data.get("EndDate"))- max_records = int(cbor_data.get("MaxRecords", 100))+ max_records = cbor_data.get("MaxRecords")+ next_token = cbor_data.get("NextToken")+ scan_by = cbor_data.get("ScanBy")else:alarm_name = _p(params, "AlarmName")history_type = _p(params, "HistoryItemType")start_date = _parse_ts(_p(params, "StartDate"))end_date = _parse_ts(_p(params, "EndDate"))- max_records = int(_p(params, "MaxRecords") or "100")+ max_records = _p(params, "MaxRecords")+ next_token = _p(params, "NextToken")+ scan_by = _p(params, "ScanBy")- items = list(_history_entries())+ items = list(enumerate(_history_entries()))if alarm_name:- items = [h for h in items if h["AlarmName"] == alarm_name]+ items = [(i, h) for i, h in items if h["AlarmName"] == alarm_name]if history_type:- items = [h for h in items if h["HistoryItemType"] == history_type]+ items = [(i, h) for i, h in items if h["HistoryItemType"] == history_type]if start_date is not None:- items = [h for h in items if _parse_ts(h["Timestamp"]) >= start_date]+ items = [(i, h) for i, h in items if _parse_ts(h["Timestamp"]) >= start_date]if end_date is not None:- items = [h for h in items if _parse_ts(h["Timestamp"]) <= end_date]- items = items[:max_records]+ items = [(i, h) for i, h in items if _parse_ts(h["Timestamp"]) <= end_date]++ invalid = _max_records_error(max_records)+ if invalid:+ return _error("ValidationError", invalid, 400, use_json=is_json, use_cbor=is_cbor)+ max_records = int(max_records or 50)+ start = None+ if next_token:+ start = _decode_page_token(next_token)+ if start is None or not start.isdigit():+ return _error("InvalidNextToken", f"Invalid NextToken : {next_token}", 400,+ use_json=is_json, use_cbor=is_cbor)+ start = int(start)++ # Entries are stored oldest first and only appended; ScanBy defaults to TimestampDescending.+ # The token holds the stored index of the next entry, so new entries do not shift a scan.+ descending = scan_by != "TimestampAscending"+ if descending:+ items.reverse()+ if start is not None:+ items = [(i, h) for i, h in items if (i <= start if descending else i >= start)]+ token = _encode_page_token(str(items[max_records][0])) if len(items) > max_records else None+ items = [h for _, h in items[:max_records]]if is_cbor:- return _cbor_ok({"AlarmHistoryItems": [_cbor_history_item(i) for i in items]})+ result = {"AlarmHistoryItems": [_cbor_history_item(i) for i in items]}+ if token:+ result["NextToken"] = token+ return _cbor_ok(result)if is_json:- return _json_ok({"AlarmHistoryItems": items})+ result = {"AlarmHistoryItems": items}+ if token:+ result["NextToken"] = token+ return _json_ok(result)members = "".join(f"<member><AlarmName>{h['AlarmName']}</AlarmName>"@@ -1312,6 +1393,7 @@ def _describe_alarm_history(params, cbor_data, is_cbor, is_json=False):200,"DescribeAlarmHistoryResponse",f"<DescribeAlarmHistoryResult><AlarmHistoryItems>{members}</AlarmHistoryItems>"+ f"{f'<NextToken>{token}</NextToken>' if token else ''}"f"</DescribeAlarmHistoryResult>",)diff --git a/tests/test_cloudwatch.py b/tests/test_cloudwatch.pyindex 40790e1e..337a4dda 100644--- a/tests/test_cloudwatch.py+++ b/tests/test_cloudwatch.py@@ -155,6 +155,113 @@ def test_cloudwatch_describe_alarms_v2(cw):for i in range(3):assert f"cw-da-v2-{i}" in names++def _put_paging_alarm(cw, name):+ cw.put_metric_alarm(+ AlarmName=name, MetricName="M", Namespace="N", Statistic="Sum", Period=60,+ EvaluationPeriods=1, Threshold=1.0, ComparisonOperator="GreaterThanThreshold",+ )+++def test_cloudwatch_describe_alarms_pages_both_types_in_name_order(cw):+ prefix = f"cw-page-{_uuid_mod.uuid4().hex[:8]}-"+ metric = [f"{prefix}m-{i}" for i in (3, 0, 4, 1, 2)]+ for name in metric + [f"{prefix}A-upper"]:+ _put_paging_alarm(cw, name)+ for name in (f"{prefix}c-1", f"{prefix}z-2"):+ cw.put_composite_alarm(AlarmName=name, AlarmRule=f'ALARM("{metric[0]}")')+ try:+ pages, token = [], None+ while True:+ kwargs = {"NextToken": token} if token else {}+ resp = cw.describe_alarms(AlarmNamePrefix=prefix, AlarmTypes=["MetricAlarm", "CompositeAlarm"],+ MaxRecords=3, **kwargs)+ pages.append(([a["AlarmName"][len(prefix):] for a in resp["MetricAlarms"]],+ [a["AlarmName"][len(prefix):] for a in resp["CompositeAlarms"]]))+ token = resp.get("NextToken")+ if not token:+ break+ # One byte-ordered listing across both types; MaxRecords counts both.+ assert pages == [+ (["A-upper", "m-0"], ["c-1"]),+ (["m-1", "m-2", "m-3"], []),+ (["m-4"], ["z-2"]),+ ]++ paginated = cw.get_paginator("describe_alarms").paginate(+ AlarmNamePrefix=prefix, AlarmTypes=["MetricAlarm", "CompositeAlarm"], PaginationConfig={"PageSize": 2})+ assert len(paginated.build_full_result()["MetricAlarms"]) == 6+ finally:+ for name in (f"{prefix}c-1", f"{prefix}z-2"):+ cw.delete_alarms(AlarmNames=[name])+ cw.delete_alarms(AlarmNames=metric + [f"{prefix}A-upper"])+++def test_cloudwatch_describe_alarms_next_token_survives_changes_between_pages(cw):+ prefix = f"cw-page-chg-{_uuid_mod.uuid4().hex[:8]}-"+ names = [f"{prefix}m-{i}" for i in range(6)]+ for name in names:+ _put_paging_alarm(cw, name)+ try:+ first = cw.describe_alarms(AlarmNamePrefix=prefix, MaxRecords=2)+ assert [a["AlarmName"] for a in first["MetricAlarms"]] == names[:2]+ assert first["NextToken"] == names[2]+ # Delete the alarm the token names and the page before it, add one alarm on each side of the token.+ cw.delete_alarms(AlarmNames=names[:3])+ _put_paging_alarm(cw, f"{prefix}m-1a")+ _put_paging_alarm(cw, f"{prefix}m-2a")+ second = cw.describe_alarms(AlarmNamePrefix=prefix, MaxRecords=2, NextToken=first["NextToken"])+ assert [a["AlarmName"] for a in second["MetricAlarms"]] == [f"{prefix}m-2a", names[3]]+ third = cw.describe_alarms(AlarmNamePrefix=prefix, MaxRecords=2, NextToken=second["NextToken"])+ assert [a["AlarmName"] for a in third["MetricAlarms"]] == names[4:6]+ assert "NextToken" not in third+ finally:+ cw.delete_alarms(AlarmNames=names + [f"{prefix}m-1a", f"{prefix}m-2a"])+++def test_cloudwatch_describe_alarms_defaults_to_50_metric_alarms(cw):+ prefix = f"cw-page-def-{_uuid_mod.uuid4().hex[:8]}-"+ names = [f"{prefix}{i:02d}" for i in range(52)]+ for name in names:+ _put_paging_alarm(cw, name)+ cw.put_composite_alarm(AlarmName=f"{prefix}comp", AlarmRule=f'ALARM("{names[0]}")')+ try:+ first = cw.describe_alarms(AlarmNamePrefix=prefix)+ assert [a["AlarmName"] for a in first["MetricAlarms"]] == names[:50]+ assert first["CompositeAlarms"] == []+ second = cw.describe_alarms(AlarmNamePrefix=prefix, NextToken=first["NextToken"])+ assert [a["AlarmName"] for a in second["MetricAlarms"]] == names[50:]+ assert "NextToken" not in second+ finally:+ cw.delete_alarms(AlarmNames=[f"{prefix}comp"])+ cw.delete_alarms(AlarmNames=names)+++def test_cloudwatch_describe_alarms_max_records_bounds_and_any_token():+ from conftest import make_client++ raw = make_client("cloudwatch", {"parameter_validation": False})+ for value, bound in ((0, "greater than or equal to 1"), (101, "less than or equal to 100")):+ with pytest.raises(ClientError) as exc:+ raw.describe_alarms(MaxRecords=value)+ assert exc.value.response["Error"]["Code"] == "ValidationError"+ assert exc.value.response["Error"]["Message"] == (+ f"1 validation error detected: Value '{value}' at 'maxRecords' failed to satisfy constraint: "+ f"Member must have value {bound}"+ )+ prefix = f"cw-page-tok-{_uuid_mod.uuid4().hex[:8]}-"+ names = [f"{prefix}{i}" for i in range(2)]+ for name in names:+ _put_paging_alarm(raw, name)+ try:+ # Any string is a name to start from: one after every name gives an empty page, one before them the first.+ resp = raw.describe_alarms(AlarmNamePrefix=prefix, NextToken="zzzz")+ assert resp["MetricAlarms"] == [] and "NextToken" not in resp+ resp = raw.describe_alarms(AlarmNamePrefix=prefix, NextToken="aaaa")+ assert [a["AlarmName"] for a in resp["MetricAlarms"]] == names+ finally:+ raw.delete_alarms(AlarmNames=names)+def test_cloudwatch_delete_alarms_v2(cw):cw.put_metric_alarm(AlarmName="cw-del-v2",@@ -522,6 +629,50 @@ def test_cloudwatch_describe_alarm_history(cw):assert "AlarmHistoryItems" in respcw.delete_alarms(AlarmNames=[alarm_name])++def test_cloudwatch_describe_alarm_history_pages_newest_first(cw):+ alarm_name = f"intg-hist-page-{_uuid_mod.uuid4().hex[:8]}"+ _put_paging_alarm(cw, alarm_name)+ for state in ("ALARM", "OK", "ALARM"):+ cw.set_alarm_state(AlarmName=alarm_name, StateValue=state, StateReason="paging")+ try:+ query = {"AlarmName": alarm_name, "HistoryItemType": "StateUpdate"}+ everything = cw.describe_alarm_history(**query)["AlarmHistoryItems"]+ assert [h["HistorySummary"] for h in everything[:3]] == [+ "Alarm updated from OK to ALARM",+ "Alarm updated from ALARM to OK",+ "Alarm updated from INSUFFICIENT_DATA to ALARM",+ ]+ ascending = cw.describe_alarm_history(ScanBy="TimestampAscending", **query)["AlarmHistoryItems"]+ assert ascending == everything[::-1]++ first = cw.describe_alarm_history(MaxRecords=2, **query)+ assert first["AlarmHistoryItems"] == everything[:2]+ # A state change between pages adds a newer entry; the scan goes on where it stopped.+ cw.set_alarm_state(AlarmName=alarm_name, StateValue="OK", StateReason="paging")+ second = cw.describe_alarm_history(MaxRecords=2, NextToken=first["NextToken"], **query)+ assert second["AlarmHistoryItems"] == everything[2:4]+ everything = cw.describe_alarm_history(**query)["AlarmHistoryItems"]+ paginated = cw.get_paginator("describe_alarm_history").paginate(+ PaginationConfig={"PageSize": 2}, **query)+ assert paginated.build_full_result()["AlarmHistoryItems"] == everything+ finally:+ cw.delete_alarms(AlarmNames=[alarm_name])+++def test_cloudwatch_describe_alarm_history_max_records_bounds_and_unknown_token():+ from conftest import make_client++ raw = make_client("cloudwatch", {"parameter_validation": False})+ with pytest.raises(ClientError) as exc:+ raw.describe_alarm_history(MaxRecords=101)+ assert exc.value.response["Error"]["Code"] == "ValidationError"+ assert "Member must have value less than or equal to 100" in exc.value.response["Error"]["Message"]+ with pytest.raises(ClientError) as exc:+ raw.describe_alarm_history(NextToken="bogus-token")+ assert exc.value.response["Error"]["Code"] == "InvalidNextToken"+ assert exc.value.response["Error"]["Message"] == "Invalid NextToken : bogus-token"+def test_cloudwatch_get_metric_data_time_range(cw):"""GetMetricData respects StartTime/EndTime filtering."""import datetime@@ -831,6 +982,48 @@ def test_cloudwatch_describe_alarms_cbor_omits_absent_optional_fields():_resp._request_account_id.reset(acct_tok)+def test_cloudwatch_describe_alarms_next_token_over_cbor_and_query():+ import re as _re++ import cbor2++ from ministack.core import responses as _resp+ from ministack.services import cloudwatch as _cw++ acct_tok = _resp._request_account_id.set("000000000000")+ region_tok = _resp._request_region.set("us-east-1")+ prefix = f"wire-page-{_uuid_mod.uuid4().hex[:8]}-"+ names = [f"{prefix}{i}" for i in range(3)]+ try:+ for name in names:+ _cw._put_metric_alarm({}, {+ "AlarmName": name, "ComparisonOperator": "GreaterThanThreshold", "EvaluationPeriods": 1,+ "MetricName": "Errors", "Namespace": "AWS/Lambda", "Period": 300, "Statistic": "Sum",+ "Threshold": 1,+ }, is_cbor=True)++ _, _, body = _cw._describe_alarms({}, {"AlarmNamePrefix": prefix, "MaxRecords": 2}, is_cbor=True)+ decoded = cbor2.loads(body)+ assert [a["AlarmName"] for a in decoded["MetricAlarms"]] == names[:2]+ _, _, body = _cw._describe_alarms(+ {}, {"AlarmNamePrefix": prefix, "MaxRecords": 2, "NextToken": decoded["NextToken"]}, is_cbor=True)+ decoded = cbor2.loads(body)+ assert [a["AlarmName"] for a in decoded["MetricAlarms"]] == names[2:]+ assert "NextToken" not in decoded++ _, _, body = _cw._describe_alarms({"AlarmNamePrefix": [prefix], "MaxRecords": ["2"]}, {}, is_cbor=False)+ token = _re.search(r"<NextToken>([^<]+)</NextToken>", body.decode()).group(1)+ _, _, body = _cw._describe_alarms(+ {"AlarmNamePrefix": [prefix], "MaxRecords": ["2"], "NextToken": [token]}, {}, is_cbor=False)+ assert _re.findall(r"<AlarmName>([^<]+)</AlarmName>", body.decode()) == names[2:]+ assert "<NextToken>" not in body.decode()+ finally:+ for name in names:+ _cw._alarms.pop_scoped("000000000000", "us-east-1", name, None)+ _resp._request_region.reset(region_tok)+ _resp._request_account_id.reset(acct_tok)++def test_cloudwatch_get_metric_statistics_cbor_timestamps_are_tag1():"""GetMetricStatistics over smithy-rpc-v2-cbor must encodeDatapoint.Timestamp as CBOR tag 1, not an ISO string, so the provider's