Skip to content

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

fix(cloudfront,cloudwatch): keep tags on create and stop inventing DatapointsToAlarm (#2375)

Kacper Harabaszea2b9084f698
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 07c595cf..3f39209c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **IoT — thing-group membership authorized on the group and the thing** — with `AUTH=true`, `AddThingToThingGroup` and `RemoveThingFromThingGroup` were authorized on `thinggroup/addThingToThingGroup` (the request path), so a policy granting exactly the thing group and the thing was denied; both calls are now checked on the thing group and then the thing named in the body (by name or ARN), and a denial names the resource that failed. Contributed by @iot-rocket.
- **API Gateway — `AWS_IAM` methods refuse an `Authorization` header that is not SigV4** — under `AUTH=true` a REST API method with `AWS_IAM` authorization served a bearer token or an algorithm in lower case, and answered the SigV4a algorithm name without a signed `x-amz-region-set` or an unknown `AWS4-` algorithm with `UnrecognizedClientException`; it now answers 403 `IncompleteSignatureException` with API Gateway's message for each, while a method without `AWS_IAM` still serves such calls. Contributed by @iot-rocket.
- **S3 — access point policies and unsigned requests** — an access point policy was stored but never applied, and an unsigned request through an access point was served. With `AUTH=true` a request through an access point alias or ARN is allowed on the access point by an identity policy or the access point policy (a Deny in either refuses it), and an unsigned one gets 400 `InvalidRequest`; S3 Control calls on the access point are unaffected. Contributed by @iot-rocket.
+- **CloudFront — `CreateFunction` tags** — the request's `Tags` were dropped, so `ListTagsForResource` on the new function's ARN was empty and Terraform re-planned `tags_all` on `aws_cloudfront_function`; they are now stored, a tag without `Value` is listed with an empty one, a refused create stores none, and `DeleteFunction` removes them so a function created again under the same name starts without them. `CreateFunction` and `UpdateFunction` answer invalid base64 code with `MalformedInput` "Invalid Base64 encoding", and `CreateFunction` now refuses what AWS refuses, before the name lookup: a missing or empty `FunctionCode`, a missing `FunctionConfig` or `Runtime`, an unknown runtime, a missing or empty `Name`, and a tag key that is missing, empty, over 128 characters or outside letters, numbers, spaces and `_ . : / = + - @` (values over 256 characters or outside the same set), listed together (at most ten) in one `MalformedXML`; and after it, `InvalidTagging` for a repeated key, an `aws:` key or more than 50 tags. Contributed by @kharabasz.
+- **CloudWatch — `PutMetricAlarm` and `PutCompositeAlarm` tags on create** — `Tags` were dropped when either call created an alarm, so Terraform re-planned `tags_all` on `aws_cloudwatch_metric_alarm` and `aws_cloudwatch_composite_alarm`; they are now stored over CBOR, JSON 1.0 and Query, keeping empty values and the last value of a repeated key, and they are still ignored when the call updates an existing alarm, as on AWS (use `TagResource` / `UntagResource`). Both calls now refuse what AWS refuses, before anything is stored (`PutCompositeAlarm` before its `AlarmRule` checks): a wrong JSON type in `Tags` (`MalformedInput`), a missing or empty `Key`, a missing `Value`, a key over 128 or a value over 256 characters, or a `DatapointsToAlarm` below 1, listed together (at most ten) in one `ValidationError`, on create a key or value with characters outside letters, numbers, spaces and `_ . : / = + - @` or too long in UTF-16 units, an `aws:` key on create (`PutMetricAlarm` 403 `AccessDenied`, `PutCompositeAlarm` `ValidationError` "Invalid System Tag"), and more than 50 tags on create. Query error messages are now XML-escaped. Contributed by @kharabasz.
+- **CloudWatch — `DatapointsToAlarm` only when set** — an alarm created by `PutMetricAlarm` or `AWS::CloudWatch::Alarm` without `DatapointsToAlarm` reported it as `EvaluationPeriods`, so Terraform planned `datapoints_to_alarm = 3 -> null`; `DescribeAlarms` now leaves it out unless the request or template sets it, the Query response includes it when set, and an update that omits it clears it. Contributed by @kharabasz.
## [1.5.31] — 2026-10-21
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index e75b7714..22e6f1ff 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -10577,7 +10577,6 @@ def _cw_metric_alarm_record(name, props):
period = int(props.get("Period", 60))
eval_periods = int(props.get("EvaluationPeriods", 1))
dta = props.get("DatapointsToAlarm")
- datapoints = int(dta if dta is not None else eval_periods)
ext_stat = props.get("ExtendedStatistic") or None
if isinstance(ext_stat, str) and not ext_stat.strip():
ext_stat = None
@@ -10614,7 +10613,6 @@ def _cw_metric_alarm_record(name, props):
"ExtendedStatistic": ext_stat,
"Period": period,
"EvaluationPeriods": eval_periods,
- "DatapointsToAlarm": datapoints,
"Threshold": float(props["Threshold"]),
"ComparisonOperator": comparison,
"TreatMissingData": treat,
@@ -10635,6 +10633,10 @@ def _cw_metric_alarm_record(name, props):
"Unit": props.get("Unit"),
"AlarmConfigurationUpdatedTimestamp": int(time.time()),
}
+ # As with PutMetricAlarm, AWS describes DatapointsToAlarm only while the
+ # template sets it, on create and on update.
+ if dta is not None:
+ alarm["DatapointsToAlarm"] = int(dta)
return alarm
diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.py
index 958aeb89..977baa96 100644
--- a/ministack/services/cloudfront.py
+++ b/ministack/services/cloudfront.py
@@ -62,6 +62,7 @@ import logging
import random
import re
import string
+import unicodedata
import uuid
from datetime import datetime, timezone
from urllib.parse import unquote
@@ -828,16 +829,143 @@ def _cf_decode_function_code(code_b64: str):
try:
return base64.b64decode(code_b64.encode("ascii"), validate=True), None
except Exception:
- return None, _error("InvalidArgument", "FunctionCode is not valid base64.", 400)
+ return None, _error("MalformedInput", "Invalid Base64 encoding", 400)
+
+
+_FUNCTION_RUNTIMES = ("cloudfront-js-1.0", "cloudfront-js-2.0")
+_TAG_PATTERN = "([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)"
+_TAG_SPECIAL_CHARS = "_.:/=+-@"
+_MAX_LISTED_VALIDATION_ERRORS = 10
+_FUNCTION_TAG_LIMIT = 50
+
+
+def _last_child(el, tag):
+ """The last direct child with this local name (AWS keeps the last of a
+ repeated member)."""
+ found = None
+ for child in el:
+ if _local_tag_name(child) == tag:
+ found = child
+ return found
+
+
+def _function_request_tags(el):
+ """CreateFunctionRequest's Tags/Items in order as (Key, Value), None for a
+ missing element, and AWS's parse error for a malformed tag or None. AWS
+ reads every child of the last Items as a tag, whatever its name, keeps the
+ last of a repeated Key or Value, and ignores tags placed directly under
+ Tags."""
+ tags_el = _find(el, "Tags")
+ items_el = _last_child(tags_el, "Items") if tags_el is not None else None
+ tags = []
+ for tag_el in items_el if items_el is not None else []:
+ # Text in a tag without child elements is malformed, even whitespace;
+ # next to children it is ignored.
+ if not len(tag_el) and tag_el.text is not None:
+ return [], "Unexpected complex element termination"
+ if any(len(child) for child in tag_el if _local_tag_name(child) in ("Key", "Value")):
+ return [], "Start of list found where not expected"
+ key_el, value_el = _last_child(tag_el, "Key"), _last_child(tag_el, "Value")
+ tags.append((None if key_el is None else key_el.text or "",
+ None if value_el is None else value_el.text or ""))
+ return tags, None
+
+
+def _function_tag_constraint_errors(tags):
+ """AWS's member constraints on CreateFunction tags: per tag Value, then
+ Key; per member length, then pattern. Value may be absent."""
+ errors = []
+ for i, (key, value) in enumerate(tags, 1):
+ for field, text, limit in (("value", value, 256), ("key", key, 128)):
+ at = f"at 'tags.items.{i}.member.{field}' failed to satisfy constraint:"
+ if text is None:
+ if field == "key":
+ errors.append(f"Value null {at} Member must not be null")
+ continue
+ if field == "key" and not text:
+ errors.append(f"Value '' {at} Member must have length greater than or equal to 1")
+ elif len(text) > limit:
+ errors.append(f"Value '{text}' {at} Member must have length less than or equal to {limit}")
+ if not all(unicodedata.category(ch)[0] in "LNZ" or ch in _TAG_SPECIAL_CHARS for ch in text):
+ errors.append(f"Value '{text}' {at} Member must satisfy regular expression pattern: {_TAG_PATTERN}")
+ return errors
+
+
+def _function_code_and_runtime_errors(el):
+ """The functionCode, functionConfig and runtime constraint messages, in
+ that order, which AWS lists before the tag messages."""
+ errors = []
+ code_el = _find(el, "FunctionCode")
+ if code_el is None:
+ errors.append("Value at 'functionCode' failed to satisfy constraint: Member must not be null")
+ elif not code_el.text:
+ errors.append("Value at 'functionCode' failed to satisfy constraint: "
+ "Member must have length greater than or equal to 1")
+ cfg_el = _find(el, "FunctionConfig")
+ runtime_el = _find(cfg_el, "Runtime") if cfg_el is not None else None
+ if cfg_el is None:
+ errors.append("Value null at 'functionConfig' failed to satisfy constraint: Member must not be null")
+ elif runtime_el is None:
+ errors.append("Value null at 'functionConfig.runtime' failed to satisfy constraint: Member must not be null")
+ elif (runtime_el.text or "") not in _FUNCTION_RUNTIMES:
+ errors.append(f"Value '{runtime_el.text or ''}' at 'functionConfig.runtime' failed to satisfy constraint: "
+ f"Member must satisfy enum value set: [{', '.join(_FUNCTION_RUNTIMES)}]")
+ return errors
+
+
+def _function_name_errors(el):
+ """AWS's constraint messages for a missing or empty Name."""
+ name_el = _find(el, "Name")
+ if name_el is None:
+ return ["Value null at 'name' failed to satisfy constraint: Member must not be null"]
+ if not name_el.text:
+ return ["Value '' at 'name' failed to satisfy constraint: Member must have length greater than or equal to 1",
+ "Value '' at 'name' failed to satisfy constraint: "
+ "Member must satisfy regular expression pattern: [a-zA-Z0-9-_]{1,64}"]
+ return []
+
+
+def _function_tagging_error(tags):
+ """AWS's InvalidTagging checks, after the constraints: a repeated key, then
+ an aws: key, then more than 50 tags."""
+ seen = set()
+ for key, _ in tags:
+ if key in seen:
+ return f"Duplicate tag key: '{key}'."
+ seen.add(key)
+ # A lowercase aws: key anywhere is reported before one in another case.
+ if any(key.startswith("aws:") for key, _ in tags):
+ return "Tag key cannot start with 'aws:'."
+ for key, _ in tags:
+ if key.lower().startswith("aws:"):
+ return f'Invalid System Tag: {key} must be prefixed with "aws:" in lowercase.'
+ if len(tags) > _FUNCTION_TAG_LIMIT:
+ return "Too many tags."
+ return None
def _cf_create_function(headers, body):
el = _parse_body(body)
if el is None:
return _error("MalformedXML", "The XML document is malformed.", 400)
+ # Parse errors first (a malformed tag before invalid base64, wherever
+ # each sits in the document), then the member constraints.
+ tags, tags_parse_error = _function_request_tags(el)
+ if tags_parse_error:
+ return _error("MalformedInput", tags_parse_error, 400)
+ code_el = _find(el, "FunctionCode")
+ if code_el is not None and code_el.text:
+ _, err = _cf_decode_function_code(code_el.text)
+ if err is not None:
+ return err
name = _text(el, "Name")
- if not name:
- return _error("InvalidArgument", "Name is required.", 400)
+ # AWS checks the members before it looks the name up: the code, the
+ # config and runtime, the name and the tags, in one MalformedXML.
+ errors = _function_code_and_runtime_errors(el) + _function_name_errors(el) + _function_tag_constraint_errors(tags)
+ if errors:
+ errors = errors[:_MAX_LISTED_VALIDATION_ERRORS]
+ count = f"{len(errors)} validation error{'s' if len(errors) > 1 else ''} detected"
+ return _error("MalformedXML", f"{count}: {'; '.join(errors)}", 400)
if name in _functions:
return _error("FunctionAlreadyExists", "A function with the same name already exists in this account.", 409)
@@ -848,6 +976,9 @@ def _cf_create_function(headers, body):
code, err = _cf_decode_function_code(_text(el, "FunctionCode"))
if err is not None:
return err
+ tagging_error = _function_tagging_error(tags)
+ if tagging_error:
+ return _error("InvalidTagging", tagging_error, 400)
now = _now_iso()
dev_etag = new_uuid()
@@ -868,6 +999,9 @@ def _cf_create_function(headers, body):
# The body PublishFunction froze; LIVE serves this, not the working copy.
"live_body": None,
}
+ # The validated Tags/Items, as AWS reads them; ListTagsForResource lists
+ # them on the ARN, and a missing Value is an empty one.
+ _tags[fn["arn"]] = [{"Key": key, "Value": value or ""} for key, value in tags]
_functions[name] = fn
logger.info("CreateFunction name=%s", name)
@@ -1041,6 +1175,7 @@ def _cf_delete_function(name: str, headers):
)
del _functions[name]
+ _tags.pop(fn["arn"], None)
logger.info("DeleteFunction name=%s", name)
return 204, {}, b""
diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.py
index 14c1f7f2..d62ef414 100644
--- a/ministack/services/cloudwatch.py
+++ b/ministack/services/cloudwatch.py
@@ -20,9 +20,11 @@ import logging
import os
import re
import time
+import unicodedata
from collections import defaultdict
from datetime import datetime, timezone
from urllib.parse import parse_qs
+from xml.sax.saxutils import escape as _xml_escape
from ministack.core.arn import ArnParseError, parse_arn
from ministack.core.responses import AccountRegionScopedDict, AccountScopedDict, get_account_id, get_region, new_uuid
@@ -524,7 +526,9 @@ async def handle_request(method, path, headers, body, query_params):
logger.error("JSON decode error: %s", e)
cbor_data = {}
else:
- for k, v in parse_qs(body.decode("utf-8", errors="replace")).items():
+ # Blank values kept: "Tags.member.2.Value=" is an empty value on
+ # AWS, while an absent member is null.
+ for k, v in parse_qs(body.decode("utf-8", errors="replace"), keep_blank_values=True).items():
params[k] = v
action = ""
@@ -994,10 +998,7 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):
"ExtendedStatistic": cbor_data.get("ExtendedStatistic"),
"Period": int(cbor_data.get("Period", 60)),
"EvaluationPeriods": int(cbor_data.get("EvaluationPeriods", 1)),
- "DatapointsToAlarm": int(
- cbor_data.get("DatapointsToAlarm")
- or cbor_data.get("EvaluationPeriods", 1)
- ),
+ "DatapointsToAlarm": _optional_int(cbor_data.get("DatapointsToAlarm")),
"Threshold": float(cbor_data.get("Threshold", 0)),
"ComparisonOperator": cbor_data.get("ComparisonOperator"),
"TreatMissingData": cbor_data.get("TreatMissingData", "missing"),
@@ -1050,11 +1051,7 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):
"ExtendedStatistic": _p(params, "ExtendedStatistic") or None,
"Period": int(_p(params, "Period") or "60"),
"EvaluationPeriods": int(_p(params, "EvaluationPeriods") or "1"),
- "DatapointsToAlarm": int(
- _p(params, "DatapointsToAlarm")
- or _p(params, "EvaluationPeriods")
- or "1"
- ),
+ "DatapointsToAlarm": _optional_int(_p(params, "DatapointsToAlarm") or None),
"Threshold": float(_p(params, "Threshold") or "0"),
"ComparisonOperator": _p(params, "ComparisonOperator"),
"TreatMissingData": _p(params, "TreatMissingData") or "missing",
@@ -1077,7 +1074,22 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):
}
is_new = name not in _alarms
+ tags = _alarm_request_tags(params, cbor_data, is_cbor, is_json)
+ refused = _alarm_tags_refusal(tags, alarm["DatapointsToAlarm"], is_new, is_cbor, is_json)
+ if refused:
+ return refused
+
+ # AWS describes DatapointsToAlarm only when the request sets it (absent
+ # and null alike); keep it off the record otherwise.
+ if alarm["DatapointsToAlarm"] is None:
+ del alarm["DatapointsToAlarm"]
+
_alarms[name] = alarm
+ # PutMetricAlarm applies Tags on creation only; on an existing alarm they
+ # are ignored on every protocol (TagResource and UntagResource change them).
+ # A key sent twice keeps its last value.
+ if is_new and tags:
+ _resource_tags[alarm["AlarmArn"]] = {t["Key"]: t["Value"] for t in tags}
if is_new:
_record_history(
@@ -1096,6 +1108,189 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):
return _xml(200, "PutMetricAlarmResponse", "")
+_ALARM_TAG_LIMIT = 50
+
+
+_QUERY_TAG_MEMBER = re.compile(r"Tags\.member\.([1-9][0-9]*)\.(Key|Value)")
+
+
+def _alarm_request_tags(params, cbor_data, is_cbor, is_json=False):
+ """An alarm request's Tags as sent, or None when absent. Query members are
+ read in index order, and one sent without Key or Value keeps that member
+ missing (AWS reports it as null)."""
+ if is_cbor or is_json:
+ return cbor_data.get("Tags")
+ members = {}
+ for param in params:
+ match = _QUERY_TAG_MEMBER.fullmatch(param)
+ if match:
+ members.setdefault(int(match.group(1)), {})[match.group(2)] = _p(params, param)
+ return [members[index] for index in sorted(members)] if members else None
+
+
+def _string_member_type_error(value):
+ """AWS's SerializationException text for a JSON/CBOR value sent where a
+ String is expected ("" where AWS sends no message), or None for a string
+ or null."""
+ if value is None or isinstance(value, str):
+ return None
+ if isinstance(value, bool):
+ return f"{'TRUE' if value else 'FALSE'}_VALUE cannot be converted to String"
+ if isinstance(value, int):
+ return "NUMBER_VALUE cannot be converted to String"
+ if isinstance(value, float):
+ return "DECIMAL_VALUE cannot be converted to String"
+ if isinstance(value, dict):
+ return "Start of structure or map found where not expected"
+ return ""
+
+
+def _tags_serialization_error(tags):
+ """The first wrong JSON type in Tags, in document order, as (code, message,
+ status), or None."""
+ if tags is None:
+ return None
+ if isinstance(tags, dict):
+ return "MalformedInput", "Start of structure or map found where not expected", 400
+ if not isinstance(tags, list):
+ return "MalformedInput", "Unexpected field type", 400
+ for tag in tags:
+ if tag is None:
+ return "InternalFailure", "", 500
+ if isinstance(tag, list):
+ return "MalformedInput", "", 400
+ if not isinstance(tag, dict):
+ return "MalformedInput", "Unexpected value type in payload", 400
+ for field in tag:
+ if field in ("Key", "Value"):
+ message = _string_member_type_error(tag[field])
+ if message is not None:
+ return "MalformedInput", message, 400
+ return None
+
+
+def _tag_constraint_errors(tags):
+ """Constraint messages for each tag in order, Value before Key."""
+ errors = []
+ for i, tag in enumerate(tags or [], 1):
+ value, key = tag.get("Value"), tag.get("Key")
+ if value is None:
+ errors.append(f"Value null at 'tags.{i}.member.value' failed to satisfy constraint: Member must not be null")
+ elif len(value) > 256:
+ errors.append(f"Value '{value}' at 'tags.{i}.member.value' failed to satisfy constraint: "
+ "Member must have length less than or equal to 256")
+ if key is None:
+ errors.append(f"Value null at 'tags.{i}.member.key' failed to satisfy constraint: Member must not be null")
+ elif not key:
+ errors.append(f"Value '' at 'tags.{i}.member.key' failed to satisfy constraint: "
+ "Member must have length greater than or equal to 1")
+ elif len(key) > 128:
+ errors.append(f"Value '{key}' at 'tags.{i}.member.key' failed to satisfy constraint: "
+ "Member must have length less than or equal to 128")
+ return errors
+
+
+_TAG_SPECIAL_CHARS = "_.:/=+-@"
+_TAG_CHARS_MESSAGE = ("Tags can only contain letters, numbers, spaces, and the following special characters: "
+ "_ . : / = + - @")
+_MAX_LISTED_VALIDATION_ERRORS = 10
+
+
+def _java_hashmap_order(keys):
+ """Distinct keys in the iteration order of a java.util.HashMap they were
+ put into: String.hashCode over UTF-16 units, spread (h ^ h >>> 16), default
+ capacity 16 doubled past a 0.75 load, insertion order within a bucket."""
+ unique = list(dict.fromkeys(keys))
+ capacity = 16
+ while len(unique) > capacity * 0.75:
+ capacity *= 2
+
+ def bucket(key):
+ units = key.encode("utf-16-be")
+ h = 0
+ for i in range(0, len(units), 2):
+ h = (31 * h + int.from_bytes(units[i:i + 2], "big")) & 0xFFFFFFFF
+ return (h ^ (h >> 16)) & (capacity - 1)
+
+ return sorted(unique, key=lambda key: (bucket(key), unique.index(key)))
+
+
+def _tagset_error(tags):
+ """The tag-set check AWS runs on create after the member constraints, on
+ the tags de-duplicated by key (a later value replaces an earlier one): a
+ character error anywhere, then the first too-long value, then the first
+ too-long key, in the tag map's iteration order. Length counts UTF-16
+ units; a tag whose key is too long is not checked further."""
+ def too_long(text, limit):
+ return len(text.encode("utf-16-le")) // 2 > limit
+
+ def bad_chars(text):
+ return not all(unicodedata.category(ch)[0] in "LNZ" or ch in _TAG_SPECIAL_CHARS for ch in text)
+
+ values = {tag["Key"]: tag["Value"] for tag in tags or []}
+ order = _java_hashmap_order(tag["Key"] for tag in tags or [])
+ usable = [key for key in order if not too_long(key, 128)]
+ if any(bad_chars(key) or (not too_long(values[key], 256) and bad_chars(values[key])) for key in usable):
+ return _TAG_CHARS_MESSAGE
+ long_value = next((values[key] for key in usable if too_long(values[key], 256)), None)
+ if long_value is not None:
+ text, type_name = long_value, "TagValue"
+ else:
+ text = next((key for key in order if too_long(key, 128)), None)
+ if text is None:
+ return None
+ type_name = "TagKey"
+ return f"'{text}' is not a valid value for com.amazon.aws.platform.billing.tagset.type.{type_name} - it is too long"
+
+
+def _composite_system_tag_error(tags):
+ """PutCompositeAlarm's check of aws: keys, after the tag-set check, in the
+ same tag-map order (the first aws: key in that order is named)."""
+ for key in _java_hashmap_order(tag["Key"] for tag in tags or []):
+ if key.startswith("aws:"):
+ if ":" not in key[4:]:
+ return f"Invalid System Tag: {key} is missing Vendor Id."
+ return f"Invalid System Tag: {key} is not whitelisted for vendor:cloudwatch"
+ if key.lower().startswith("aws:"):
+ return f'Invalid System Tag: {key} must be prefixed with "aws:" in lowercase.'
+ return None
+
+
+def _alarm_tags_refusal(tags, datapoints, is_new, is_cbor, is_json, composite=False):
+ """The error AWS answers for an alarm's Tags (and PutMetricAlarm's
+ DatapointsToAlarm), in AWS's order, or None. A refused call stores
+ nothing. The two calls differ only in how they refuse an aws: key."""
+ def refuse(code, message, status):
+ return _error(code, "" if is_cbor and code == "MalformedInput" else message, status,
+ use_json=is_json, use_cbor=is_cbor)
+
+ if is_cbor or is_json:
+ wrong_type = _tags_serialization_error(tags)
+ if wrong_type:
+ return refuse(*wrong_type)
+ # The aws: prefix is refused only when the call creates the alarm (an
+ # update ignores its Tags), and before the member constraints.
+ if is_new and not composite and any(isinstance(t.get("Key"), str) and t["Key"].lower().startswith("aws:")
+ for t in tags or []):
+ return refuse("AccessDenied", 'The provided tag keys must not start with any case of "aws:"', 403)
+ errors = _tag_constraint_errors(tags)
+ if datapoints is not None and datapoints < 1:
+ errors.append(f"Value '{datapoints}' at 'datapointsToAlarm' failed to satisfy constraint: "
+ "Member must have value greater than or equal to 1")
+ if errors:
+ # AWS lists at most ten, and counts only those.
+ errors = errors[:_MAX_LISTED_VALIDATION_ERRORS]
+ count = f"{len(errors)} validation error{'s' if len(errors) > 1 else ''} detected"
+ return refuse("ValidationError", f"{count}: {'; '.join(errors)}", 400)
+ if is_new:
+ invalid = _tagset_error(tags) or (_composite_system_tag_error(tags) if composite else None)
+ if invalid:
+ return refuse("ValidationError", invalid, 400)
+ if is_new and len({t["Key"] for t in tags or []}) > _ALARM_TAG_LIMIT:
+ return refuse("ValidationError", "The resultant tag set must not have more than 50 user tags.", 400)
+ return None
+
+
# ---------------------------------------------------------------------------
# Composite alarm rules
# ---------------------------------------------------------------------------
@@ -1366,6 +1561,14 @@ def _put_composite_alarm(params, cbor_data, is_cbor, is_json=False):
insuff_actions.append(_p(params, f"InsufficientDataActions.member.{ii}"))
ii += 1
+ # Tags are checked before the rule, and stored only when the call creates
+ # the alarm (an update ignores them), as with PutMetricAlarm.
+ is_new = name not in _composite_alarms
+ tags = _alarm_request_tags(params, cbor_data, is_cbor, is_json)
+ refused = _alarm_tags_refusal(tags, None, is_new, is_cbor, is_json, composite=True)
+ if refused:
+ return refused
+
try:
refs = _rule_refs(_parse_alarm_rule(alarm_rule))
except ValueError as exc:
@@ -1405,6 +1608,8 @@ def _put_composite_alarm(params, cbor_data, is_cbor, is_json=False):
if key in existing:
alarm[key] = existing[key]
_composite_alarms[name] = alarm
+ if is_new and tags:
+ _resource_tags[alarm["AlarmArn"]] = {t["Key"]: t["Value"] for t in tags}
new_state = _composite_rule_state(alarm)
if not existing or new_state != alarm["StateValue"]:
verb = "was updated and its new alarm rule evaluates to" if existing else \
@@ -1536,7 +1741,8 @@ def _describe_alarms(params, cbor_data, is_cbor, is_json=False):
f"<Namespace>{a.get('Namespace','')}</Namespace><Threshold>{a.get('Threshold','')}</Threshold>"
f"<ComparisonOperator>{a.get('ComparisonOperator','')}</ComparisonOperator>"
f"<EvaluationPeriods>{a.get('EvaluationPeriods','')}</EvaluationPeriods>"
- f"<StateReason>{a.get('StateReason','')}</StateReason>"
+ + (f"<DatapointsToAlarm>{a['DatapointsToAlarm']}</DatapointsToAlarm>" if "DatapointsToAlarm" in a else "")
+ + f"<StateReason>{a.get('StateReason','')}</StateReason>"
f"</member>"
for a in metric_alarms
)
@@ -2080,6 +2286,11 @@ def _p(params, key, default=""):
return val[0] if isinstance(val, list) else val
+def _optional_int(value):
+ """``int(value)``, or ``None`` when the request leaves the member unset."""
+ return None if value is None else int(value)
+
+
def _cbor_timestamp(value):
"""Encode an epoch/ISO timestamp as CBOR tag 1 (epoch date-time).
@@ -2234,6 +2445,10 @@ def _xml(status, root_tag, inner):
return status, {"Content-Type": "application/xml"}, body
+# AWS escapes the Query error message, quotes included (&quot;).
+_XML_QUOTE = {'"': "&quot;"}
+
+
def _error(code, message, status, use_json=False, use_cbor=False):
if use_cbor:
try:
@@ -2252,7 +2467,8 @@ def _error(code, message, status, use_json=False, use_cbor=False):
fault_type = "Sender" if status < 500 else "Receiver"
body = (
f'<ErrorResponse xmlns="http://monitoring.amazonaws.com/doc/2010-08-01/">\n'
- f" <Error><Type>{fault_type}</Type><Code>{code}</Code><Message>{message}</Message></Error>\n"
+ f" <Error><Type>{fault_type}</Type><Code>{code}</Code>"
+ f"<Message>{_xml_escape(message, _XML_QUOTE)}</Message></Error>\n"
f" <RequestId>{new_uuid()}</RequestId>\n"
f"</ErrorResponse>"
).encode("utf-8")
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index ec70ccbb..91b4cfc8 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -25811,6 +25811,40 @@ def test_cfn_cloudwatch_alarm_update_drops_omitted_properties(cfn, cw):
_delete_cfn_test_stack(cfn, stack_name)
+def test_cfn_cloudwatch_alarm_datapoints_to_alarm_only_when_declared(cfn, cw):
+ """The alarm reports DatapointsToAlarm only while the template sets it.
+ AWS: captured 2026-10-20 (cloudfront-function-and-alarm-tags C20, C21, C22)."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-alarm-dta-{uid}"
+ alarm_name = f"cfn-alarm-dta-{uid}"
+ base = {
+ "AlarmName": alarm_name, "MetricName": "Errors", "Namespace": f"CfnAlarmDta/{uid}",
+ "Statistic": "Sum", "Period": 60, "EvaluationPeriods": 3,
+ "Threshold": 1, "ComparisonOperator": "GreaterThanThreshold",
+ }
+
+ def template(**extra):
+ return json.dumps({"Resources": {"Alarm": {
+ "Type": "AWS::CloudWatch::Alarm", "Properties": {**base, **extra}}}})
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template())
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ assert "DatapointsToAlarm" not in cw.describe_alarms(AlarmNames=[alarm_name])["MetricAlarms"][0]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(DatapointsToAlarm=2))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert cw.describe_alarms(AlarmNames=[alarm_name])["MetricAlarms"][0]["DatapointsToAlarm"] == 2
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template())
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert "DatapointsToAlarm" not in cw.describe_alarms(AlarmNames=[alarm_name])["MetricAlarms"][0]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
def test_cfn_cloudwatch_alarm_update_recreates_an_alarm_deleted_out_of_band(cfn, cw):
"""An alarm removed through DeleteAlarms while its stack still declares it
is created again by the next update (the replacement path), under the
diff --git a/tests/test_cloudfront.py b/tests/test_cloudfront.py
index 83fc2845..8fb82b74 100644
--- a/tests/test_cloudfront.py
+++ b/tests/test_cloudfront.py
@@ -4197,3 +4197,462 @@ def test_cloudfront_vpc_origin_list_max_items_bounds(cloudfront, max_items, expe
assert _vo_error(exc) == (400, "InvalidArgument", "MaxItems must be a non-zero positive integer.")
else:
assert cloudfront.list_vpc_origins(MaxItems=max_items)["VpcOriginList"]["MaxItems"] == expected
+
+
+def _cf_create_tagged_function(cloudfront, name, **kwargs):
+ return cloudfront.create_function(
+ Name=name, FunctionConfig={"Comment": "", "Runtime": "cloudfront-js-2.0"},
+ FunctionCode=b"function handler(event) { return event.request; }", **kwargs)
+
+
+def _cf_delete_function_if_present(cloudfront, name):
+ try:
+ etag = cloudfront.describe_function(Name=name, Stage="DEVELOPMENT")["ETag"]
+ except ClientError:
+ return
+ cloudfront.delete_function(Name=name, IfMatch=etag)
+
+
+def _cf_tag_items(cloudfront, arn):
+ return cloudfront.list_tags_for_resource(Resource=arn)["Tags"].get("Items", [])
+
+
+def test_cloudfront_create_function_stores_request_tags(cloudfront):
+ """CreateFunctionRequest's Tags are listed on the function ARN, and
+ TagResource / UntagResource then change that same set.
+ AWS: captured 2026-10-20 (cloudfront-function-and-alarm-tags C1, C2, C3)."""
+ name = f"tagged-fn-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ fn = _cf_create_tagged_function(
+ cloudfront, name, Tags={"Items": [{"Key": "environment", "Value": "dev"}]})
+ assert fn["ResponseMetadata"]["HTTPStatusCode"] == 201
+ arn = fn["FunctionSummary"]["FunctionMetadata"]["FunctionARN"]
+ assert arn.endswith(f":function/{name}") and arn.startswith("arn:aws:cloudfront::")
+ assert _cf_tag_items(cloudfront, arn) == [{"Key": "environment", "Value": "dev"}]
+
+ cloudfront.tag_resource(Resource=arn, Tags={"Items": [{"Key": "team", "Value": "edge"}]})
+ cloudfront.untag_resource(Resource=arn, TagKeys={"Items": ["environment"]})
+ assert _cf_tag_items(cloudfront, arn) == [{"Key": "team", "Value": "edge"}]
+ finally:
+ _cf_delete_function_if_present(cloudfront, name)
+
+
+def test_cloudfront_create_function_with_empty_tags_has_none(cloudfront):
+ """AWS: captured 2026-10-20 (cloudfront-function-and-alarm-tags C4)."""
+ name = f"untagged-fn-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ fn = _cf_create_tagged_function(cloudfront, name, Tags={"Items": []})
+ arn = fn["FunctionSummary"]["FunctionMetadata"]["FunctionARN"]
+ assert _cf_tag_items(cloudfront, arn) == []
+ finally:
+ _cf_delete_function_if_present(cloudfront, name)
+
+
+def test_cloudfront_create_function_tag_without_value_lists_empty_value(cloudfront):
+ """AWS: captured 2026-10-21 (2309-uncertainties U1:cf-tag-without-value,
+ U1:cf-tag-empty-value)."""
+ name = f"novalue-fn-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ fn = _cf_create_tagged_function(
+ cloudfront, name, Tags={"Items": [{"Key": "novalue"}, {"Key": "empty", "Value": ""}]})
+ arn = fn["FunctionSummary"]["FunctionMetadata"]["FunctionARN"]
+ items = {t["Key"]: t["Value"] for t in _cf_tag_items(cloudfront, arn)}
+ assert items == {"novalue": "", "empty": ""}
+ finally:
+ _cf_delete_function_if_present(cloudfront, name)
+
+
+def test_cloudfront_create_function_already_exists_keeps_existing_tags(cloudfront):
+ """A refused second CreateFunction under the same name leaves the first
+ function's tags alone.
+ AWS: captured 2026-10-21 (2309-uncertainties U3:cf-already-exists-with-other-tags)."""
+ name = f"exists-fn-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ fn = _cf_create_tagged_function(cloudfront, name, Tags={"Items": [{"Key": "team", "Value": "edge"}]})
+ arn = fn["FunctionSummary"]["FunctionMetadata"]["FunctionARN"]
+ with pytest.raises(ClientError) as exc:
+ _cf_create_tagged_function(cloudfront, name, Tags={"Items": [{"Key": "other", "Value": "x"}]})
+ assert exc.value.response["Error"]["Code"] == "FunctionAlreadyExists"
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409
+ assert _cf_tag_items(cloudfront, arn) == [{"Key": "team", "Value": "edge"}]
+ finally:
+ _cf_delete_function_if_present(cloudfront, name)
+
+
+def test_cloudfront_delete_function_drops_its_tags(cloudfront):
+ """A function created again under a deleted function's name (same ARN)
+ starts without the old function's tags.
+ AWS: captured 2026-10-20 (cloudfront-function-and-alarm-tags C5, C6, C7)."""
+ name = f"recreated-fn-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ fn = _cf_create_tagged_function(
+ cloudfront, name, Tags={"Items": [{"Key": "environment", "Value": "dev"}]})
+ arn = fn["FunctionSummary"]["FunctionMetadata"]["FunctionARN"]
+ deleted = cloudfront.delete_function(Name=name, IfMatch=fn["ETag"])
+ assert deleted["ResponseMetadata"]["HTTPStatusCode"] == 204
+
+ again = _cf_create_tagged_function(cloudfront, name, Tags={"Items": [{"Key": "team", "Value": "edge"}]})
+ assert again["ResponseMetadata"]["HTTPStatusCode"] == 201
+ assert again["FunctionSummary"]["FunctionMetadata"]["FunctionARN"] == arn
+ assert _cf_tag_items(cloudfront, arn) == [{"Key": "team", "Value": "edge"}]
+ finally:
+ _cf_delete_function_if_present(cloudfront, name)
+
+
+_CF_PATTERN = "Member must satisfy regular expression pattern: ([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)"
+_CF_FILLER = [{"Key": "f1", "Value": "v"}, {"Key": "f2", "Value": "v"}]
+
+
+def _cf_unvalidated():
+ """boto3 without client-side checks, so it sends what AWS refuses."""
+ return __import__("conftest").make_client("cloudfront", additional_config_kwargs={"parameter_validation": False})
+
+
+def _cf_create_error(client, name, tags, **over):
+ kwargs = {"Name": name, "FunctionConfig": {"Comment": "", "Runtime": "cloudfront-js-2.0"},
+ "FunctionCode": b"function handler(event) { return event.request; }", "Tags": {"Items": tags}, **over}
+ with pytest.raises(ClientError) as exc:
+ client.create_function(**kwargs)
+ err = exc.value.response
+ return err["ResponseMetadata"]["HTTPStatusCode"], err["Error"]["Code"], err["Error"]["Message"]
+
+
+def _cf_function_exists(cloudfront, name):
+ try:
+ cloudfront.describe_function(Name=name, Stage="DEVELOPMENT")
+ return True
+ except ClientError:
+ return False
+
+
+def test_cloudfront_create_function_refuses_tag_constraint_violations(cloudfront):
+ """Member constraints come back as one MalformedXML: the code and runtime
+ first, then per tag Value before Key, per member length before pattern, at
+ most ten; nothing is created, and they come before FunctionAlreadyExists.
+ AWS: captured 2026-10-21 (2309-uncertainties F:empty-key, F:missing-key,
+ F:key-129, F:value-257, F:key-hash, F:key-amp, F:key-emoji, F:value-hash,
+ F:key-127-plus-emoji, F:key-hash-and-key-129, F:dup-and-key-129,
+ F:aws-prefix-and-key-129, F:dup-and-key-hash, F:dup-and-empty-code,
+ F:dup-and-bad-runtime, F:key-129-and-already-exists,
+ G:key-hash-and-value-hash-same-tag, G:key-129-and-value-257-same-tag,
+ G:key-129-hashes, G:missing-key-and-value-hash, G:eleven-bad-keys,
+ G:key-129-and-empty-code, G:key-129-and-bad-runtime; U10:cf-create-refused-empty-code;
+ H:bad-key-then-bad-value-next-tag, H:bad-value-then-bad-key-next-tag, H:key-combining-mark,
+ H:empty-code-and-bad-runtime)."""
+ raw = _cf_unvalidated()
+ dup = [{"Key": "dup", "Value": "a"}, {"Key": "dup", "Value": "b"}]
+
+ def at(i, field):
+ return f"at 'tags.items.{i}.member.{field}' failed to satisfy constraint:"
+
+ def one(text):
+ return f"1 validation error detected: {text}"
+
+ long_key, long_value = "k" * 129, "v" * 257
+ length_key = f"Value '{long_key}' {at(3, 'key')} Member must have length less than or equal to 128"
+ code_error = "Value at 'functionCode' failed to satisfy constraint: Member must have length greater than or equal to 1"
+ runtime_error = ("Value 'cloudfront-js-9.9' at 'functionConfig.runtime' failed to satisfy constraint: "
+ "Member must satisfy enum value set: [cloudfront-js-1.0, cloudfront-js-2.0]")
+ cases = [
+ ([{"Key": "", "Value": "x"}], {}, one(f"Value '' {at(3, 'key')} Member must have length greater than or equal to 1")),
+ ([{"Value": "x"}], {}, one(f"Value null {at(3, 'key')} Member must not be null")),
+ ([{"Key": long_key, "Value": "x"}], {}, one(length_key)),
+ ([{"Key": "a", "Value": long_value}], {},
+ one(f"Value '{long_value}' {at(3, 'value')} Member must have length less than or equal to 256")),
+ ([{"Key": "a#b", "Value": "x"}], {}, one(f"Value 'a#b' {at(3, 'key')} {_CF_PATTERN}")),
+ ([{"Key": "a&b", "Value": "x"}], {}, one(f"Value 'a&b' {at(3, 'key')} {_CF_PATTERN}")),
+ ([{"Key": "a", "Value": "a#b"}], {}, one(f"Value 'a#b' {at(3, 'value')} {_CF_PATTERN}")),
+ ([{"Key": "k" * 127 + "\U0001F600", "Value": "x"}], {},
+ one(f"Value '{'k' * 127}\U0001F600' {at(3, 'key')} {_CF_PATTERN}")),
+ ([{"Key": "a#b", "Value": "c#d"}], {}, f"2 validation errors detected: Value 'c#d' {at(3, 'value')} {_CF_PATTERN}; "
+ f"Value 'a#b' {at(3, 'key')} {_CF_PATTERN}"),
+ ([{"Key": "#" * 129, "Value": "x"}], {},
+ f"2 validation errors detected: Value '{'#' * 129}' {at(3, 'key')} Member must have length less than or equal to 128; "
+ f"Value '{'#' * 129}' {at(3, 'key')} {_CF_PATTERN}"),
+ ([{"Value": "c#d"}], {}, f"2 validation errors detected: Value 'c#d' {at(3, 'value')} {_CF_PATTERN}; "
+ f"Value null {at(3, 'key')} Member must not be null"),
+ ([{"Key": "a#b", "Value": "x"}, {"Key": long_key, "Value": "x"}], {},
+ f"2 validation errors detected: Value 'a#b' {at(3, 'key')} {_CF_PATTERN}; "
+ f"Value '{long_key}' {at(4, 'key')} Member must have length less than or equal to 128"),
+ ([{"Key": f"a#{n}", "Value": "x"} for n in range(11)], {},
+ "10 validation errors detected: " + "; ".join(f"Value 'a#{n}' {at(n + 3, 'key')} {_CF_PATTERN}" for n in range(10))),
+ (dup + [{"Key": long_key, "Value": "x"}], {},
+ one(f"Value '{long_key}' {at(5, 'key')} Member must have length less than or equal to 128")),
+ ([{"Key": long_key, "Value": "x"}], {"FunctionCode": b""}, f"2 validation errors detected: {code_error}; {length_key}"),
+ ([{"Key": long_key, "Value": "x"}], {"FunctionConfig": {"Comment": "", "Runtime": "cloudfront-js-9.9"}},
+ f"2 validation errors detected: {runtime_error}; {length_key}"),
+ ([{"Key": "a#b", "Value": "x"}, {"Key": "c", "Value": "d#e"}], {},
+ f"2 validation errors detected: Value 'a#b' {at(3, 'key')} {_CF_PATTERN}; Value 'd#e' {at(4, 'value')} {_CF_PATTERN}"),
+ ([{"Key": "a", "Value": "b#c"}, {"Key": "d#e", "Value": "x"}], {},
+ f"2 validation errors detected: Value 'b#c' {at(3, 'value')} {_CF_PATTERN}; Value 'd#e' {at(4, 'key')} {_CF_PATTERN}"),
+ ([{"Key": "e\u0301", "Value": "x"}], {}, one(f"Value 'e\u0301' {at(3, 'key')} {_CF_PATTERN}")),
+ ([], {"FunctionCode": b"", "FunctionConfig": {"Comment": "", "Runtime": "cloudfront-js-9.9"}},
+ f"2 validation errors detected: {code_error}; {runtime_error}"),
+ (dup, {"FunctionCode": b""}, one(code_error)),
+ (dup, {"FunctionConfig": {"Comment": "", "Runtime": "cloudfront-js-9.9"}}, one(runtime_error)),
+ ]
+ for i, (tags, over, message) in enumerate(cases):
+ name = f"cf-constraint-{i}-{_uuid_mod.uuid4().hex[:8]}"
+ assert _cf_create_error(raw, name, _CF_FILLER + tags, **over) == (400, "MalformedXML", message), i
+ assert not _cf_function_exists(cloudfront, name), i
+
+ name = f"cf-constraint-exists-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ _cf_create_tagged_function(cloudfront, name)
+ assert _cf_create_error(raw, name, _CF_FILLER + [{"Key": long_key, "Value": "x"}]) == (
+ 400, "MalformedXML", one(length_key))
+ finally:
+ _cf_delete_function_if_present(cloudfront, name)
+
+
+def test_cloudfront_create_function_refuses_invalid_tagging(cloudfront):
+ """After the constraints and the name lookup, InvalidTagging: a repeated
+ key, then an aws: key, then more than 50 tags; nothing is created.
+ AWS: captured 2026-10-21 (2309-uncertainties F:dup-keys, U2:cf-duplicate-keys,
+ F:key-aws-prefix, F:key-AWS-prefix, F:51-tags, F:dup-and-aws-prefix,
+ F:51-tags-and-dup, F:51-tags-and-aws-prefix, F:dup-and-invalid-code,
+ F:dup-and-already-exists, H:two-dup-pairs-abba, H:mixed-case-Aws, H:AWS-then-aws,
+ H:aws-then-AWS)."""
+ raw = _cf_unvalidated()
+ many = [{"Key": f"k{n:02d}", "Value": "v"} for n in range(48)]
+ dup = [{"Key": "dup", "Value": "a"}, {"Key": "dup", "Value": "b"}]
+ cases = [
+ (dup, "Duplicate tag key: 'dup'."),
+ ([{"Key": "aws:x", "Value": "x"}], "Tag key cannot start with 'aws:'."),
+ ([{"Key": "AWS:x", "Value": "x"}], 'Invalid System Tag: AWS:x must be prefixed with "aws:" in lowercase.'),
+ (many + [{"Key": "k48", "Value": "v"}], "Too many tags."),
+ (dup + [{"Key": "aws:x", "Value": "x"}], "Duplicate tag key: 'dup'."),
+ (many + [{"Key": "k00", "Value": "again"}], "Duplicate tag key: 'k00'."),
+ (many + [{"Key": "aws:x", "Value": "x"}], "Tag key cannot start with 'aws:'."),
+ ([{"Key": "a", "Value": "1"}, {"Key": "b", "Value": "2"}, {"Key": "b", "Value": "3"}, {"Key": "a", "Value": "4"}],
+ "Duplicate tag key: 'b'."),
+ ([{"Key": "Aws:x", "Value": "x"}], 'Invalid System Tag: Aws:x must be prefixed with "aws:" in lowercase.'),
+ ([{"Key": "AWS:x", "Value": "x"}, {"Key": "aws:y", "Value": "y"}], "Tag key cannot start with 'aws:'."),
+ ([{"Key": "aws:y", "Value": "y"}, {"Key": "AWS:x", "Value": "x"}], "Tag key cannot start with 'aws:'."),
+ ]
+ for i, (tags, message) in enumerate(cases):
+ name = f"cf-tagging-{i}-{_uuid_mod.uuid4().hex[:8]}"
+ assert _cf_create_error(raw, name, _CF_FILLER + tags) == (400, "InvalidTagging", message), i
+ assert not _cf_function_exists(cloudfront, name), i
+ name = f"cf-tagging-code-{_uuid_mod.uuid4().hex[:8]}"
+ assert _cf_create_error(raw, name, _CF_FILLER + dup, FunctionCode=b"this is not javascript {{{") == (
+ 400, "InvalidTagging", "Duplicate tag key: 'dup'.")
+
+ name = f"cf-tagging-exists-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ _cf_create_tagged_function(cloudfront, name)
+ status, code, _ = _cf_create_error(raw, name, _CF_FILLER + dup)
+ assert (status, code) == (409, "FunctionAlreadyExists")
+ finally:
+ _cf_delete_function_if_present(cloudfront, name)
+
+
+def test_cloudfront_create_function_tag_values_aws_accepts(cloudfront):
+ """AWS: captured 2026-10-21 (2309-uncertainties F:key-128, F:value-256,
+ F:key-space-e-acute, F:key-specials, F:value-aws-prefix,
+ F:dup-keys-differing-case, F:50-tags, F:tags-without-items, G:missing-value,
+ U1:cf-tag-without-value, H:key-roman-numeral-Nl, H:key-superscript-No,
+ H:key-line-separator-Zl, I:raw-key-with-spaces-around)."""
+ cases = [
+ ([{"Key": "k" * 128, "Value": "x"}, {"Key": "a", "Value": "v" * 256}], {"k" * 128: "x", "a": "v" * 256}),
+ ([{"Key": "a b\u00e9", "Value": "x"}, {"Key": "_.:/=+-@", "Value": "x"}], {"a b\u00e9": "x", "_.:/=+-@": "x"}),
+ ([{"Key": "a", "Value": "aws:x"}, {"Key": "dup", "Value": "a"}, {"Key": "DUP", "Value": "b"}],
+ {"a": "aws:x", "dup": "a", "DUP": "b"}),
+ ([{"Key": f"k{n:02d}", "Value": "v"} for n in range(50)], {f"k{n:02d}": "v" for n in range(50)}),
+ ([{"Key": "novalue"}], {"novalue": ""}),
+ ([{"Key": "\u2160", "Value": "x"}, {"Key": "\u00b2", "Value": "x"}, {"Key": "a\u2028b", "Value": "x"},
+ {"Key": " a ", "Value": " b "}], {"\u2160": "x", "\u00b2": "x", "a\u2028b": "x", " a ": " b "}),
+ ]
+ raw = _cf_unvalidated()
+ for i, (tags, expected) in enumerate(cases):
+ name = f"cf-accepted-{i}-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ fn = _cf_create_tagged_function(raw, name, Tags={"Items": tags})
+ arn = fn["FunctionSummary"]["FunctionMetadata"]["FunctionARN"]
+ assert {t["Key"]: t["Value"] for t in _cf_tag_items(cloudfront, arn)} == expected, i
+ finally:
+ _cf_delete_function_if_present(cloudfront, name)
+ name = f"cf-accepted-noitems-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ fn = _cf_create_tagged_function(raw, name, Tags={})
+ assert _cf_tag_items(cloudfront, fn["FunctionSummary"]["FunctionMetadata"]["FunctionARN"]) == []
+ finally:
+ _cf_delete_function_if_present(cloudfront, name)
+
+
+def _cf_raw_create_function(body):
+ """CreateFunction with an exact REST-XML body; returns (status, code, message)."""
+ import urllib.error
+ import urllib.request
+
+ from conftest import ENDPOINT
+ req = urllib.request.Request(f"{ENDPOINT}/2020-05-31/function", data=body.encode(), method="POST", headers={
+ "Content-Type": "application/xml",
+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/cloudfront/aws4_request, "
+ "SignedHeaders=host, Signature=x"})
+ try:
+ with urllib.request.urlopen(req) as resp:
+ return resp.status, None, None
+ except urllib.error.HTTPError as e:
+ text = e.read().decode()
+ code = re.search(r"<Code>(.*?)</Code>", text)
+ message = re.search(r"<Message>(.*?)</Message>", text, re.S)
+ return e.code, code and code.group(1), message and message.group(1)
+
+
+def test_cloudfront_create_function_raw_xml_shapes(cloudfront):
+ """Shapes boto3 can't send: a missing FunctionCode, FunctionConfig or
+ Runtime and an empty Runtime join the MalformedXML list (code, config,
+ runtime, then tags); Tag elements directly under Tags are ignored; every
+ child of the last Items is a tag, whatever its name, and the last of two
+ Keys or Values counts; text in a tag without children, or an element
+ inside a Key or Value, is MalformedInput, then invalid base64 code, before
+ everything else; a missing or empty Name joins the MalformedXML list.
+ AWS: captured 2026-10-21 (2309-uncertainties H:raw-missing-code,
+ H:raw-missing-code-and-key-129, H:raw-missing-config, H:raw-missing-config-and-key-129,
+ H:raw-missing-runtime, H:raw-missing-runtime-and-key-129, H:raw-empty-runtime,
+ I:raw-empty-runtime-and-key-129, I:raw-missing-code-and-missing-config,
+ I:raw-missing-code-and-missing-runtime, H:raw-tags-direct-tag-children,
+ H:raw-tags-direct-valid-children, H:raw-items-non-tag-child,
+ I:raw-items-other-child-name-and-dup, N:cf-items-child-with-text-only,
+ N:cf-key-with-child-element, N:cf-items-child-without-key-or-value,
+ N:cf-key-nested-in-wrapper, N:cf-text-directly-in-items, N:cf-tag-with-two-keys,
+ L:cf-whitespace-only-tag, L:cf-value-with-child-element, L:cf-key-text-and-child,
+ L:cf-first-key-child-last-plain, L:cf-two-values, L:cf-pretty-printed-tag,
+ L:cf-text-before-child, L:cf-text-after-child, L:cf-two-items-elements,
+ L:cf-parse-error-without-name, L:cf-bad-base64-and-key-hash, L:cf-bad-base64-alone,
+ E:cf-tags-before-bad-base64-with-tag-parse-error, E:cf-bad-base64-before-tags-with-tag-parse-error,
+ E:cf-no-name-alone, E:cf-no-name-and-key-129, E:cf-empty-name-and-key-129)."""
+ import base64
+ from xml.sax.saxutils import escape
+ code = base64.b64encode(b"function handler(event) { return event.request; }").decode()
+ config = "<FunctionConfig><Comment></Comment><Runtime>cloudfront-js-2.0</Runtime></FunctionConfig>"
+ long_key = "k" * 129
+ key_error = (f"Value '{long_key}' at 'tags.items.1.member.key' failed to satisfy constraint: "
+ "Member must have length less than or equal to 128")
+ long_items = f"<Tags><Items><Tag><Key>{long_key}</Key><Value>x</Value></Tag></Items></Tags>"
+ missing_code = "Value at 'functionCode' failed to satisfy constraint: Member must not be null"
+ missing_config = "Value null at 'functionConfig' failed to satisfy constraint: Member must not be null"
+ missing_runtime = "Value null at 'functionConfig.runtime' failed to satisfy constraint: Member must not be null"
+ empty_runtime = ("Value '' at 'functionConfig.runtime' failed to satisfy constraint: "
+ "Member must satisfy enum value set: [cloudfront-js-1.0, cloudfront-js-2.0]")
+ no_runtime = "<FunctionConfig><Comment></Comment></FunctionConfig>"
+ blank_runtime = "<FunctionConfig><Comment></Comment><Runtime></Runtime></FunctionConfig>"
+
+ def body(name, code_xml, config_xml, tags_xml=""):
+ return ('<?xml version="1.0" encoding="UTF-8"?>'
+ '<CreateFunctionRequest xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">'
+ f"{code_xml}{config_xml}<Name>{escape(name)}</Name>{tags_xml}</CreateFunctionRequest>")
+
+ with_code = f"<FunctionCode>{code}</FunctionCode>"
+ refused = [
+ ("", config, "", f"1 validation error detected: {missing_code}"),
+ ("", config, long_items, f"2 validation errors detected: {missing_code}; {key_error}"),
+ (with_code, "", "", f"1 validation error detected: {missing_config}"),
+ (with_code, "", long_items, f"2 validation errors detected: {missing_config}; {key_error}"),
+ (with_code, no_runtime, "", f"1 validation error detected: {missing_runtime}"),
+ (with_code, no_runtime, long_items, f"2 validation errors detected: {missing_runtime}; {key_error}"),
+ (with_code, blank_runtime, "", f"1 validation error detected: {empty_runtime}"),
+ (with_code, blank_runtime, long_items, f"2 validation errors detected: {empty_runtime}; {key_error}"),
+ ("", "", "", f"2 validation errors detected: {missing_code}; {missing_config}"),
+ ("", no_runtime, "", f"2 validation errors detected: {missing_code}; {missing_runtime}"),
+ ]
+ for i, (code_xml, config_xml, tags_xml, message) in enumerate(refused):
+ name = f"cf-raw-{i}-{_uuid_mod.uuid4().hex[:8]}"
+ assert _cf_raw_create_function(body(name, code_xml, config_xml, tags_xml)) == (400, "MalformedXML", message), i
+ assert not _cf_function_exists(cloudfront, name), i
+
+ for i, (items, message) in enumerate([
+ ("<Tag>just text</Tag>", "Unexpected complex element termination"),
+ ("<Tag> </Tag>", "Unexpected complex element termination"),
+ ("<Tag><Key><b>x</b></Key><Value>v</Value></Tag>", "Start of list found where not expected"),
+ ("<Tag><Key>k</Key><Value><b>x</b></Value></Tag>", "Start of list found where not expected"),
+ ("<Tag><Key>a<b>x</b></Key><Value>v</Value></Tag>", "Start of list found where not expected"),
+ ("<Tag><Key><b>x</b></Key><Key>k</Key><Value>v</Value></Tag>", "Start of list found where not expected"),
+ ]):
+ name = f"cf-raw-parse-{i}-{_uuid_mod.uuid4().hex[:8]}"
+ assert _cf_raw_create_function(body(name, with_code, config, f"<Tags><Items>{items}</Items></Tags>")) == (
+ 400, "MalformedInput", message), i
+ assert not _cf_function_exists(cloudfront, name), i
+ for i, items in enumerate(["<Tag></Tag>", "<Tag><Wrap><Key>k</Key></Wrap><Value>v</Value></Tag>"]):
+ name = f"cf-raw-nokey-{i}-{_uuid_mod.uuid4().hex[:8]}"
+ assert _cf_raw_create_function(body(name, with_code, config, f"<Tags><Items>{items}</Items></Tags>")) == (
+ 400, "MalformedXML", "1 validation error detected: Value null at 'tags.items.1.member.key' "
+ "failed to satisfy constraint: Member must not be null"), i
+ for i, tags_xml in enumerate(["", "<Tags><Items><Tag><Key>a#b</Key><Value>x</Value></Tag></Items></Tags>"]):
+ name = f"cf-raw-b64-{i}-{_uuid_mod.uuid4().hex[:8]}"
+ assert _cf_raw_create_function(body(name, "<FunctionCode>!!!not-base64!!!</FunctionCode>", config, tags_xml)) == (
+ 400, "MalformedInput", "Invalid Base64 encoding"), i
+ assert _cf_raw_create_function(body("", with_code, config, "<Tags><Items><Tag>x</Tag></Items></Tags>").replace(
+ "<Name></Name>", "")) == (400, "MalformedInput", "Unexpected complex element termination")
+ bad_code = "<FunctionCode>!!!not-base64!!!</FunctionCode>"
+ parse_tags = "<Tags><Items><Tag>x</Tag></Items></Tags>"
+ for i, xml in enumerate([body(f"cf-b64-a-{i}", bad_code, config, parse_tags),
+ body(f"cf-b64-b-{i}", "", config, parse_tags).replace(config, parse_tags + bad_code + config, 1)
+ .replace(parse_tags + "</CreateFunctionRequest>", "</CreateFunctionRequest>")]):
+ assert _cf_raw_create_function(xml) == (400, "MalformedInput", "Unexpected complex element termination"), i
+ null_name = "Value null at 'name' failed to satisfy constraint: Member must not be null"
+ empty_name = ("Value '' at 'name' failed to satisfy constraint: Member must have length greater than or equal to 1; "
+ "Value '' at 'name' failed to satisfy constraint: Member must satisfy regular expression pattern: "
+ "[a-zA-Z0-9-_]{1,64}")
+ no_name = body("x", with_code, config, "").replace("<Name>x</Name>", "")
+ assert _cf_raw_create_function(no_name) == (400, "MalformedXML", f"1 validation error detected: {null_name}")
+ assert _cf_raw_create_function(body("x", with_code, config, long_items).replace("<Name>x</Name>", "")) == (
+ 400, "MalformedXML", f"2 validation errors detected: {null_name}; {key_error}")
+ assert _cf_raw_create_function(body("", with_code, config, long_items)) == (
+ 400, "MalformedXML", f"3 validation errors detected: {empty_name}; {key_error}")
+ name = f"cf-raw-dup-{_uuid_mod.uuid4().hex[:8]}"
+ assert _cf_raw_create_function(body(name, with_code, config, "<Tags><Items><Foo><Key>d</Key><Value>1</Value></Foo>"
+ "<Tag><Key>d</Key><Value>2</Value></Tag></Items></Tags>")) == (
+ 400, "InvalidTagging", "Duplicate tag key: 'd'.")
+ accepted = [
+ ("<Tags><Tag><Key>aws:x</Key><Value>x</Value></Tag><Tag><Key>dup</Key><Value>a</Value></Tag>"
+ "<Tag><Key>dup</Key><Value>b</Value></Tag></Tags>", []),
+ ("<Tags><Tag><Key>team</Key><Value>edge</Value></Tag></Tags>", []),
+ ("<Tags><Items><Tag><Key>a</Key><Value>b</Value></Tag><Foo><Key>x</Key></Foo></Items></Tags>",
+ [{"Key": "a", "Value": "b"}, {"Key": "x", "Value": ""}]),
+ ("<Tags><Items><Tag><Key>a</Key><Value>b</Value></Tag>stray text</Items></Tags>", [{"Key": "a", "Value": "b"}]),
+ ("<Tags><Items><Tag><Key>first</Key><Key>second</Key><Value>v</Value></Tag></Items></Tags>",
+ [{"Key": "second", "Value": "v"}]),
+ ("<Tags><Items><Tag><Key>k</Key><Value>v1</Value><Value>v2</Value></Tag></Items></Tags>",
+ [{"Key": "k", "Value": "v2"}]),
+ ("<Tags><Items><Tag>\n <Key>k</Key>\n <Value>v</Value>\n</Tag></Items></Tags>", [{"Key": "k", "Value": "v"}]),
+ ("<Tags><Items><Tag>junk<Key>k</Key>junk<Value>v</Value></Tag></Items></Tags>", [{"Key": "k", "Value": "v"}]),
+ ("<Tags><Items><Tag><Key>first</Key><Value>v</Value></Tag></Items>"
+ "<Items><Tag><Key>second</Key><Value>v</Value></Tag></Items></Tags>", [{"Key": "second", "Value": "v"}]),
+ ]
+ for i, (tags_xml, expected) in enumerate(accepted):
+ name = f"cf-raw-ok-{i}-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ assert _cf_raw_create_function(body(name, with_code, config, tags_xml))[0] == 201, i
+ arn = cloudfront.describe_function(Name=name, Stage="DEVELOPMENT")["FunctionSummary"]["FunctionMetadata"]["FunctionARN"]
+ assert sorted(_cf_tag_items(cloudfront, arn), key=lambda t: t["Key"]) == expected, i
+ finally:
+ _cf_delete_function_if_present(cloudfront, name)
+
+
+def test_cloudfront_update_function_invalid_base64(cloudfront):
+ """AWS: captured 2026-10-21 (2309-uncertainties L:cf-update-function-bad-base64)."""
+ import urllib.error
+ import urllib.request
+
+ from conftest import ENDPOINT
+ name = f"cf-update-b64-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ fn = _cf_create_tagged_function(cloudfront, name)
+ body = ('<?xml version="1.0" encoding="UTF-8"?>'
+ '<UpdateFunctionRequest xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">'
+ "<FunctionCode>!!!not-base64!!!</FunctionCode><FunctionConfig><Comment></Comment>"
+ "<Runtime>cloudfront-js-2.0</Runtime></FunctionConfig></UpdateFunctionRequest>")
+ req = urllib.request.Request(f"{ENDPOINT}/2020-05-31/function/{name}", data=body.encode(), method="PUT", headers={
+ "Content-Type": "application/xml", "If-Match": fn["ETag"],
+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/cloudfront/aws4_request, "
+ "SignedHeaders=host, Signature=x"})
+ with pytest.raises(urllib.error.HTTPError) as exc:
+ urllib.request.urlopen(req)
+ text = exc.value.read().decode()
+ assert exc.value.code == 400
+ assert re.search(r"<Code>(.*?)</Code>", text).group(1) == "MalformedInput"
+ assert re.search(r"<Message>(.*?)</Message>", text).group(1) == "Invalid Base64 encoding"
+ finally:
+ _cf_delete_function_if_present(cloudfront, name)
diff --git a/tests/test_cloudwatch.py b/tests/test_cloudwatch.py
index b44cfe99..d5c9e61b 100644
--- a/tests/test_cloudwatch.py
+++ b/tests/test_cloudwatch.py
@@ -1,3 +1,4 @@
+import html
import json
import re
import time
@@ -1509,3 +1510,873 @@ def test_cloudwatch_parse_ts_accepts_cbor_datetime():
assert _parse_ts(ts) == ts.timestamp()
assert _parse_ts(ts.replace(tzinfo=None)) == ts.timestamp()
+
+_ALARM_BASE = dict(MetricName="CPUUtilization", Namespace="AWS/EC2", Statistic="Average", Period=60,
+ EvaluationPeriods=3, Threshold=80, ComparisonOperator="GreaterThanThreshold")
+
+
+def _cw_tag_set(cw, arn):
+ """ListTagsForResource as a {Key: Value} dict: AWS lists alarm tags in no
+ order we could pin down, so tests compare sets."""
+ return {t["Key"]: t["Value"] for t in cw.list_tags_for_resource(ResourceARN=arn)["Tags"]}
+
+
+def _cw_raw(protocol, action, params):
+ """A CloudWatch call over Query or JSON 1.0 (boto3 speaks CBOR). Returns
+ (status, body text)."""
+ import urllib.error
+ import urllib.parse
+ import urllib.request
+
+ from conftest import ENDPOINT
+ auth = ("AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/monitoring/aws4_request, "
+ "SignedHeaders=host, Signature=x")
+ if protocol == "query":
+ body = urllib.parse.urlencode({"Action": action, "Version": "2010-08-01", **params}).encode()
+ headers = {"Content-Type": "application/x-www-form-urlencoded", "Authorization": auth}
+ else:
+ body = json.dumps(params).encode()
+ headers = {"Content-Type": "application/x-amz-json-1.0", "x-amzn-query-mode": "true",
+ "X-Amz-Target": f"GraniteServiceVersion20100801.{action}", "Authorization": auth}
+ req = urllib.request.Request(ENDPOINT, data=body, headers=headers)
+ try:
+ with urllib.request.urlopen(req) as resp:
+ return resp.status, resp.read().decode()
+ except urllib.error.HTTPError as e:
+ return e.code, e.read().decode()
+
+
+def test_cloudwatch_put_metric_alarm_applies_tags_on_create_only(cw):
+ """PutMetricAlarm's Tags are stored when it creates the alarm and ignored
+ on an existing one; TagResource still adds to them.
+ AWS: captured 2026-10-20 (cloudfront-function-and-alarm-tags C8, C9, C10)."""
+ name = f"tagged-alarm-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ cw.put_metric_alarm(AlarmName=name, Tags=[{"Key": "team", "Value": "platform"}], **_ALARM_BASE)
+ arn = cw.describe_alarms(AlarmNames=[name])["MetricAlarms"][0]["AlarmArn"]
+ assert _cw_tag_set(cw, arn) == {"team": "platform"}
+
+ cw.put_metric_alarm(AlarmName=name, Tags=[{"Key": "other", "Value": "x"}], **_ALARM_BASE)
+ assert _cw_tag_set(cw, arn) == {"team": "platform"}
+
+ cw.tag_resource(ResourceARN=arn, Tags=[{"Key": "other", "Value": "x"}])
+ assert _cw_tag_set(cw, arn) == {"team": "platform", "other": "x"}
+ finally:
+ cw.delete_alarms(AlarmNames=[name])
+
+
+def test_cloudwatch_put_metric_alarm_tags_ignored_on_alarm_created_without_tags(cw):
+ """AWS: captured 2026-10-21 (2309-uncertainties U9:cbor-created-untagged-then-update-with-tags)."""
+ name = f"untagged-alarm-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ cw.put_metric_alarm(AlarmName=name, **_ALARM_BASE)
+ cw.put_metric_alarm(AlarmName=name, Tags=[{"Key": "team", "Value": "platform"}], **_ALARM_BASE)
+ arn = cw.describe_alarms(AlarmNames=[name])["MetricAlarms"][0]["AlarmArn"]
+ assert cw.list_tags_for_resource(ResourceARN=arn)["Tags"] == []
+ finally:
+ cw.delete_alarms(AlarmNames=[name])
+
+
+def test_cloudwatch_put_metric_alarm_create_tags_empty_and_repeated_keys(cw):
+ """An empty Tags list stores nothing. A key sent twice keeps the last
+ value, and keys that differ only in case are two tags.
+ AWS: captured 2026-10-21 (2309-uncertainties U7:cbor-empty-tags-on-create,
+ U6:cbor-duplicate-keys, U6:cbor-keys-differing-in-case)."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ names = [f"empty-tags-{uid}", f"dup-tags-{uid}", f"case-tags-{uid}"]
+ try:
+ cw.put_metric_alarm(AlarmName=names[0], Tags=[], **_ALARM_BASE)
+ cw.put_metric_alarm(AlarmName=names[1], Tags=[{"Key": "dup", "Value": "a"}, {"Key": "dup", "Value": "b"}],
+ **_ALARM_BASE)
+ cw.put_metric_alarm(AlarmName=names[2], Tags=[{"Key": "dup", "Value": "a"}, {"Key": "DUP", "Value": "b"}],
+ **_ALARM_BASE)
+ by_name = {a["AlarmName"]: a["AlarmArn"] for a in cw.describe_alarms(AlarmNames=names)["MetricAlarms"]}
+ assert cw.list_tags_for_resource(ResourceARN=by_name[names[0]])["Tags"] == []
+ assert _cw_tag_set(cw, by_name[names[1]]) == {"dup": "b"}
+ assert _cw_tag_set(cw, by_name[names[2]]) == {"dup": "a", "DUP": "b"}
+ finally:
+ cw.delete_alarms(AlarmNames=names)
+
+
+def test_cloudwatch_alarm_created_again_after_delete_has_only_its_own_tags(cw):
+ """AWS: captured 2026-10-20 (cloudfront-function-and-alarm-tags C12)."""
+ name = f"recreated-alarm-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ cw.put_metric_alarm(AlarmName=name, Tags=[{"Key": "team", "Value": "platform"}], **_ALARM_BASE)
+ cw.delete_alarms(AlarmNames=[name])
+ cw.put_metric_alarm(AlarmName=name, Tags=[{"Key": "contact", "Value": ""}], **_ALARM_BASE)
+ arn = cw.describe_alarms(AlarmNames=[name])["MetricAlarms"][0]["AlarmArn"]
+ assert cw.list_tags_for_resource(ResourceARN=arn)["Tags"] == [{"Key": "contact", "Value": ""}]
+ finally:
+ cw.delete_alarms(AlarmNames=[name])
+
+
+def test_cloudwatch_put_metric_alarm_returns_datapoints_to_alarm_only_when_set(cw):
+ """An update that leaves DatapointsToAlarm out clears it; a value equal to
+ EvaluationPeriods is still returned.
+ AWS: captured 2026-10-20 (cloudfront-function-and-alarm-tags C13, C14, C15)
+ and 2026-10-21 (2309-uncertainties U8:cbor-dta-equal-to-evaluation-periods)."""
+ name = f"m-of-n-alarm-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ cw.put_metric_alarm(AlarmName=name, **_ALARM_BASE)
+ assert "DatapointsToAlarm" not in cw.describe_alarms(AlarmNames=[name])["MetricAlarms"][0]
+
+ cw.put_metric_alarm(AlarmName=name, DatapointsToAlarm=2, **_ALARM_BASE)
+ assert cw.describe_alarms(AlarmNames=[name])["MetricAlarms"][0]["DatapointsToAlarm"] == 2
+
+ cw.put_metric_alarm(AlarmName=name, **_ALARM_BASE)
+ assert "DatapointsToAlarm" not in cw.describe_alarms(AlarmNames=[name])["MetricAlarms"][0]
+
+ cw.put_metric_alarm(AlarmName=name, DatapointsToAlarm=3, **_ALARM_BASE)
+ assert cw.describe_alarms(AlarmNames=[name])["MetricAlarms"][0]["DatapointsToAlarm"] == 3
+ finally:
+ cw.delete_alarms(AlarmNames=[name])
+
+
+_QUERY_ALARM = {"MetricName": "Errors", "Namespace": "AWS/Lambda", "Statistic": "Sum", "Period": "60",
+ "EvaluationPeriods": "3", "Threshold": "1", "ComparisonOperator": "GreaterThanThreshold"}
+
+
+def test_cloudwatch_query_put_metric_alarm_tags_and_datapoints_to_alarm(cw):
+ """Query: Tags.member.N are stored on create, an empty value included;
+ DescribeAlarms has no <DatapointsToAlarm> until an update sets it, and that
+ update's Tags are ignored.
+ AWS: captured 2026-10-20 (cloudfront-function-and-alarm-tags C16, C17, C18)."""
+ name = f"query-alarm-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ status, body = _cw_raw("query", "PutMetricAlarm", {
+ "AlarmName": name, **_QUERY_ALARM, "Tags.member.1.Key": "team", "Tags.member.1.Value": "platform",
+ "Tags.member.2.Key": "contact", "Tags.member.2.Value": ""})
+ assert status == 200
+ assert re.search(r"<PutMetricAlarmResponse[^>]*>\s*<ResponseMetadata>", body)
+ arn = cw.describe_alarms(AlarmNames=[name])["MetricAlarms"][0]["AlarmArn"]
+ status, body = _cw_raw("query", "ListTagsForResource", {"ResourceARN": arn})
+ assert status == 200
+ members = re.findall(r"<member>(.*?)</member>", body, re.S)
+ tags = {re.search(r"<Key>(.*?)</Key>", m).group(1): re.search(r"<Value>(.*?)</Value>|<Value/>", m).group(1) or ""
+ for m in members}
+ assert tags == {"team": "platform", "contact": ""}
+ status, body = _cw_raw("query", "DescribeAlarms", {"AlarmNames.member.1": name})
+ assert status == 200 and "<EvaluationPeriods>3</EvaluationPeriods>" in body
+ assert "<DatapointsToAlarm>" not in body
+
+ status, _ = _cw_raw("query", "PutMetricAlarm", {
+ "AlarmName": name, **_QUERY_ALARM, "DatapointsToAlarm": "2",
+ "Tags.member.1.Key": "other", "Tags.member.1.Value": "x"})
+ assert status == 200
+ _, body = _cw_raw("query", "DescribeAlarms", {"AlarmNames.member.1": name})
+ assert "<DatapointsToAlarm>2</DatapointsToAlarm>" in body
+ assert _cw_tag_set(cw, arn) == {"team": "platform", "contact": ""}
+ finally:
+ cw.delete_alarms(AlarmNames=[name])
+
+
+def test_cloudwatch_query_put_metric_alarm_tags_ignored_on_alarm_created_without_tags(cw):
+ """AWS: captured 2026-10-21 (2309-uncertainties U9:query-created-untagged-then-update-with-tags)."""
+ name = f"query-untagged-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ assert _cw_raw("query", "PutMetricAlarm", {"AlarmName": name, **_QUERY_ALARM})[0] == 200
+ assert _cw_raw("query", "PutMetricAlarm", {"AlarmName": name, **_QUERY_ALARM, "Tags.member.1.Key": "team",
+ "Tags.member.1.Value": "platform"})[0] == 200
+ arn = cw.describe_alarms(AlarmNames=[name])["MetricAlarms"][0]["AlarmArn"]
+ assert cw.list_tags_for_resource(ResourceARN=arn)["Tags"] == []
+ finally:
+ cw.delete_alarms(AlarmNames=[name])
+
+
+def test_cloudwatch_json_put_metric_alarm_tags_and_datapoints_to_alarm(cw):
+ """JSON 1.0: Tags are stored on create and ignored by an update, whether
+ the alarm had tags or not; DescribeAlarms leaves DatapointsToAlarm out when
+ it is absent or null.
+ AWS: captured 2026-10-20 (cloudfront-function-and-alarm-tags C19) and
+ 2026-10-21 (2309-uncertainties U4:json-update-different-tags,
+ U9:json-created-untagged-then-update-with-tags, U8:json-dta-null)."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ tagged, untagged = f"json-tagged-{uid}", f"json-untagged-{uid}"
+ base = {**_ALARM_BASE}
+ try:
+ status, _ = _cw_raw("json", "PutMetricAlarm", {"AlarmName": tagged, **base,
+ "Tags": [{"Key": "team", "Value": "platform"}]})
+ assert status == 200
+ status, body = _cw_raw("json", "DescribeAlarms", {"AlarmNames": [tagged]})
+ alarm = json.loads(body)["MetricAlarms"][0]
+ assert alarm["EvaluationPeriods"] == 3 and "DatapointsToAlarm" not in alarm
+ status, body = _cw_raw("json", "ListTagsForResource", {"ResourceARN": alarm["AlarmArn"]})
+ assert status == 200 and json.loads(body) == {"Tags": [{"Key": "team", "Value": "platform"}]}
+
+ assert _cw_raw("json", "PutMetricAlarm", {"AlarmName": tagged, **base,
+ "Tags": [{"Key": "other", "Value": "x"}]})[0] == 200
+ assert _cw_tag_set(cw, alarm["AlarmArn"]) == {"team": "platform"}
+
+ assert _cw_raw("json", "PutMetricAlarm", {"AlarmName": untagged, **base, "DatapointsToAlarm": None})[0] == 200
+ assert "DatapointsToAlarm" not in cw.describe_alarms(AlarmNames=[untagged])["MetricAlarms"][0]
+ assert _cw_raw("json", "PutMetricAlarm", {"AlarmName": untagged, **base,
+ "Tags": [{"Key": "team", "Value": "platform"}]})[0] == 200
+ arn = cw.describe_alarms(AlarmNames=[untagged])["MetricAlarms"][0]["AlarmArn"]
+ assert cw.list_tags_for_resource(ResourceARN=arn)["Tags"] == []
+ finally:
+ cw.delete_alarms(AlarmNames=[tagged, untagged])
+
+
+def test_cloudwatch_put_metric_alarm_repeated_key_keeps_last_value_over_json_and_query(cw):
+ """AWS: captured 2026-10-21 (2309-uncertainties U15:json-duplicate-keys,
+ U15:query-duplicate-keys)."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ json_name, query_name = f"json-dup-{uid}", f"query-dup-{uid}"
+ try:
+ assert _cw_raw("json", "PutMetricAlarm", {"AlarmName": json_name, **_ALARM_BASE, "Tags": [
+ {"Key": "dup", "Value": "a"}, {"Key": "dup", "Value": "b"}]})[0] == 200
+ assert _cw_raw("query", "PutMetricAlarm", {
+ "AlarmName": query_name, **_QUERY_ALARM, "Tags.member.1.Key": "dup", "Tags.member.1.Value": "a",
+ "Tags.member.2.Key": "dup", "Tags.member.2.Value": "b"})[0] == 200
+ by_name = {a["AlarmName"]: a["AlarmArn"]
+ for a in cw.describe_alarms(AlarmNames=[json_name, query_name])["MetricAlarms"]}
+ assert _cw_tag_set(cw, by_name[json_name]) == {"dup": "b"}
+ assert _cw_tag_set(cw, by_name[query_name]) == {"dup": "b"}
+ finally:
+ cw.delete_alarms(AlarmNames=[json_name, query_name])
+
+
+def test_cloudwatch_json_put_metric_alarm_null_tags(cw):
+ """"Tags": null creates the alarm without tags, and on an update leaves the
+ alarm's tags as they were.
+ AWS: captured 2026-10-21 (2309-uncertainties U14:json-tags-null-on-create,
+ U14:json-tags-null-on-update)."""
+ name = f"json-null-tags-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ assert _cw_raw("json", "PutMetricAlarm", {"AlarmName": name, **_ALARM_BASE, "Tags": None})[0] == 200
+ arn = cw.describe_alarms(AlarmNames=[name])["MetricAlarms"][0]["AlarmArn"]
+ assert cw.list_tags_for_resource(ResourceARN=arn)["Tags"] == []
+
+ cw.tag_resource(ResourceARN=arn, Tags=[{"Key": "team", "Value": "platform"}])
+ assert _cw_raw("json", "PutMetricAlarm", {"AlarmName": name, **_ALARM_BASE, "Tags": None})[0] == 200
+ assert _cw_tag_set(cw, arn) == {"team": "platform"}
+ finally:
+ cw.delete_alarms(AlarmNames=[name])
+
+
+# Two leading tags put the tag under test at index 3, as in the captures.
+_FILLER_TAGS = [{"Key": "f1", "Value": "v"}, {"Key": "f2", "Value": "v"}]
+_NULL_KEY = "Value null at 'tags.{}.member.key' failed to satisfy constraint: Member must not be null"
+_NULL_VALUE = "Value null at 'tags.{}.member.value' failed to satisfy constraint: Member must not be null"
+_DTA_MIN = ("Value '{}' at 'datapointsToAlarm' failed to satisfy constraint: "
+ "Member must have value greater than or equal to 1")
+_AWS_PREFIX = 'The provided tag keys must not start with any case of "aws:"'
+_TAG_LIMIT = "The resultant tag set must not have more than 50 user tags."
+
+
+def _cw_unvalidated():
+ """boto3 over CBOR without client-side checks, so it sends what AWS refuses."""
+ return __import__("conftest").make_client("cloudwatch", additional_config_kwargs={"parameter_validation": False})
+
+
+def _cw_json_put(name, tags, **extra):
+ """JSON 1.0 PutMetricAlarm; returns (status, message). The message is read
+ as botocore reads it: "message" or "Message", "" when there is none (AWS
+ sends no message for some errors), None on success."""
+ status, body = _cw_raw("json", "PutMetricAlarm", {"AlarmName": name, **_ALARM_BASE, "Tags": tags, **extra})
+ if status < 300:
+ return status, None
+ payload = json.loads(body)
+ return status, payload.get("message", payload.get("Message")) or ""
+
+
+def _cw_alarm_exists(cw, name):
+ return bool(cw.describe_alarms(AlarmNames=[name])["MetricAlarms"])
+
+
+def test_cloudwatch_put_metric_alarm_refuses_tag_constraint_violations(cw):
+ """Each tag is checked Value first, then Key; datapointsToAlarm comes after
+ the tags; all violations are joined in one message, and nothing is created.
+ AWS: captured 2026-10-21 (2309-uncertainties V:json-two-missing-key,
+ V:json-missing-key-and-value-same-tag, V:json-missing-value-then-missing-key,
+ V:json-missing-key-first, V:json-empty-key, V:json-key-129, V:json-value-257,
+ V:json-four-missing-values, V:json-missing-value-and-dta-0, X:json-dta-negative,
+ X:json-value-explicit-null, U5:json-tag-without-value, U19:json-tag-without-key,
+ U18:json-dta-0)."""
+ cases = [
+ (_FILLER_TAGS + [{"Value": "x"}, {"Value": "y"}], {},
+ f"2 validation errors detected: {_NULL_KEY.format(3)}; {_NULL_KEY.format(4)}"),
+ (_FILLER_TAGS + [{}], {}, f"2 validation errors detected: {_NULL_VALUE.format(3)}; {_NULL_KEY.format(3)}"),
+ (_FILLER_TAGS + [{"Key": "a"}, {"Value": "y"}], {},
+ f"2 validation errors detected: {_NULL_VALUE.format(3)}; {_NULL_KEY.format(4)}"),
+ ([{"Value": "x"}] + _FILLER_TAGS, {}, f"1 validation error detected: {_NULL_KEY.format(1)}"),
+ (_FILLER_TAGS + [{"Key": "a", "Value": None}], {}, f"1 validation error detected: {_NULL_VALUE.format(3)}"),
+ (_FILLER_TAGS + [{"Key": "", "Value": "x"}], {},
+ "1 validation error detected: Value '' at 'tags.3.member.key' failed to satisfy constraint: "
+ "Member must have length greater than or equal to 1"),
+ (_FILLER_TAGS + [{"Key": "k" * 129, "Value": "x"}], {},
+ f"1 validation error detected: Value '{'k' * 129}' at 'tags.3.member.key' failed to satisfy constraint: "
+ "Member must have length less than or equal to 128"),
+ (_FILLER_TAGS + [{"Key": "a", "Value": "v" * 257}], {},
+ f"1 validation error detected: Value '{'v' * 257}' at 'tags.3.member.value' failed to satisfy constraint: "
+ "Member must have length less than or equal to 256"),
+ (_FILLER_TAGS + [{"Key": k} for k in "abcd"], {},
+ "4 validation errors detected: " + "; ".join(_NULL_VALUE.format(i) for i in range(3, 7))),
+ (_FILLER_TAGS + [{"Key": "a"}], {"DatapointsToAlarm": 0},
+ f"2 validation errors detected: {_NULL_VALUE.format(3)}; {_DTA_MIN.format(0)}"),
+ (_FILLER_TAGS, {"DatapointsToAlarm": -1}, f"1 validation error detected: {_DTA_MIN.format(-1)}"),
+ (_FILLER_TAGS, {"DatapointsToAlarm": 0}, f"1 validation error detected: {_DTA_MIN.format(0)}"),
+ ]
+ for i, (tags, extra, message) in enumerate(cases):
+ name = f"tag-constraint-{i}-{_uuid_mod.uuid4().hex[:8]}"
+ assert _cw_json_put(name, tags, **extra) == (400, message), i
+ assert not _cw_alarm_exists(cw, name), i
+
+
+def test_cloudwatch_put_metric_alarm_tag_constraint_bounds_are_accepted(cw):
+ """A 128-character key, a 256-character value, an empty value and an
+ unknown member inside a tag are accepted.
+ AWS: captured 2026-10-21 (2309-uncertainties V:json-key-128, V:json-value-256,
+ X:json-unknown-tag-member) and 2026-10-20 (cloudfront-function-and-alarm-tags C12)."""
+ name = f"tag-bounds-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ tags = [{"Key": "k" * 128, "Value": "x"}, {"Key": "a", "Value": "v" * 256}, {"Key": "e", "Value": ""},
+ {"Key": "b", "Value": "c", "Extra": "d"}]
+ assert _cw_json_put(name, tags)[0] == 200
+ arn = cw.describe_alarms(AlarmNames=[name])["MetricAlarms"][0]["AlarmArn"]
+ assert _cw_tag_set(cw, arn) == {"k" * 128: "x", "a": "v" * 256, "e": "", "b": "c"}
+ finally:
+ cw.delete_alarms(AlarmNames=[name])
+
+
+def test_cloudwatch_put_metric_alarm_tag_errors_over_cbor(cw):
+ """boto3's codes and messages over CBOR, as AWS answered them.
+ AWS: captured 2026-10-21 through boto3 (2309-uncertainties Z:boto3-cbor-missing-key,
+ Z:boto3-cbor-aws-prefix, Z:boto3-cbor-dta-0, Z:boto3-cbor-missing-value) and
+ 2026-10-20 (I11:cbor-51-tags); messages also V:cbor-two-missing-key,
+ V:cbor-missing-key-and-value-same-tag."""
+ raw = _cw_unvalidated()
+ cases = [
+ (_FILLER_TAGS + [{"Value": "x"}, {"Value": "y"}], "ValidationError", 400,
+ f"2 validation errors detected: {_NULL_KEY.format(3)}; {_NULL_KEY.format(4)}"),
+ (_FILLER_TAGS + [{}], "ValidationError", 400,
+ f"2 validation errors detected: {_NULL_VALUE.format(3)}; {_NULL_KEY.format(3)}"),
+ (_FILLER_TAGS + [{"Key": "aws:x", "Value": "x"}], "AccessDenied", 403, _AWS_PREFIX),
+ (_FILLER_TAGS + [{"Key": f"k{i:02d}", "Value": "v"} for i in range(49)], "ValidationError", 400, _TAG_LIMIT),
+ (_FILLER_TAGS + [{"Key": "a"}], "ValidationError", 400, f"1 validation error detected: {_NULL_VALUE.format(3)}"),
+ (_FILLER_TAGS + [{"Value": "x"}], "ValidationError", 400, f"1 validation error detected: {_NULL_KEY.format(3)}"),
+ ]
+ for i, (tags, code, status, message) in enumerate(cases):
+ name = f"cbor-tag-error-{i}-{_uuid_mod.uuid4().hex[:8]}"
+ with pytest.raises(ClientError) as exc:
+ raw.put_metric_alarm(AlarmName=name, Tags=tags, **_ALARM_BASE)
+ err = exc.value.response
+ assert (err["Error"]["Code"], err["ResponseMetadata"]["HTTPStatusCode"], err["Error"]["Message"]) == (
+ code, status, message), i
+ assert not _cw_alarm_exists(cw, name), i
+ name = f"cbor-dta-0-{_uuid_mod.uuid4().hex[:8]}"
+ with pytest.raises(ClientError) as exc:
+ raw.put_metric_alarm(AlarmName=name, Tags=_FILLER_TAGS, DatapointsToAlarm=0, **_ALARM_BASE)
+ assert (exc.value.response["Error"]["Code"], exc.value.response["Error"]["Message"]) == (
+ "ValidationError", f"1 validation error detected: {_DTA_MIN.format(0)}")
+
+
+def test_cloudwatch_put_metric_alarm_aws_prefix_refused_on_create_only(cw):
+ """An aws: key (any case) is refused with 403 on create, before the tag
+ constraints and datapointsToAlarm; an update ignores it. A value or a key
+ like "awsx" is fine.
+ AWS: captured 2026-10-21 (2309-uncertainties W:json-aws-prefix,
+ W:json-AWS-upper-prefix, W:json-aws-prefix-and-missing-value,
+ W:json-aws-prefix-and-51-tags, X:json-aws-prefix-and-dta-0,
+ W:json-aws-prefix-in-value-only, W:json-key-awsx-no-colon, W:json-update-aws-prefix,
+ X:json-update-missing-value-and-aws-prefix)."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ for i, (tags, extra) in enumerate([
+ (_FILLER_TAGS + [{"Key": "aws:x", "Value": "x"}], {}),
+ (_FILLER_TAGS + [{"Key": "AWS:x", "Value": "x"}], {}),
+ (_FILLER_TAGS + [{"Key": "aws:x", "Value": "x"}, {"Key": "a"}], {}),
+ (_FILLER_TAGS + [{"Key": f"k{n:02d}", "Value": "v"} for n in range(48)] + [{"Key": "aws:x", "Value": "x"}], {}),
+ (_FILLER_TAGS + [{"Key": "aws:x", "Value": "x"}], {"DatapointsToAlarm": 0}),
+ ]):
+ name = f"aws-prefix-{i}-{uid}"
+ assert _cw_json_put(name, tags, **extra) == (403, _AWS_PREFIX), i
+ assert not _cw_alarm_exists(cw, name), i
+
+ ok, existing = f"aws-in-value-{uid}", f"aws-update-{uid}"
+ try:
+ assert _cw_json_put(ok, [{"Key": "a", "Value": "aws:x"}, {"Key": "awsx", "Value": "x"}])[0] == 200
+ assert _cw_json_put(existing, [{"Key": "team", "Value": "platform"}])[0] == 200
+ assert _cw_json_put(existing, [{"Key": "aws:x", "Value": "x"}], Threshold=82)[0] == 200
+ alarm = cw.describe_alarms(AlarmNames=[existing])["MetricAlarms"][0]
+ assert alarm["Threshold"] == 82
+ assert _cw_tag_set(cw, alarm["AlarmArn"]) == {"team": "platform"}
+ assert _cw_json_put(existing, [{"Key": "aws:x", "Value": "x"}, {"Key": "a"}], Threshold=84) == (
+ 400, f"1 validation error detected: {_NULL_VALUE.format(2)}")
+ assert cw.describe_alarms(AlarmNames=[existing])["MetricAlarms"][0]["Threshold"] == 82
+ finally:
+ cw.delete_alarms(AlarmNames=[ok, existing])
+
+
+def test_cloudwatch_put_metric_alarm_tag_limit_on_create_only(cw):
+ """More than 50 unique keys are refused on create, after the tag
+ constraints; repeated keys count once; an update with 51 tags succeeds and
+ keeps the alarm's tags; a refused update changes nothing.
+ AWS: captured 2026-10-21 (2309-uncertainties W:json-51-tags,
+ V:json-51-tags-and-missing-value, V:json-51-tags-and-key-129,
+ V:json-51-tags-repeated-key-50-unique, V:json-update-51-tags,
+ V:json-update-missing-key, X:json-update-dta-0) and 2026-10-20 (I11:cbor-50-tags)."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ fifty_one = _FILLER_TAGS + [{"Key": f"k{n:02d}", "Value": "v"} for n in range(49)]
+ assert _cw_json_put(f"limit-51-{uid}", fifty_one) == (400, _TAG_LIMIT)
+ assert not _cw_alarm_exists(cw, f"limit-51-{uid}")
+ assert _cw_json_put(f"limit-mv-{uid}", fifty_one[:50] + [{"Key": "z"}]) == (
+ 400, f"1 validation error detected: {_NULL_VALUE.format(51)}")
+ names = [f"limit-dup-{uid}", f"limit-upd-{uid}"]
+ try:
+ assert _cw_json_put(names[0], fifty_one[:50] + [{"Key": "k00", "Value": "again"}])[0] == 200
+ arn = cw.describe_alarms(AlarmNames=[names[0]])["MetricAlarms"][0]["AlarmArn"]
+ assert len(_cw_tag_set(cw, arn)) == 50
+
+ assert _cw_json_put(names[1], [{"Key": "team", "Value": "platform"}])[0] == 200
+ assert _cw_json_put(names[1], fifty_one, Threshold=81)[0] == 200
+ alarm = cw.describe_alarms(AlarmNames=[names[1]])["MetricAlarms"][0]
+ assert alarm["Threshold"] == 81 and _cw_tag_set(cw, alarm["AlarmArn"]) == {"team": "platform"}
+ assert _cw_json_put(names[1], _FILLER_TAGS + [{"Value": "x"}], Threshold=85) == (
+ 400, f"1 validation error detected: {_NULL_KEY.format(3)}")
+ assert _cw_json_put(names[1], [], DatapointsToAlarm=0, Threshold=86) == (
+ 400, f"1 validation error detected: {_DTA_MIN.format(0)}")
+ assert cw.describe_alarms(AlarmNames=[names[1]])["MetricAlarms"][0]["Threshold"] == 81
+ finally:
+ cw.delete_alarms(AlarmNames=names)
+
+
+def test_cloudwatch_put_metric_alarm_refuses_wrong_json_types_in_tags(cw):
+ """The first wrong JSON type in Tags, in document order, before any other
+ check; an update is refused the same way and changes nothing.
+ AWS: captured 2026-10-21 (2309-uncertainties V:json-tags-not-a-list,
+ V:json-tag-not-an-object, V:json-key-number, W:json-value-number, X:json-key-true,
+ Y:json-key-false, X:json-key-list, X:json-key-object, X:json-value-float,
+ Y:json-value-true, Y:json-value-list, Y:json-value-object, X:json-tags-object,
+ Y:json-tags-number, Y:json-tags-true, Y:json-element-number, Y:json-element-list,
+ Y:json-element-true, X:json-tag-null-element, X:json-key-number-and-aws-prefix,
+ Y:json-key-number-then-value-true, Y:json-value-true-then-key-number,
+ W:json-update-key-number)."""
+ t = _FILLER_TAGS
+ cases = [
+ ("x", 400, "Unexpected field type"),
+ (5, 400, "Unexpected field type"),
+ (True, 400, "Unexpected field type"),
+ ({"Key": "a", "Value": "b"}, 400, "Start of structure or map found where not expected"),
+ (t + ["x"], 400, "Unexpected value type in payload"),
+ (t + [5], 400, "Unexpected value type in payload"),
+ (t + [True], 400, "Unexpected value type in payload"),
+ (t + [["a"]], 400, ""),
+ (t + [None], 500, ""),
+ (t + [{"Key": 5, "Value": "x"}], 400, "NUMBER_VALUE cannot be converted to String"),
+ (t + [{"Key": "a", "Value": 5}], 400, "NUMBER_VALUE cannot be converted to String"),
+ (t + [{"Key": "a", "Value": 1.5}], 400, "DECIMAL_VALUE cannot be converted to String"),
+ (t + [{"Key": True, "Value": "x"}], 400, "TRUE_VALUE cannot be converted to String"),
+ (t + [{"Key": False, "Value": "x"}], 400, "FALSE_VALUE cannot be converted to String"),
+ (t + [{"Key": "a", "Value": True}], 400, "TRUE_VALUE cannot be converted to String"),
+ (t + [{"Key": ["a"], "Value": "x"}], 400, ""),
+ (t + [{"Key": "a", "Value": ["x"]}], 400, ""),
+ (t + [{"Key": {"a": 1}, "Value": "x"}], 400, "Start of structure or map found where not expected"),
+ (t + [{"Key": "a", "Value": {"x": 1}}], 400, "Start of structure or map found where not expected"),
+ (t + [{"Key": "aws:x", "Value": "x"}, {"Key": 5, "Value": "x"}], 400, "NUMBER_VALUE cannot be converted to String"),
+ (t + [{"Key": 5, "Value": True}], 400, "NUMBER_VALUE cannot be converted to String"),
+ (t + [{"Value": True, "Key": 5}], 400, "TRUE_VALUE cannot be converted to String"),
+ ]
+ for i, (tags, status, message) in enumerate(cases):
+ name = f"tag-type-{i}-{_uuid_mod.uuid4().hex[:8]}"
+ assert _cw_json_put(name, tags) == (status, message), i
+ assert not _cw_alarm_exists(cw, name), i
+
+ name = f"tag-type-update-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ assert _cw_json_put(name, [{"Key": "team", "Value": "platform"}])[0] == 200
+ assert _cw_json_put(name, t + [{"Key": 5, "Value": "x"}], Threshold=82) == (
+ 400, "NUMBER_VALUE cannot be converted to String")
+ assert cw.describe_alarms(AlarmNames=[name])["MetricAlarms"][0]["Threshold"] == 80
+ finally:
+ cw.delete_alarms(AlarmNames=[name])
+
+
+def test_cloudwatch_query_put_metric_alarm_tag_and_datapoints_errors(cw):
+ """Query: a member without Key or Value is null; DatapointsToAlarm 0 breaks
+ the minimum.
+ AWS: captured 2026-10-21 (2309-uncertainties V:query-member-3-key-only-empty-value-param,
+ U5:query-tag-without-value, U19:query-tag-without-key, U18:query-dta-0, W:query-51-tags,
+ W:query-aws-prefix)."""
+ def put(name, **params):
+ status, body = _cw_raw("query", "PutMetricAlarm", {"AlarmName": name, **_QUERY_ALARM, **params})
+ code = re.search(r"<Code>(.*?)</Code>", body)
+ message = re.search(r"<Message>(.*?)</Message>", body, re.S)
+ return status, code and code.group(1), message and html.unescape(message.group(1))
+
+ filler = {"Tags.member.1.Key": "f1", "Tags.member.1.Value": "v", "Tags.member.2.Key": "f2", "Tags.member.2.Value": "v"}
+ fifty_one = {}
+ for n in range(51):
+ fifty_one.update({f"Tags.member.{n + 1}.Key": f"k{n:02d}", f"Tags.member.{n + 1}.Value": "v"})
+ cases = [
+ ({**filler, "Tags.member.3.Key": "team"}, 400, "ValidationError",
+ f"1 validation error detected: {_NULL_VALUE.format(3)}"),
+ ({**filler, "Tags.member.3.Value": "x"}, 400, "ValidationError",
+ f"1 validation error detected: {_NULL_KEY.format(3)}"),
+ ({**filler, "DatapointsToAlarm": "0"}, 400, "ValidationError", f"1 validation error detected: {_DTA_MIN.format(0)}"),
+ (fifty_one, 400, "ValidationError", _TAG_LIMIT),
+ ({**filler, "Tags.member.3.Key": "aws:x", "Tags.member.3.Value": "x"}, 403, "AccessDenied",
+ _AWS_PREFIX),
+ ]
+ for i, (params, status, code, message) in enumerate(cases):
+ name = f"query-tag-error-{i}-{_uuid_mod.uuid4().hex[:8]}"
+ assert put(name, **params) == (status, code, message), i
+ assert not _cw_alarm_exists(cw, name), i
+
+
+def _cw_cbor_put(name, tags, **extra):
+ """A raw CBOR PutMetricAlarm with query mode, for values boto3 can't send;
+ returns (status, __type, message)."""
+ import urllib.error
+ import urllib.request
+
+ import cbor2
+ from conftest import ENDPOINT
+ req = urllib.request.Request(
+ f"{ENDPOINT}/service/GraniteServiceVersion20100801/operation/PutMetricAlarm",
+ data=cbor2.dumps({"AlarmName": name, **_ALARM_BASE, "Tags": tags, **extra}),
+ headers={"Content-Type": "application/cbor", "Accept": "application/cbor", "smithy-protocol": "rpc-v2-cbor",
+ "x-amzn-query-mode": "true",
+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/monitoring/aws4_request, "
+ "SignedHeaders=host, Signature=x"})
+ try:
+ with urllib.request.urlopen(req) as resp:
+ return resp.status, None, None
+ except urllib.error.HTTPError as e:
+ payload = cbor2.loads(e.read())
+ return e.code, payload.get("__type"), payload.get("message", payload.get("Message")) or ""
+
+
+def test_cloudwatch_cbor_put_metric_alarm_wrong_types_in_tags(cw):
+ """Over CBOR a wrong type is MalformedInput with no message, a null tag is
+ a 500, and bytes count as a wrong type.
+ AWS: captured 2026-10-21 (2309-uncertainties Z:cbor-qm-key-number,
+ Z:cbor-qm-tags-not-a-list, Z:cbor-qm-null-element, Z:cbor-qm-key-bytes,
+ Z:cbor-qm-value-bytes; x-amzn-query-error MalformedInput;Sender and
+ InternalFailure;Receiver)."""
+ for i, (tags, status, code) in enumerate([
+ (_FILLER_TAGS + [{"Key": 5, "Value": "x"}], 400, "MalformedInput"),
+ ("x", 400, "MalformedInput"),
+ (_FILLER_TAGS + [None], 500, "InternalFailure"),
+ (_FILLER_TAGS + [{"Key": b"ab", "Value": "x"}], 400, "MalformedInput"),
+ (_FILLER_TAGS + [{"Key": "a", "Value": b"ab"}], 400, "MalformedInput"),
+ ]):
+ name = f"cbor-type-{i}-{_uuid_mod.uuid4().hex[:8]}"
+ assert _cw_cbor_put(name, tags) == (status, code, ""), i
+ assert not _cw_alarm_exists(cw, name), i
+
+
+def test_cloudwatch_put_metric_alarm_lists_at_most_ten_validation_errors(cw):
+ """AWS: captured 2026-10-21 (2309-uncertainties S:json-10-missing-values,
+ S:json-11-missing-values, S:json-12-missing-values, S:json-5-missing-and-dta-0)."""
+ for n in (10, 11, 12):
+ name = f"ten-errors-{n}-{_uuid_mod.uuid4().hex[:8]}"
+ message = "10 validation errors detected: " + "; ".join(_NULL_VALUE.format(i) for i in range(3, 13))
+ assert _cw_json_put(name, _FILLER_TAGS + [{"Key": f"m{i}"} for i in range(n)]) == (400, message), n
+ name = f"ten-errors-dta-{_uuid_mod.uuid4().hex[:8]}"
+ assert _cw_json_put(name, _FILLER_TAGS + [{"Key": f"m{i}"} for i in range(10)], DatapointsToAlarm=0) == (
+ 400, "10 validation errors detected: " + "; ".join(_NULL_VALUE.format(i) for i in range(3, 13)))
+
+
+def test_cloudwatch_put_metric_alarm_tag_character_and_utf16_length_rules(cw):
+ """On create, keys and values may hold letters, numbers and spaces of any
+ script plus _ . : / = + - @; length is counted in UTF-16 units. The check
+ runs after the member constraints and datapointsToAlarm, before the tag
+ limit, on the tags de-duplicated by key; a character error anywhere wins,
+ then the first too-long value, then the first too-long key, in Java
+ HashMap order of the keys; an update ignores it.
+ AWS: captured 2026-10-21 (2309-uncertainties C:json-key-*, C:json-value-*,
+ C:json-key-127-plus-emoji, C:json-key-hash-and-missing-value, C:json-key-hash-and-51,
+ C:json-key-hash-and-dta-0, C:json-two-bad-char-keys, C:json-key-65-emoji-and-hash,
+ C:json-update-key-hash, Z:json-key-128-e-acute, Z:json-key-129-e-acute,
+ Z:json-key-64-emoji, Z:json-key-65-emoji, S:json-key-and-value-too-long-same-tag,
+ S:json-value-too-long-and-key-bad-char-same-tag, S:json-too-long-then-bad-char-next-tag,
+ S:query-key-hash; which too-long tag is named: M:json-two-too-long-keys,
+ M:json-too-long-value-then-too-long-key, N:json-three-too-long-keys,
+ N:json-two-too-long-keys-reversed-letters, N:json-too-long-key-then-too-long-value,
+ L:json-keys-c-a-b, L:json-value-then-key-repeat-1, L:json-value-then-key-repeat-2,
+ L:json-value-under-z-and-key-a, L:json-key-m-value-b-key-x, L:json-values-under-a-and-b,
+ L:json-values-under-b-and-a, E:json-keys-a-and-e, E:json-keys-e-and-a, E:json-keys-a-d-e-q,
+ E:json-values-under-i-and-x, E:json-values-under-x-and-i, E:json-values-under-k-m-z,
+ E:json-dup-key-short-then-long-value, E:json-bad-char-value-next-to-long-key,
+ E:json-dup-key-long-value-then-short, E:json-dup-key-bad-char-value-then-ok;
+ past twelve keys: Z9:metric-13-keys-long-b-and-a)."""
+ chars = ("Tags can only contain letters, numbers, spaces, and the following special characters: "
+ "_ . : / = + - @")
+ emoji = "\U0001F600"
+
+ def too_long(text, kind):
+ return f"'{text}' is not a valid value for com.amazon.aws.platform.billing.tagset.type.{kind} - it is too long"
+
+ uid = _uuid_mod.uuid4().hex[:8]
+ accepted = [("a b", "x"), ("é", "x"), ("123", "x"), ("_.:/=+-@", "x"), ("日本", "x"),
+ ("a b", "x"), ("1", "x"), ("é" * 128, "x")]
+ names = []
+ try:
+ for i, (key, value) in enumerate(accepted):
+ names.append(f"chars-ok-{i}-{uid}")
+ assert _cw_json_put(names[-1], _FILLER_TAGS + [{"Key": key, "Value": value}])[0] == 200, i
+ refused = [
+ ([{"Key": k, "Value": "x"}], chars) for k in ("a&b", "a<b", "a#b", emoji, "a\tb", "a,b", "a*b")
+ ] + [
+ ([{"Key": "a", "Value": v}], chars) for v in ("a&b", emoji, "a#b", emoji * 128)
+ ] + [
+ ([{"Key": "a", "Value": emoji * 129}], too_long(emoji * 129, "TagValue")),
+ ([{"Key": "k" * 127 + emoji, "Value": "x"}], too_long("k" * 127 + emoji, "TagKey")),
+ ([{"Key": emoji * 64, "Value": "x"}], chars),
+ ([{"Key": emoji * 65, "Value": "x"}], too_long(emoji * 65, "TagKey")),
+ ([{"Key": "k" * 127 + emoji, "Value": emoji * 129}], too_long("k" * 127 + emoji, "TagKey")),
+ ([{"Key": "a#b", "Value": emoji * 129}], chars),
+ ([{"Key": "k" * 127 + emoji, "Value": "x"}, {"Key": "a#b", "Value": "x"}], chars),
+ ([{"Key": "a#b", "Value": "x"}, {"Key": emoji * 65, "Value": "x"}], chars),
+ ([{"Key": "a" * 127 + emoji, "Value": "x"}, {"Key": "b" * 127 + emoji, "Value": "x"},
+ {"Key": "c" * 127 + emoji, "Value": "x"}], too_long("c" * 127 + emoji, "TagKey")),
+ ([{"Key": "c" * 127 + emoji, "Value": "x"}, {"Key": "a" * 127 + emoji, "Value": "x"},
+ {"Key": "b" * 127 + emoji, "Value": "x"}], too_long("c" * 127 + emoji, "TagKey")),
+ ([{"Key": "a" * 127 + emoji, "Value": "x"}, {"Key": "e" * 127 + emoji, "Value": "x"}],
+ too_long("a" * 127 + emoji, "TagKey")),
+ ([{"Key": "e" * 127 + emoji, "Value": "x"}, {"Key": "a" * 127 + emoji, "Value": "x"}],
+ too_long("a" * 127 + emoji, "TagKey")),
+ ([{"Key": c * 127 + emoji, "Value": "x"} for c in "adeq"], too_long("d" * 127 + emoji, "TagKey")),
+ ([{"Key": "i", "Value": emoji * 129}, {"Key": "x", "Value": emoji * 130}], too_long(emoji * 130, "TagValue")),
+ ([{"Key": "x", "Value": emoji * 129}, {"Key": "i", "Value": emoji * 130}], too_long(emoji * 129, "TagValue")),
+ ([{"Key": "k", "Value": emoji * 129}, {"Key": "m", "Value": emoji * 130}, {"Key": "z", "Value": emoji * 131}],
+ too_long(emoji * 131, "TagValue")),
+ ([{"Key": "a", "Value": "x"}, {"Key": "a", "Value": emoji * 129}], too_long(emoji * 129, "TagValue")),
+ ([{"Key": "a" * 127 + emoji, "Value": "x"}, {"Key": "b", "Value": "c#d"}], chars),
+ ([{"Key": f"g{n:02d}", "Value": "v"} for n in range(9)] + [{"Key": "b" * 127 + emoji, "Value": "x"},
+ {"Key": "a" * 127 + emoji, "Value": "x"}], too_long("a" * 127 + emoji, "TagKey")),
+ ([{"Key": "a", "Value": emoji * 129}, {"Key": "b" * 127 + emoji, "Value": "x"}], too_long(emoji * 129, "TagValue")),
+ ([{"Key": "m" * 127 + emoji, "Value": "x"}, {"Key": "b", "Value": emoji * 129},
+ {"Key": "x" * 127 + emoji, "Value": "x"}], too_long(emoji * 129, "TagValue")),
+ ([{"Key": "b", "Value": emoji * 129}, {"Key": "a", "Value": emoji * 130}], too_long(emoji * 130, "TagValue")),
+ ([{"Key": "a#b", "Value": "x"}, {"Key": "c*d", "Value": "x"}], chars),
+ ([{"Key": "a#b", "Value": "x"}] + [{"Key": f"k{n:02d}", "Value": "v"} for n in range(48)], chars),
+ ([{"Key": "a#b", "Value": "x"}, {"Key": "c"}], f"1 validation error detected: {_NULL_VALUE.format(4)}"),
+ ([{"Key": "é" * 129, "Value": "x"}],
+ f"1 validation error detected: Value '{chr(0xe9) * 129}' at 'tags.3.member.key' failed to satisfy "
+ "constraint: Member must have length less than or equal to 128"),
+ ]
+ for i, (tags, message) in enumerate(refused):
+ name = f"chars-bad-{i}-{uid}"
+ assert _cw_json_put(name, _FILLER_TAGS + tags) == (400, message), i
+ assert not _cw_alarm_exists(cw, name), i
+ for tags in ([{"Key": "a", "Value": emoji * 129}, {"Key": "a", "Value": "x"}],
+ [{"Key": "a", "Value": "a#b"}, {"Key": "a", "Value": "x"}]):
+ names.append(f"chars-dup-{len(names)}-{uid}")
+ assert _cw_json_put(names[-1], _FILLER_TAGS + tags)[0] == 200
+ name = f"chars-dta-{uid}"
+ assert _cw_json_put(name, _FILLER_TAGS + [{"Key": "a#b", "Value": "x"}], DatapointsToAlarm=0) == (
+ 400, f"1 validation error detected: {_DTA_MIN.format(0)}")
+
+ names.append(f"chars-update-{uid}")
+ assert _cw_json_put(names[-1], [{"Key": "team", "Value": "platform"}])[0] == 200
+ assert _cw_json_put(names[-1], [{"Key": "a#b", "Value": "x"}], Threshold=87)[0] == 200
+ alarm = cw.describe_alarms(AlarmNames=[names[-1]])["MetricAlarms"][0]
+ assert alarm["Threshold"] == 87 and _cw_tag_set(cw, alarm["AlarmArn"]) == {"team": "platform"}
+
+ status, body = _cw_raw("query", "PutMetricAlarm", {
+ "AlarmName": f"chars-query-{uid}", **_QUERY_ALARM, "Tags.member.1.Key": "a#b", "Tags.member.1.Value": "x"})
+ assert status == 400 and html.unescape(re.search(r"<Message>(.*?)</Message>", body).group(1)) == chars
+ finally:
+ cw.delete_alarms(AlarmNames=names)
+
+
+def test_cloudwatch_query_put_metric_alarm_escapes_and_blank_values(cw):
+ """An echoed key is XML-escaped in a Query error, and a member's Value sent
+ with no "=" is an empty value.
+ AWS: captured 2026-10-21 (2309-uncertainties Z:query-key-amp-lt-129, Z:query-bare-value)."""
+ import urllib.error
+ import urllib.parse
+ import urllib.request
+
+ from conftest import ENDPOINT
+ auth = ("AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/monitoring/aws4_request, "
+ "SignedHeaders=host, Signature=x")
+
+ def put(name, tail):
+ body = (f"Action=PutMetricAlarm&Version=2010-08-01&{urllib.parse.urlencode(_QUERY_ALARM)}"
+ f"&AlarmName={name}{tail}").encode()
+ req = urllib.request.Request(ENDPOINT, data=body, headers={
+ "Content-Type": "application/x-www-form-urlencoded", "Authorization": auth})
+ try:
+ with urllib.request.urlopen(req) as resp:
+ return resp.status, None, None
+ except urllib.error.HTTPError as e:
+ text = e.read().decode()
+ return (e.code, re.search(r"<Code>(.*?)</Code>", text).group(1),
+ re.search(r"<Message>(.*?)</Message>", text, re.S).group(1))
+
+ two = "&Tags.member.1.Key=f1&Tags.member.1.Value=v&Tags.member.2.Key=f2&Tags.member.2.Value=v"
+ uid = _uuid_mod.uuid4().hex[:8]
+ name = f"query-escape-{uid}"
+ status, code, raw_message = put(name, two + "&Tags.member.3.Key=" + urllib.parse.quote("&<" + "k" * 127)
+ + "&Tags.member.3.Value=x")
+ assert (status, code) == (400, "ValidationError")
+ assert raw_message.startswith("1 validation error detected: Value '&amp;&lt;kkk")
+ assert html.unescape(raw_message) == (f"1 validation error detected: Value '&<{'k' * 127}' at 'tags.3.member.key' "
+ "failed to satisfy constraint: Member must have length less than or equal to 128")
+ assert not _cw_alarm_exists(cw, name)
+
+ bare = f"query-bare-{uid}"
+ try:
+ assert put(bare, two + "&Tags.member.3.Key=a&Tags.member.3.Value")[0] == 200
+ arn = cw.describe_alarms(AlarmNames=[bare])["MetricAlarms"][0]["AlarmArn"]
+ assert _cw_tag_set(cw, arn) == {"f1": "v", "f2": "v", "a": ""}
+ finally:
+ cw.delete_alarms(AlarmNames=[bare])
+
+
+def _cw_composite_base(cw, uid):
+ name = f"composite-base-{uid}"
+ cw.put_metric_alarm(AlarmName=name, **_ALARM_BASE)
+ return name, f'ALARM("{name}")'
+
+
+def test_cloudwatch_put_composite_alarm_applies_tags_on_create_only(cw):
+ """PutCompositeAlarm stores Tags when it creates the alarm and ignores them
+ on an update, whether the alarm had tags or not; a repeated key keeps its
+ last value; an empty list or null stores none.
+ AWS: captured 2026-10-21 (2309-uncertainties I11:put-composite-alarm-tags-on-create,
+ I11:put-composite-alarm-update-different-tags) and 2026-10-22 (K:json-create-with-tags,
+ K:json-update-other-tags, K:json-create-untagged, K:json-untagged-then-update-with-tags,
+ K:json-dup-keys, K:json-tags-empty, K:json-tags-null, K:query-create-with-tags)."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ base, rule = _cw_composite_base(cw, uid)
+ names = [f"composite-{n}-{uid}" for n in ("tagged", "untagged", "dup", "empty", "null", "query")]
+
+ def arn(name):
+ return f"arn:aws:cloudwatch:us-east-1:000000000000:alarm:{name}"
+
+ try:
+ cw.put_composite_alarm(AlarmName=names[0], AlarmRule=rule, Tags=[{"Key": "team", "Value": "platform"}])
+ assert _cw_tag_set(cw, arn(names[0])) == {"team": "platform"}
+ cw.put_composite_alarm(AlarmName=names[0], AlarmRule=rule, Tags=[{"Key": "other", "Value": "x"}])
+ assert _cw_tag_set(cw, arn(names[0])) == {"team": "platform"}
+
+ cw.put_composite_alarm(AlarmName=names[1], AlarmRule=rule)
+ cw.put_composite_alarm(AlarmName=names[1], AlarmRule=rule, Tags=[{"Key": "team", "Value": "platform"}])
+ assert _cw_tag_set(cw, arn(names[1])) == {}
+
+ cw.put_composite_alarm(AlarmName=names[2], AlarmRule=rule,
+ Tags=[{"Key": "d", "Value": "1"}, {"Key": "d", "Value": "2"}])
+ assert _cw_tag_set(cw, arn(names[2])) == {"d": "2"}
+ cw.put_composite_alarm(AlarmName=names[3], AlarmRule=rule, Tags=[])
+ assert _cw_tag_set(cw, arn(names[3])) == {}
+ assert _cw_raw("json", "PutCompositeAlarm", {"AlarmName": names[4], "AlarmRule": rule, "Tags": None})[0] == 200
+ assert _cw_tag_set(cw, arn(names[4])) == {}
+ assert _cw_raw("query", "PutCompositeAlarm", {"AlarmName": names[5], "AlarmRule": rule,
+ "Tags.member.1.Key": "team", "Tags.member.1.Value": ""})[0] == 200
+ assert _cw_tag_set(cw, arn(names[5])) == {"team": ""}
+ finally:
+ for name in names: # DeleteAlarms takes one composite alarm per call
+ cw.delete_alarms(AlarmNames=[name])
+ cw.delete_alarms(AlarmNames=[base])
+
+
+def test_cloudwatch_put_composite_alarm_refuses_invalid_tags(cw):
+ """PutCompositeAlarm checks Tags like PutMetricAlarm (types, member
+ constraints, the tag-set check, then at most 50 tags), before its
+ AlarmRule; an aws: key is a ValidationError after the tag-set check, not
+ PutMetricAlarm's AccessDenied. An update checks the member constraints
+ only. Nothing is created or changed on a refusal.
+ AWS: captured 2026-10-22 (2309-uncertainties K:json-missing-value, K:json-missing-key,
+ K:json-key-129, K:json-key-hash, K:json-value-129-emoji, K:json-51-tags, K:json-50-tags,
+ K:json-aws-prefix, K:json-tags-string, K:json-key-number, K:json-bad-rule-and-missing-value,
+ K:json-missing-child-and-missing-value, K:json-missing-child-and-aws-prefix,
+ K:json-missing-child-and-51-tags, K:json-missing-child-and-key-hash,
+ K:json-bad-rule-and-key-number, K:query-missing-value, K:cbor-missing-key,
+ K:json-update-missing-key, K:json-update-aws-prefix, K:json-update-51-tags,
+ K2:json-AWS-upper, K2:json-aws-vendor-key, K2:json-aws-colon-only,
+ K2:json-aws-and-missing-value, K2:json-aws-and-key-hash, K2:json-key-hash-then-aws,
+ K2:json-aws-and-51-tags, K2:json-aws-and-too-long-value, K2:json-aws-and-key-number,
+ Z9:composite-AWS-x-then-aws-y, Z9:composite-aws-zz-then-aws-a-b, Z9:composite-Aws-q-then-AWS-b)."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ base, rule = _cw_composite_base(cw, uid)
+ emoji = "\U0001F600"
+ many = [{"Key": f"k{n:02d}", "Value": "v"} for n in range(49)]
+ chars = ("Tags can only contain letters, numbers, spaces, and the following special characters: "
+ "_ . : / = + - @")
+ missing = f'ALARM("composite-missing-{uid}")'
+
+ def put(name, tags, alarm_rule=rule):
+ status, body = _cw_raw("json", "PutCompositeAlarm", {"AlarmName": name, "AlarmRule": alarm_rule, "Tags": tags})
+ if status < 300:
+ return status, None
+ payload = json.loads(body)
+ return status, payload.get("message", payload.get("Message")) or ""
+
+ cases = [
+ (_FILLER_TAGS + [{"Key": "a"}], rule, (400, f"1 validation error detected: {_NULL_VALUE.format(3)}")),
+ (_FILLER_TAGS + [{"Value": "x"}], rule, (400, f"1 validation error detected: {_NULL_KEY.format(3)}")),
+ (_FILLER_TAGS + [{"Key": "k" * 129, "Value": "x"}], rule,
+ (400, f"1 validation error detected: Value '{'k' * 129}' at 'tags.3.member.key' failed to satisfy constraint: "
+ "Member must have length less than or equal to 128")),
+ (_FILLER_TAGS + [{"Key": "a#b", "Value": "x"}], rule, (400, chars)),
+ (_FILLER_TAGS + [{"Key": "a", "Value": emoji * 129}], rule,
+ (400, f"'{emoji * 129}' is not a valid value for com.amazon.aws.platform.billing.tagset.type.TagValue - it is too long")),
+ (_FILLER_TAGS + many, rule, (400, _TAG_LIMIT)),
+ (_FILLER_TAGS + [{"Key": "aws:x", "Value": "x"}], rule, (400, "Invalid System Tag: aws:x is missing Vendor Id.")),
+ (_FILLER_TAGS + [{"Key": "aws:", "Value": "x"}], rule, (400, "Invalid System Tag: aws: is missing Vendor Id.")),
+ (_FILLER_TAGS + [{"Key": "aws:vendor:x", "Value": "x"}], rule,
+ (400, "Invalid System Tag: aws:vendor:x is not whitelisted for vendor:cloudwatch")),
+ (_FILLER_TAGS + [{"Key": "AWS:x", "Value": "x"}], rule,
+ (400, 'Invalid System Tag: AWS:x must be prefixed with "aws:" in lowercase.')),
+ ([{"Key": "AWS:x", "Value": "x"}, {"Key": "aws:y", "Value": "x"}], rule,
+ (400, "Invalid System Tag: aws:y is missing Vendor Id.")),
+ ([{"Key": "aws:zz", "Value": "x"}, {"Key": "aws:a:b", "Value": "x"}], rule,
+ (400, "Invalid System Tag: aws:a:b is not whitelisted for vendor:cloudwatch")),
+ ([{"Key": "Aws:q", "Value": "x"}, {"Key": "AWS:b", "Value": "x"}], rule,
+ (400, 'Invalid System Tag: AWS:b must be prefixed with "aws:" in lowercase.')),
+ (_FILLER_TAGS + [{"Key": "aws:x", "Value": "x"}, {"Key": "a"}], rule,
+ (400, f"1 validation error detected: {_NULL_VALUE.format(4)}")),
+ (_FILLER_TAGS + [{"Key": "aws:x", "Value": "x"}, {"Key": "a#b", "Value": "x"}], rule, (400, chars)),
+ (_FILLER_TAGS + [{"Key": "a#b", "Value": "x"}, {"Key": "aws:x", "Value": "x"}], rule, (400, chars)),
+ (_FILLER_TAGS + many[:48] + [{"Key": "aws:x", "Value": "x"}], rule,
+ (400, "Invalid System Tag: aws:x is missing Vendor Id.")),
+ (_FILLER_TAGS + [{"Key": "aws:x", "Value": "x"}, {"Key": "b", "Value": emoji * 129}], rule,
+ (400, f"'{emoji * 129}' is not a valid value for com.amazon.aws.platform.billing.tagset.type.TagValue - it is too long")),
+ ("x", rule, (400, "Unexpected field type")),
+ (_FILLER_TAGS + [{"Key": 5, "Value": "x"}], rule, (400, "NUMBER_VALUE cannot be converted to String")),
+ (_FILLER_TAGS + [{"Key": "aws:x", "Value": "x"}, {"Key": 5, "Value": "x"}], rule,
+ (400, "NUMBER_VALUE cannot be converted to String")),
+ (_FILLER_TAGS + [{"Key": "a"}], "NOT A RULE (((", (400, f"1 validation error detected: {_NULL_VALUE.format(3)}")),
+ (_FILLER_TAGS + [{"Key": "a"}], missing, (400, f"1 validation error detected: {_NULL_VALUE.format(3)}")),
+ (_FILLER_TAGS + [{"Key": "aws:x", "Value": "x"}], missing, (400, "Invalid System Tag: aws:x is missing Vendor Id.")),
+ (_FILLER_TAGS + many, missing, (400, _TAG_LIMIT)),
+ (_FILLER_TAGS + [{"Key": "a#b", "Value": "x"}], missing, (400, chars)),
+ (_FILLER_TAGS + [{"Key": 5, "Value": "x"}], "NOT A RULE (((", (400, "NUMBER_VALUE cannot be converted to String")),
+ ]
+ for i, (tags, alarm_rule, expected) in enumerate(cases):
+ name = f"composite-refused-{i}-{uid}"
+ assert put(name, tags, alarm_rule) == expected, i
+ assert not cw.describe_alarms(AlarmNames=[name], AlarmTypes=["CompositeAlarm"])["CompositeAlarms"], i
+
+ status, body = _cw_raw("query", "PutCompositeAlarm", {"AlarmName": f"composite-q-{uid}", "AlarmRule": rule,
+ "Tags.member.1.Key": "f1", "Tags.member.1.Value": "v",
+ "Tags.member.2.Key": "f2", "Tags.member.2.Value": "v",
+ "Tags.member.3.Key": "a"})
+ assert status == 400 and html.unescape(re.search(r"<Message>(.*?)</Message>", body).group(1)) == (
+ f"1 validation error detected: {_NULL_VALUE.format(3)}")
+ with pytest.raises(ClientError) as exc:
+ _cw_unvalidated().put_composite_alarm(AlarmName=f"composite-c-{uid}", AlarmRule=rule,
+ Tags=_FILLER_TAGS + [{"Value": "x"}])
+ assert (exc.value.response["Error"]["Code"], exc.value.response["Error"]["Message"]) == (
+ "ValidationError", f"1 validation error detected: {_NULL_KEY.format(3)}")
+
+ existing = f"composite-update-{uid}"
+ try:
+ assert put(existing, [{"Key": "team", "Value": "platform"}])[0] == 200
+ assert put(existing, _FILLER_TAGS + [{"Value": "x"}], f'OK("{base}")') == (
+ 400, f"1 validation error detected: {_NULL_KEY.format(3)}")
+ alarm = cw.describe_alarms(AlarmNames=[existing], AlarmTypes=["CompositeAlarm"])["CompositeAlarms"][0]
+ assert alarm["AlarmRule"] == rule
+ for tags, new_rule in ((_FILLER_TAGS + [{"Key": "aws:x", "Value": "x"}], f'OK("{base}")'),
+ (_FILLER_TAGS + many, f'INSUFFICIENT_DATA("{base}")')):
+ assert put(existing, tags, new_rule)[0] == 200
+ alarm = cw.describe_alarms(AlarmNames=[existing], AlarmTypes=["CompositeAlarm"])["CompositeAlarms"][0]
+ assert alarm["AlarmRule"] == new_rule
+ assert _cw_tag_set(cw, alarm["AlarmArn"]) == {"team": "platform"}
+ finally:
+ cw.delete_alarms(AlarmNames=[existing])
+ cw.delete_alarms(AlarmNames=[base])