Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(stepfunctions): keep and validate encryptionConfiguration on state machines (#2335)
Kacper Harabasz5dcc0dbf8791
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9beb9a79..37876ca2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **WAF v2 — `CreateIPSet` and `CreateRuleGroup` refuse a duplicate name** — a second IP set or rule group with the name and scope of an existing one is now refused with `WAFDuplicateItemException`, as AWS does and as `CreateWebACL` and `CreateRegexPatternSet` already did. Both stored the duplicate silently, so a client that retries a create after losing the response ended up with two. Contributed by @OS-kiranmalsetty.- **Route 53 — private hosted zones keep their VPC** — `CreateHostedZone` with a `VPC` made a public zone and dropped the VPC, so Terraform's `aws_route53_zone` with a `vpc` block planned to add it again on every run; the zone is now private, the response carries the `VPC` instead of a delegation set, also on a `CallerReference` replay, and `GetHostedZone` returns its `VPCs`. Contributed by @kharabasz.- **ELBv2 — listener `SslPolicy` and certificate** — `CreateListener` and `ModifyListener` dropped `SslPolicy` and `Certificates`, so `DescribeListeners` returned neither and Terraform re-planned `ssl_policy` on every HTTPS listener; HTTPS and TLS listeners now keep and return both, the policy defaults to `ELBSecurityPolicy-2016-08`, a listener moved to HTTP or TCP drops them, and more than one default certificate answers `ValidationError`. Contributed by @kharabasz.+- **Step Functions — `encryptionConfiguration` on state machines** — `CreateStateMachine` and `UpdateStateMachine` dropped `encryptionConfiguration`, so Terraform's `aws_sfn_state_machine` showed a diff on `encryption_configuration` after every apply. It is now stored and returned by `DescribeStateMachine`, published versions and `DescribeStateMachineForExecution`: `{"type": "AWS_OWNED_KEY"}` when none was set, and a customer managed key with `kmsDataKeyReusePeriodSeconds` 300 when no period was sent, on create and update. Requests are refused as AWS refuses them: `SerializationException` for wrong JSON types, `ValidationException` for the member constraints (several in one message), `InvalidEncryptionConfiguration` for a customer managed key without `kmsKeyId` or an `AWS_OWNED_KEY` with a key or period, and `MissingRequiredParameter` for an update without `definition`, in AWS's check order. A re-create with a different configuration answers `StateMachineAlreadyExists`. `AWS::StepFunctions::StateMachine` applies `EncryptionConfiguration` on create and update, keeps it when an update drops the block, and fails with AWS's handler messages. The key is not looked up in KMS. Contributed by @kharabasz.- **Cognito — `ChangePassword` checks `PreviousPassword`** — a wrong or missing `PreviousPassword` was ignored and the password was replaced; for a user with a password, a wrong one now fails with `NotAuthorizedException` and a missing one with `InvalidParameterException`, as on AWS, and the password is unchanged. Contributed by @jun-ut.- **SQS — `MD5OfMessageAttributes` of filtered attributes** — `ReceiveMessage` with `MessageAttributeNames` selecting some of a message's attributes returned only those attributes but the digest of all of them, so SDKs that validate `MD5OfMessageAttributes` rejected the response; the digest is now computed over the attributes returned. Contributed by @Xevos117.diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.pyindex d87cfa89..7d0c477b 100644--- a/ministack/services/cloudformation/changesets.py+++ b/ministack/services/cloudformation/changesets.py@@ -43,6 +43,7 @@ from .helpers import (_page,_request_problems,_resolve_template,+ _sdk_error,_xml,enum_problems,stack_name_problems,@@ -100,13 +101,6 @@ def _extract_resources_to_import(params):_IMPORT_NOT_FOUND = "Resource of type '{type}' with identifier '{value}' was not found."-def _sdk_error(message, service, status, request_id=None):- """A service error as the import's resource handler words it in the- StatusReason: the service's own message, then its SDK's suffix."""- return (f"{message} (Service: {service}, Status Code: {status}, "- f"Request ID: {request_id or new_uuid()}) (SDK Attempt Count: 1)")--def _queue_import_problem(url):if not url:return "QueueUrl is not found"diff --git a/ministack/services/cloudformation/helpers.py b/ministack/services/cloudformation/helpers.pyindex 2bcb5597..ad84b67f 100644--- a/ministack/services/cloudformation/helpers.py+++ b/ministack/services/cloudformation/helpers.py@@ -334,3 +334,10 @@ def _page(items, params, action, page_size=PAGE_SIZE):if start + page_size < len(items):next_token_xml = f"<NextToken>{action}:{start + page_size}</NextToken>"return page, next_token_xml, None+++def _sdk_error(message, service, status, request_id=None):+ """A service error as a resource handler words it in the+ StatusReason: the service's own message, then its SDK's suffix."""+ return (f"{message} (Service: {service}, Status Code: {status}, "+ f"Request ID: {request_id or new_uuid()}) (SDK Attempt Count: 1)")diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 414ce5bb..df80f60e 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -65,6 +65,8 @@ import ministack.services.stepfunctions as _sfnimport ministack.services.waf as _waffrom ministack.core.responses import get_account_id, get_region, new_uuid, now_iso+from .helpers import _sdk_error+logger = logging.getLogger("cloudformation")# Module-level REGION kept for legacy imports; new code must use get_region()@@ -9182,6 +9184,90 @@ def _sfn_tags(props):return [{"key": t.get("Key", ""), "value": t.get("Value", "")} for t in props.get("Tags") or []]+def _sfn_handler_error(message):+ """The resource status reason AWS's AWS::StepFunctions::StateMachine+ handler reports for a request it refuses."""+ return ValueError(f'Resource handler returned message: "{message}" '+ f"(RequestToken: {new_uuid()}, HandlerErrorCode: InvalidRequest)")+++def _sfn_service_error(resp):+ """The handler error for a refused Step Functions API response, with the+ service's message and the SDK details the handler appends to it."""+ body = json.loads(resp[2])+ return _sfn_handler_error(_sdk_error(body.get("message", body.get("Message", "")), "Sfn", resp[0]))+++_SFN_TYPE_PATH = "#/EncryptionConfiguration/Type"+_SFN_KEY_PATH = "#/EncryptionConfiguration/KmsKeyId"+_SFN_PERIOD_PATH = "#/EncryptionConfiguration/KmsDataKeyReusePeriodSeconds"+_SFN_NOT_INTEGER = ("expected type: Integer, found: String. This may occur when a numeric value exceeds "+ "32-bit integer max (2147483647). Consider using 'number' type or ensure value fits in "+ "integer range.")+++def _sfn_schema_problem(enc):+ """The text after "Model validation failed " for a template block that+ breaks the resource schema, or None. Template scalars reach the handler+ as strings, so a number or boolean block is "found: String". Several+ member violations are listed together in the order Type, KmsKeyId,+ KmsDataKeyReusePeriodSeconds."""+ if isinstance(enc, list):+ return "(#/EncryptionConfiguration: expected type: JSONObject, found: JSONArray)"+ if not isinstance(enc, dict):+ return "(#/EncryptionConfiguration: expected type: JSONObject, found: String)"+ if "Type" not in enc:+ return "(#/EncryptionConfiguration: required key [Type] not found)"+ problems = []+ if enc["Type"] not in _sfn._ENCRYPTION_TYPES:+ problems.append((_SFN_TYPE_PATH, "#: only 1 subschema matches out of 2"))+ key_id = enc.get("KmsKeyId")+ if isinstance(key_id, str) and not key_id:+ problems.append((_SFN_KEY_PATH, "expected minLength: 1, actual: 0"))+ elif isinstance(key_id, str) and len(key_id) > 2048:+ problems.append((_SFN_KEY_PATH, f"expected maxLength: 2048, actual: {len(key_id)}"))+ period = enc.get("KmsDataKeyReusePeriodSeconds")+ if period is not None:+ try:+ period = int(period)+ except (TypeError, ValueError):+ problems.append((_SFN_PERIOD_PATH, _SFN_NOT_INTEGER))+ else:+ if period < 60:+ problems.append((_SFN_PERIOD_PATH, "failed validation constraint for keyword [minimum]"))+ elif period > 900:+ problems.append((_SFN_PERIOD_PATH, "failed validation constraint for keyword [maximum]"))+ if not problems:+ return None+ if len(problems) > 1:+ lines = "\n".join(f"{path}: {text} ({path})" for path, text in problems)+ return f"(#/EncryptionConfiguration: {len(problems)} schema violations found)\n{lines}"+ path, text = problems[0]+ if path == _SFN_TYPE_PATH:+ return (f"({path}: {text})\n{path}: failed validation constraint for keyword [enum] ({path})")+ return f"({path}: {text})"+++def _sfn_encryption(cfn_encryption):+ """A template's EncryptionConfiguration ({Type, KmsKeyId,+ KmsDataKeyReusePeriodSeconds}) as the configuration the machine stores,+ refused the way the AWS handler refuses it: the resource schema first,+ then the service's own checks."""+ problem = _sfn_schema_problem(cfn_encryption)+ if problem:+ raise _sfn_handler_error(f"Model validation failed {problem}")+ encryption = {"type": cfn_encryption["Type"]}+ if cfn_encryption.get("KmsKeyId") is not None:+ encryption["kmsKeyId"] = cfn_encryption["KmsKeyId"]+ if cfn_encryption.get("KmsDataKeyReusePeriodSeconds") is not None:+ # The handler takes a numeric string such as "600" as the integer.+ encryption["kmsDataKeyReusePeriodSeconds"] = int(cfn_encryption["KmsDataKeyReusePeriodSeconds"])+ invalid = _sfn._encryption_configuration_error(encryption)+ if invalid:+ raise _sfn_service_error(invalid)+ return _sfn._stored_encryption(encryption)++def _sfn_attrs(arn, name):"""Ref is the ARN; Fn::GetAtt serves Arn, Name and StateMachineRevisionId,the revision the record carries (rotated by every create and update)."""@@ -9197,14 +9283,15 @@ def _sfn_state_machine_create(logical_id, props, stack_name):role_arn = props.get("RoleArn", f"arn:aws:iam::{get_account_id()}:role/StepFunctionsRole")definition = _sfn_definition(props)sm_type = props.get("StateMachineType", "STANDARD")+ encryption = (_sfn_encryption(props["EncryptionConfiguration"])+ if "EncryptionConfiguration" in props else _sfn._default_encryption())arn = f"arn:aws:states:{get_region()}:{get_account_id()}:stateMachine:{name}"ts = now_iso()# The record mirrors what CreateStateMachine writes, revision id and# version counter included, so versions published later behave the same- # for a template-created machine. TracingConfiguration and- # EncryptionConfiguration have no field in the store and are accepted- # without effect.+ # for a template-created machine. TracingConfiguration has no field in+ # the store and is accepted without effect._sfn._state_machines[arn] = {"stateMachineArn": arn,"name": name,@@ -9214,6 +9301,7 @@ def _sfn_state_machine_create(logical_id, props, stack_name):"creationDate": ts,"status": "ACTIVE","loggingConfiguration": props.get("LoggingConfiguration", {"level": "OFF", "includeExecutionData": False}),+ "encryptionConfiguration": encryption,"revisionId": new_uuid(),"lastVersionNumber": 0,}@@ -9230,10 +9318,11 @@ def _sfn_state_machine_update(physical_id, old_props, new_props, stack_name,StateMachineName and StateMachineType require replacement(https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-stepfunctions-statemachine.html):``_update_resource`` performs it before this runs. Definition,- DefinitionSubstitutions, RoleArn, LoggingConfiguration and Tags update- without interruption;- TracingConfiguration and EncryptionConfiguration are accepted without- effect, the store has no field for them.+ DefinitionSubstitutions, RoleArn, LoggingConfiguration,+ EncryptionConfiguration and Tags update without interruption. A template+ that drops EncryptionConfiguration leaves the machine's configuration as+ it is, as AWS does. TracingConfiguration is accepted without effect, the+ store has no field for it."""name = new_props.get("StateMachineName") or _physical_name(stack_name, logical_id or physical_id, max_len=80@@ -9262,6 +9351,10 @@ def _sfn_state_machine_update(physical_id, old_props, new_props, stack_name,"LoggingConfiguration": {"level": "OFF", "includeExecutionData": False}})if logging:data["loggingConfiguration"] = logging["LoggingConfiguration"]+ # EncryptionConfiguration is sent only when the new template declares it:+ # on AWS, dropping the block keeps the configuration the machine has.+ if "EncryptionConfiguration" in new_props:+ data["encryptionConfiguration"] = _sfn_encryption(new_props["EncryptionConfiguration"])resp = _sfn._update_state_machine(data)if resp[0] >= 400:raise ValueError(f"AWS::StepFunctions::StateMachine update failed: {resp[2]!r}")diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.pyindex edfb1b15..b116fae4 100644--- a/ministack/services/stepfunctions.py+++ b/ministack/services/stepfunctions.py@@ -354,18 +354,181 @@ def _validate_definition_jsonata(definition_str) -> str | None:return walk(definition, "")+_ENCRYPTION_TYPES = ("AWS_OWNED_KEY", "CUSTOMER_MANAGED_KMS_KEY")+# What AWS stores when a CUSTOMER_MANAGED_KMS_KEY configuration has no reuse period.+_DEFAULT_KMS_DATA_KEY_REUSE_PERIOD = 300+++def _default_encryption():+ """The encryptionConfiguration a machine reports when no customer+ managed key was set. A fresh dict each call, so no two records share one."""+ return {"type": "AWS_OWNED_KEY"}+++# How AWS's JSON deserializer names a value of the wrong JSON type.+def _json_token(value):+ if isinstance(value, bool):+ return "TRUE_VALUE" if value else "FALSE_VALUE"+ if isinstance(value, (int, float)):+ return "NUMBER_VALUE"+ return "STRING_VALUE"+++def _wrong_json_type(value, expected):+ """AWS's SerializationException message for a member of the wrong JSON+ type, or None. expected is "Integer", "String" or "structure"."""+ if isinstance(value, list):+ return "Start of list found where not expected"+ if isinstance(value, dict):+ return None if expected == "structure" else "Start of structure or map found where not expected."+ if expected == "structure":+ return "Expected null"+ if expected == "Integer":+ if isinstance(value, (bool, str)):+ return f"{_json_token(value)} can not be converted to an Integer"+ return None+ if isinstance(value, str):+ return None+ return f"{_json_token(value)} can not be converted to a String"+++def _encryption_serialization_error(cfg):+ """The SerializationException AWS answers when encryptionConfiguration or+ one of its members has the wrong JSON type. AWS reports one member,+ checking them in the order reuse period, kmsKeyId, type whatever order+ the request lists them in. A JSON null is not an error: AWS treats it as+ an absent field. This exception's message member is "Message" on the+ wire."""+ if cfg is None:+ return None+ message = _wrong_json_type(cfg, "structure")+ if message is None:+ for member, expected in (("kmsDataKeyReusePeriodSeconds", "Integer"),+ ("kmsKeyId", "String"), ("type", "String")):+ if cfg.get(member) is not None:+ message = _wrong_json_type(cfg[member], expected)+ if message:+ break+ if message is None:+ return None+ return error_response_json("SerializationException", message, 400, message_key="Message")+++def _with_integer_period(cfg):+ """The configuration with a JSON number period read as an integer: AWS+ accepts 300.5 and stores 300."""+ period = cfg.get("kmsDataKeyReusePeriodSeconds")+ if isinstance(period, float):+ return {**cfg, "kmsDataKeyReusePeriodSeconds": int(period)}+ return cfg+++def _encryption_validation_error(cfg):+ """The ValidationException for an encryptionConfiguration that breaks the+ member constraints, or None. AWS reports every broken constraint in one+ message, in the order reuse period, kmsKeyId, type."""+ problems = []+ period = cfg.get("kmsDataKeyReusePeriodSeconds")+ if isinstance(period, int) and not isinstance(period, bool):+ if period < 60:+ problems.append(+ f"Value '{period}' at 'encryptionConfiguration.kmsDataKeyReusePeriodSeconds' "+ "failed to satisfy constraint: Member must have value greater than or equal to 60")+ elif period > 900:+ problems.append(+ f"Value '{period}' at 'encryptionConfiguration.kmsDataKeyReusePeriodSeconds' "+ "failed to satisfy constraint: Member must have value less than or equal to 900")+ key_id = cfg.get("kmsKeyId")+ if isinstance(key_id, str):+ if not key_id:+ problems.append(+ "Value '' at 'encryptionConfiguration.kmsKeyId' failed to satisfy "+ "constraint: Member must have length greater than or equal to 1")+ elif len(key_id) > 2048:+ problems.append(+ f"Value '{key_id}' at 'encryptionConfiguration.kmsKeyId' failed to satisfy "+ "constraint: Member must have length less than or equal to 2048")+ enc_type = cfg.get("type")+ if enc_type is None:+ problems.append(+ "Value null at 'encryptionConfiguration.type' failed to satisfy "+ "constraint: Member must not be null")+ elif enc_type not in _ENCRYPTION_TYPES:+ problems.append(+ f"Value '{enc_type}' at 'encryptionConfiguration.type' failed to satisfy "+ f"constraint: Member must satisfy enum value set: [{', '.join(_ENCRYPTION_TYPES)}]")+ if not problems:+ return None+ count = (f"{len(problems)} validation error detected" if len(problems) == 1+ else f"{len(problems)} validation errors detected")+ return error_response_json("ValidationException", f"{count}: " + "; ".join(problems), 400)+++def _encryption_configuration_error(cfg):+ """The InvalidEncryptionConfiguration for a well-formed configuration+ whose members do not fit its type, or None. The key is not looked up in+ KMS."""+ if cfg["type"] == "CUSTOMER_MANAGED_KMS_KEY":+ if cfg.get("kmsKeyId") is None:+ return error_response_json(+ "InvalidEncryptionConfiguration",+ "Invalid Encryption Configuration: Must set a valid kmsKeyId.", 400)+ return None+ if cfg.get("kmsKeyId") is not None:+ return error_response_json(+ "InvalidEncryptionConfiguration",+ "Invalid Encryption Configuration: Custom kmsKeyId is not allowed when "+ "selecting AWS_OWNED_KEY.", 400)+ if cfg.get("kmsDataKeyReusePeriodSeconds") is not None:+ return error_response_json(+ "InvalidEncryptionConfiguration",+ "Invalid Encryption Configuration: Custom kmsDataKeyReusePeriodSeconds is not "+ "allowed when selecting AWS_OWNED_KEY.", 400)+ return None+++def _stored_encryption(cfg):+ """The configuration a machine stores and describes for an accepted+ request value: AWS_OWNED_KEY when absent, and a customer managed key with+ the 300 second default when no reuse period was sent."""+ if cfg is None or cfg["type"] == "AWS_OWNED_KEY":+ return _default_encryption()+ period = cfg.get("kmsDataKeyReusePeriodSeconds")+ return {+ "type": "CUSTOMER_MANAGED_KMS_KEY",+ "kmsKeyId": cfg["kmsKeyId"],+ "kmsDataKeyReusePeriodSeconds": (+ _DEFAULT_KMS_DATA_KEY_REUSE_PERIOD if period is None else period),+ }++def _create_state_machine(data):name = data.get("name")if not name:return error_response_json("ValidationException", "name is required", 400)+ # AWS checks the encryptionConfiguration's JSON types and member+ # constraints before the definition, and whether its members fit its+ # type after the definition and before the existing-machine check.+ encryption = data.get("encryptionConfiguration")+ invalid = _encryption_serialization_error(encryption)+ if invalid is None and encryption is not None:+ encryption = _with_integer_period(encryption)+ invalid = _encryption_validation_error(encryption)+ if invalid:+ return invalidinvalid = _validate_definition_jsonata(data.get("definition"))if invalid:return error_response_json("InvalidDefinition", invalid, 400)+ if encryption is not None:+ invalid = _encryption_configuration_error(encryption)+ if invalid:+ return invalid+ encryption = _stored_encryption(encryption)arn = f"arn:aws:states:{get_region()}:{get_account_id()}:stateMachine:{name}"if arn in _state_machines:# Creating the same machine twice is idempotent on AWS and makes SDK retry safe- # It checks the sfn itself: definition, type, logging and whether the call publishes+ # It checks the sfn itself: definition, type, logging, encryption and whether the call publishesexisting = _state_machines[arn]publishes = bool(data.get("publish"))if (data.get("definition", "{}") == existing["definition"]@@ -373,6 +536,7 @@ def _create_state_machine(data):and data.get("loggingConfiguration",{"level": "OFF", "includeExecutionData": False})== existing["loggingConfiguration"]+ and encryption == existing.get("encryptionConfiguration", _default_encryption())and publishes == bool(existing.get("createVersionArn"))# AWS's idempotency check also covers versionDescription: a# publishing re-create carrying a different description is a@@ -409,6 +573,8 @@ def _create_state_machine(data):"loggingConfiguration": data.get("loggingConfiguration",{"level": "OFF", "includeExecutionData": False}),+ # Machines without a customer managed key report AWS_OWNED_KEY.+ "encryptionConfiguration": encryption,# AWS rotates revisionId on every Create/Update. Callers use it# as an optimistic-concurrency precondition when publishing a# version (see _publish_state_machine_version).@@ -444,6 +610,8 @@ def _create_state_machine(data):"type": _state_machines[arn]["type"],"loggingConfiguration": copy.deepcopy(_state_machines[arn]["loggingConfiguration"]),+ "encryptionConfiguration": copy.deepcopy(+ _state_machines[arn]["encryptionConfiguration"]),}response["stateMachineVersionArn"] = version_arnreturn json_response(response)@@ -473,8 +641,10 @@ def _describe_state_machine(data):arn = data.get("stateMachineArn")sm = _state_machines.get(arn)if sm:- return json_response({k: v for k, v in sm.items()- if k not in _SM_INTERNAL_KEYS})+ body = {k: v for k, v in sm.items() if k not in _SM_INTERNAL_KEYS}+ # Machines persisted before encryptionConfiguration was stored.+ body.setdefault("encryptionConfiguration", _default_encryption())+ return json_response(body)# AWS's DescribeStateMachine also accepts a qualified version ARN# (arn:...:stateMachine:<name>:<N>) and returns the snapshot# captured at publish time, with stateMachineArn echoing the@@ -493,6 +663,8 @@ def _describe_state_machine(data):"description": version.get("description", ""),"loggingConfiguration": version.get("loggingConfiguration")or base_sm.get("loggingConfiguration", {"level": "OFF"}),+ "encryptionConfiguration": version.get("encryptionConfiguration")+ or _default_encryption(),"revisionId": version.get("stateMachineRevisionId", ""),})# DescribeStateMachine on an alias ARN: AWS accepts it and returns@@ -521,12 +693,31 @@ def _describe_state_machine(data):def _update_state_machine(data):+ # AWS checks the encryptionConfiguration's JSON types and member+ # constraints before it looks the machine up, and whether its members fit+ # its type before the definition. Everything is checked before anything+ # is written, so a refused call changes nothing.+ encryption = data.get("encryptionConfiguration")+ invalid = _encryption_serialization_error(encryption)+ if invalid is None and encryption is not None:+ encryption = _with_integer_period(encryption)+ invalid = _encryption_validation_error(encryption)+ if invalid:+ return invalidarn = data.get("stateMachineArn")sm = _state_machines.get(arn)if not sm:return error_response_json("StateMachineDoesNotExist",f"State machine {arn} not found", 400)+ if encryption is not None:+ invalid = _encryption_configuration_error(encryption)+ if invalid:+ return invalid+ if "definition" not in data:+ return error_response_json(+ "MissingRequiredParameter",+ "The definition must be specified when updating the EncryptionConfiguration", 400)if "definition" in data:invalid = _validate_definition_jsonata(data["definition"])if invalid:@@ -536,6 +727,8 @@ def _update_state_machine(data):sm["roleArn"] = data["roleArn"]if "loggingConfiguration" in data:sm["loggingConfiguration"] = data["loggingConfiguration"]+ if encryption is not None:+ sm["encryptionConfiguration"] = _stored_encryption(encryption)# Rotate revisionId so subsequent PublishStateMachineVersion calls# with a stale caller-supplied revisionId raise ConflictException# (matches AWS optimistic-concurrency semantics).@@ -559,6 +752,8 @@ def _update_state_machine(data):"roleArn": sm["roleArn"],"type": sm["type"],"loggingConfiguration": copy.deepcopy(sm["loggingConfiguration"]),+ "encryptionConfiguration": copy.deepcopy(+ sm.get("encryptionConfiguration") or _default_encryption()),}response["stateMachineVersionArn"] = version_arnresponse["revisionId"] = sm["revisionId"]@@ -590,6 +785,19 @@ def _list_state_machines(data):# Execution lifecycle# ---------------------------------------------------------------------------+def _execution_version_arn(arn):+ """The version ARN an execution of ``arn`` runs: the version itself, or+ for an alias the version _resolve_state_machine_arn picks. None for a+ base state machine."""+ if arn in _state_machine_versions:+ return arn+ alias = _state_machine_aliases.get(arn)+ routing = (alias or {}).get("routingConfiguration") or []+ if routing:+ return max(routing, key=lambda r: r.get("weight", 0)).get("stateMachineVersionArn")+ return None++def _resolve_state_machine_arn(arn):"""Resolve a state-machine, version, or alias ARN to the base state-machineARN. Returns None when the ARN doesn't match anything in any of the three@@ -638,6 +846,7 @@ def _start_execution(data):return error_response_json("StateMachineDoesNotExist",f"State machine {sm_arn} not found", 400)+ requested_arn = sm_arnsm_arn = base_arnsm = _state_machines[sm_arn]@@ -667,6 +876,12 @@ def _start_execution(data):"outputDetails": {"included": True},"testCase": test_case,"mockAttempts": {},+ # DescribeStateMachineForExecution reports the encryption configuration+ # the execution started with: the version's when a version or an alias+ # was named.+ "encryptionConfiguration": copy.deepcopy(+ (_state_machine_versions.get(_execution_version_arn(requested_arn)) or sm)+ .get("encryptionConfiguration") or _default_encryption()),"events": [{"id": 1, "type": "ExecutionStarted", "timestamp": start_date,"executionStartedEventDetails": {@@ -968,6 +1183,9 @@ def _describe_state_machine_for_execution(data):"definition": sm["definition"],"roleArn": sm["roleArn"],"updateDate": sm.get("creationDate", now_iso()),+ "encryptionConfiguration": copy.deepcopy(+ execution.get("encryptionConfiguration")+ or sm.get("encryptionConfiguration") or _default_encryption()),})@@ -5171,6 +5389,8 @@ def _publish_state_machine_version(data):"type": sm.get("type", "STANDARD"),"loggingConfiguration": copy.deepcopy(sm.get("loggingConfiguration", {"level": "OFF"})),+ "encryptionConfiguration": copy.deepcopy(+ sm.get("encryptionConfiguration") or _default_encryption()),}return json_response({"stateMachineVersionArn": version_arn,diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 645ab298..ff10b696 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -24677,6 +24677,202 @@ def test_cfn_state_machine_update_keeps_arn_and_executions(cfn, sfn):_delete_cfn_test_stack(cfn, stack_name)+def _sfn_encryption_template(name, encryption=None, declared=True):+ props = {+ "StateMachineName": name,+ "DefinitionString": _sfn_definition_json("enc"),+ "RoleArn": "arn:aws:iam::000000000000:role/sfn-role",+ }+ if declared:+ props["EncryptionConfiguration"] = encryption+ return json.dumps({+ "Resources": {"SM": {"Type": "AWS::StepFunctions::StateMachine", "Properties": props}},+ "Outputs": {"Arn": {"Value": {"Ref": "SM"}}},+ })+++def _sfn_cmk(key, period=300):+ cfg = {"type": "CUSTOMER_MANAGED_KMS_KEY", "kmsKeyId": key}+ if period is not None:+ cfg["kmsDataKeyReusePeriodSeconds"] = period+ return cfg+++def _cfn_sfn_update(cfn, stack_name, body):+ cfn.update_stack(StackName=stack_name, TemplateBody=body)+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ return stack+++def test_cfn_state_machine_encryption_configuration_create_and_update(cfn, sfn, kms_client):+ """CMK create, a string period updated in place, and a removed block that+ keeps the configuration. AWS: captured 2026-10-20 (sfn-encryption-configuration+ C44-C46; repeats sfn:C44, sfn:C45, sfn:C46:remove-block-after-600)."""+ key = kms_client.create_key()["KeyMetadata"]["Arn"]+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = name = f"cfn-sfn-enc-{uid}"+ cmk = {"Type": "CUSTOMER_MANAGED_KMS_KEY", "KmsKeyId": key}+ cfn.create_stack(StackName=stack_name, TemplateBody=_sfn_encryption_template(+ name, {**cmk, "KmsDataKeyReusePeriodSeconds": 300}))+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ arn = _output(stack, "Arn")+ assert sfn.describe_state_machine(stateMachineArn=arn)["encryptionConfiguration"] == _sfn_cmk(key)++ stack = _cfn_sfn_update(cfn, stack_name, _sfn_encryption_template(+ name, {**cmk, "KmsDataKeyReusePeriodSeconds": "600"}))+ assert _output(stack, "Arn") == arn+ assert sfn.describe_state_machine(stateMachineArn=arn)["encryptionConfiguration"] == _sfn_cmk(key, 600)++ _cfn_sfn_update(cfn, stack_name, _sfn_encryption_template(name, declared=False))+ assert sfn.describe_state_machine(stateMachineArn=arn)["encryptionConfiguration"] == _sfn_cmk(key, 600)+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+++def test_cfn_state_machine_encryption_configuration_period_defaults_to_300(cfn, sfn, kms_client):+ """A block without KmsDataKeyReusePeriodSeconds stores 300, on create and on+ an update from 600. AWS: captured 2026-10-20 (2308-cfn-period+ 5cfn:create-cmk-no-period, 5cfn:update-600-to-no-period)."""+ key = kms_client.create_key()["KeyMetadata"]["Arn"]+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = name = f"cfn-sfn-enc-noper-{uid}"+ cmk = {"Type": "CUSTOMER_MANAGED_KMS_KEY", "KmsKeyId": key}+ cfn.create_stack(StackName=stack_name, TemplateBody=_sfn_encryption_template(name, cmk))+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ arn = _output(stack, "Arn")+ assert sfn.describe_state_machine(stateMachineArn=arn)["encryptionConfiguration"] == _sfn_cmk(key, 300)++ _cfn_sfn_update(cfn, stack_name, _sfn_encryption_template(+ name, {**cmk, "KmsDataKeyReusePeriodSeconds": 600}))+ assert sfn.describe_state_machine(stateMachineArn=arn)["encryptionConfiguration"] == _sfn_cmk(key, 600)++ stack = _cfn_sfn_update(cfn, stack_name, _sfn_encryption_template(name, cmk))+ assert _output(stack, "Arn") == arn+ assert sfn.describe_state_machine(stateMachineArn=arn)["encryptionConfiguration"] == _sfn_cmk(key, 300)+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+++def test_cfn_state_machine_without_encryption_configuration_is_aws_owned_key(cfn, sfn):+ """AWS: captured 2026-10-20 (sfn-encryption-configuration C47)."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = name = f"cfn-sfn-enc-none-{uid}"+ cfn.create_stack(StackName=stack_name, TemplateBody=_sfn_encryption_template(name, declared=False))+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ assert sfn.describe_state_machine(stateMachineArn=_output(stack, "Arn"))[+ "encryptionConfiguration"] == {"type": "AWS_OWNED_KEY"}+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+++_UUID_RE = r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"+_SFN_ANY_KEY = "arn:aws:kms:us-east-1:000000000000:key/00000000-0000-0000-0000-000000000000"+_SFN_PERIOD_NOT_INTEGER = (+ 'Resource handler returned message: "Model validation failed (#/EncryptionConfiguration/'+ "KmsDataKeyReusePeriodSeconds: expected type: Integer, found: String. This may occur when a numeric "+ "value exceeds 32-bit integer max (2147483647). Consider using 'number' type or ensure value fits in "+ 'integer range.)" (RequestToken: ')++[email protected]("encryption,reason", [+ ({"Type": "CUSTOMER_MANAGED_KMS_KEY"},+ re.escape('Resource handler returned message: "Invalid Encryption Configuration: Must set a valid '+ 'kmsKeyId. (Service: Sfn, Status Code: 400, Request ID: ') + _UUID_RE+ + re.escape(') (SDK Attempt Count: 1)" (RequestToken: ') + _UUID_RE+ + re.escape(", HandlerErrorCode: InvalidRequest)")),+ ("AWS_OWNED_KEY",+ re.escape('Resource handler returned message: "Model validation failed (#/EncryptionConfiguration: '+ 'expected type: JSONObject, found: String)" (RequestToken: ') + _UUID_RE+ + re.escape(", HandlerErrorCode: InvalidRequest)")),+ ({},+ re.escape('Resource handler returned message: "Model validation failed (#/EncryptionConfiguration: '+ 'required key [Type] not found)" (RequestToken: ') + _UUID_RE+ + re.escape(", HandlerErrorCode: InvalidRequest)")),+ # captures/2308-pr-uncertainties.json U16, U17, U18+ ({"Type": "SOME_OTHER_KEY"},+ re.escape('Resource handler returned message: "Model validation failed (#/EncryptionConfiguration/Type: '+ '#: only 1 subschema matches out of 2)\n#/EncryptionConfiguration/Type: failed validation '+ 'constraint for keyword [enum] (#/EncryptionConfiguration/Type)" (RequestToken: ') + _UUID_RE+ + re.escape(", HandlerErrorCode: InvalidRequest)")),+ ({"Type": "CUSTOMER_MANAGED_KMS_KEY", "KmsKeyId": _SFN_ANY_KEY, "KmsDataKeyReusePeriodSeconds": 59},+ re.escape('Resource handler returned message: "Model validation failed (#/EncryptionConfiguration/'+ 'KmsDataKeyReusePeriodSeconds: failed validation constraint for keyword [minimum])" '+ '(RequestToken: ') + _UUID_RE + re.escape(", HandlerErrorCode: InvalidRequest)")),+ ({"Type": "CUSTOMER_MANAGED_KMS_KEY", "KmsKeyId": ""},+ re.escape('Resource handler returned message: "Model validation failed (#/EncryptionConfiguration/'+ 'KmsKeyId: expected minLength: 1, actual: 0)" (RequestToken: ') + _UUID_RE+ + re.escape(", HandlerErrorCode: InvalidRequest)")),+ ({"Type": "AWS_OWNED_KEY", "KmsKeyId": _SFN_ANY_KEY},+ re.escape('Resource handler returned message: "Invalid Encryption Configuration: Custom kmsKeyId is not '+ 'allowed when selecting AWS_OWNED_KEY. (Service: Sfn, Status Code: 400, Request ID: ') + _UUID_RE+ + re.escape(') (SDK Attempt Count: 1)" (RequestToken: ') + _UUID_RE+ + re.escape(", HandlerErrorCode: InvalidRequest)")),+ (5,+ re.escape('Resource handler returned message: "Model validation failed (#/EncryptionConfiguration: '+ 'expected type: JSONObject, found: String)" (RequestToken: ') + _UUID_RE+ + re.escape(", HandlerErrorCode: InvalidRequest)")),+ (True,+ re.escape('Resource handler returned message: "Model validation failed (#/EncryptionConfiguration: '+ 'expected type: JSONObject, found: String)" (RequestToken: ') + _UUID_RE+ + re.escape(", HandlerErrorCode: InvalidRequest)")),+ ([],+ re.escape('Resource handler returned message: "Model validation failed (#/EncryptionConfiguration: '+ 'expected type: JSONObject, found: JSONArray)" (RequestToken: ') + _UUID_RE+ + re.escape(", HandlerErrorCode: InvalidRequest)")),+ ({"Type": "CUSTOMER_MANAGED_KMS_KEY", "KmsKeyId": _SFN_ANY_KEY, "KmsDataKeyReusePeriodSeconds": "abc"},+ re.escape(_SFN_PERIOD_NOT_INTEGER) + _UUID_RE + re.escape(", HandlerErrorCode: InvalidRequest)")),+ ({"Type": "CUSTOMER_MANAGED_KMS_KEY", "KmsKeyId": _SFN_ANY_KEY, "KmsDataKeyReusePeriodSeconds": "600.0"},+ re.escape(_SFN_PERIOD_NOT_INTEGER) + _UUID_RE + re.escape(", HandlerErrorCode: InvalidRequest)")),+ # captures/2308-pr-uncertainties-2.json U23+ ({"Type": "CUSTOMER_MANAGED_KMS_KEY", "KmsKeyId": _SFN_ANY_KEY, "KmsDataKeyReusePeriodSeconds": 901},+ re.escape('Resource handler returned message: "Model validation failed (#/EncryptionConfiguration/'+ 'KmsDataKeyReusePeriodSeconds: failed validation constraint for keyword [maximum])" '+ '(RequestToken: ') + _UUID_RE + re.escape(", HandlerErrorCode: InvalidRequest)")),+ ({"Type": "CUSTOMER_MANAGED_KMS_KEY", "KmsKeyId": "k" * 2049},+ re.escape('Resource handler returned message: "Model validation failed (#/EncryptionConfiguration/'+ 'KmsKeyId: expected maxLength: 2048, actual: 2049)" (RequestToken: ') + _UUID_RE+ + re.escape(", HandlerErrorCode: InvalidRequest)")),+ ({"Type": "SOME_OTHER_KEY", "KmsKeyId": ""},+ re.escape('Resource handler returned message: "Model validation failed (#/EncryptionConfiguration: 2 schema '+ 'violations found)\n#/EncryptionConfiguration/Type: #: only 1 subschema matches out of 2 '+ '(#/EncryptionConfiguration/Type)\n#/EncryptionConfiguration/KmsKeyId: expected minLength: 1, '+ 'actual: 0 (#/EncryptionConfiguration/KmsKeyId)" (RequestToken: ') + _UUID_RE+ + re.escape(", HandlerErrorCode: InvalidRequest)")),+ ({"Type": "CUSTOMER_MANAGED_KMS_KEY", "KmsKeyId": "", "KmsDataKeyReusePeriodSeconds": 59},+ re.escape('Resource handler returned message: "Model validation failed (#/EncryptionConfiguration: 2 schema '+ 'violations found)\n#/EncryptionConfiguration/KmsKeyId: expected minLength: 1, actual: 0 '+ '(#/EncryptionConfiguration/KmsKeyId)\n#/EncryptionConfiguration/KmsDataKeyReusePeriodSeconds: '+ 'failed validation constraint for keyword [minimum] '+ '(#/EncryptionConfiguration/KmsDataKeyReusePeriodSeconds)" (RequestToken: ') + _UUID_RE+ + re.escape(", HandlerErrorCode: InvalidRequest)")),+], ids=["cmk-without-key", "string-block", "empty-block", "bad-type", "period-59", "empty-key",+ "owned-with-key", "number-block", "bool-block", "list-block", "period-abc", "period-decimal-string",+ "period-901", "long-key", "bad-type-and-empty-key", "empty-key-and-period-59"])+def test_cfn_state_machine_invalid_encryption_configuration_fails(cfn, sfn, encryption, reason):+ """AWS: captured 2026-10-20 (sfn-encryption-configuration C48, C49, C51)."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = name = f"cfn-sfn-enc-bad-{uid}"+ cfn.create_stack(StackName=stack_name, TemplateBody=_sfn_encryption_template(name, encryption))+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "ROLLBACK_COMPLETE", stack["StackStatus"]+ failed = [e["ResourceStatusReason"]+ for e in _all_pages(cfn, "describe_stack_events", "StackEvents", StackName=stack_name)+ if e["LogicalResourceId"] == "SM" and e["ResourceStatus"] == "CREATE_FAILED"]+ assert len(failed) == 1, failed+ assert re.fullmatch(reason, failed[0]), failed[0]+ assert name not in [m["name"] for m in sfn.list_state_machines()["stateMachines"]]+ finally:+ _delete_cfn_test_stack(cfn, stack_name)++def test_cfn_state_machine_type_change_under_custom_name_fails_loudly(cfn, sfn):"""StateMachineType requires replacement, which CloudFormation refusesfor a custom-named machine: the stack rolls back and the machine keeps@@ -36984,3 +37180,33 @@ def test_cfn_other_resource_tag_reconciliation_remains_case_sensitive():assert _identity_tag_map(store) == {"Department": "External", "DEPARTMENT": "After"}_reconcile_tag_list(store, {"Tags": [{"Key": "DEPARTMENT", "Value": "After"}]}, {})assert _identity_tag_map(store) == {"Department": "External"}+++def test_cfn_state_machine_refused_encryption_update_rolls_back(cfn, sfn, kms_client):+ """AWS: captured 2026-10-20 (captures/2308-pr-uncertainties.json U15:update-to-cmk-without-key)."""+ key = kms_client.create_key()["KeyMetadata"]["Arn"]+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = name = f"cfn-sfn-enc-upd-bad-{uid}"+ good = {"Type": "CUSTOMER_MANAGED_KMS_KEY", "KmsKeyId": key, "KmsDataKeyReusePeriodSeconds": 300}+ cfn.create_stack(StackName=stack_name, TemplateBody=_sfn_encryption_template(name, good))+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ arn = _output(stack, "Arn")+ cfn.update_stack(StackName=stack_name, TemplateBody=_sfn_encryption_template(+ name, {"Type": "CUSTOMER_MANAGED_KMS_KEY"}))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack["StackStatus"]+ failed = [e["ResourceStatusReason"]+ for e in _all_pages(cfn, "describe_stack_events", "StackEvents", StackName=stack_name)+ if e["LogicalResourceId"] == "SM" and e["ResourceStatus"] == "UPDATE_FAILED"]+ assert len(failed) == 1, failed+ assert re.fullmatch(+ re.escape('Resource handler returned message: "Invalid Encryption Configuration: Must set a valid '+ 'kmsKeyId. (Service: Sfn, Status Code: 400, Request ID: ') + _UUID_RE+ + re.escape(') (SDK Attempt Count: 1)" (RequestToken: ') + _UUID_RE+ + re.escape(", HandlerErrorCode: InvalidRequest)"), failed[0]), failed[0]+ assert sfn.describe_state_machine(stateMachineArn=arn)["encryptionConfiguration"] == _sfn_cmk(key)+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.pyindex c028de62..62c31925 100644--- a/tests/test_stepfunctions.py+++ b/tests/test_stepfunctions.py@@ -12,7 +12,7 @@ import boto3import pytestfrom botocore.config import Configfrom botocore.exceptions import ClientError-from conftest import ENDPOINT, LoopProbe, concurrent_burst, sqs_policy_allow_sns+from conftest import ENDPOINT, LoopProbe, concurrent_burst, make_client, sqs_policy_allow_snsdef _make_zip(code: str) -> bytes:@@ -9298,3 +9298,683 @@ def test_sdk_lambda_get_function_missing_function_exact_catch(sfn):"Lambda.ResourceNotFoundException")assert result["status"] == "SUCCEEDED", resultassert json.loads(result["output"])["caught"]["Error"] == "Lambda.ResourceNotFoundException"++++# ---------------------------------------------------------------------------+# encryptionConfiguration on state machines. Every expectation below is what+# AWS answered in us-east-1 on 2026-10-20 (issue #2308 captures). MiniStack+# does not look the key up in KMS; these tests use a MiniStack KMS key so they+# would hold either way.+# ---------------------------------------------------------------------------++_ENC_DEFINITION = json.dumps({"StartAt": "Done", "States": {"Done": {"Type": "Succeed"}}})+_ENC_NEW_DEFINITION = json.dumps({"StartAt": "P", "States": {"P": {"Type": "Pass", "End": True}}})+_ENC_ROLE = "arn:aws:iam::000000000000:role/sfn-role"+_ENC_DEFAULT = {"type": "AWS_OWNED_KEY"}+_CMK = "CUSTOMER_MANAGED_KMS_KEY"+_KEY = "<key>" # stands for the module's KMS key ARN in the tables below++[email protected](scope="module")+def enc_key(kms_client):+ return kms_client.create_key()["KeyMetadata"]["Arn"]+++def _cmk(key, period=300):+ cfg = {"type": _CMK, "kmsKeyId": key}+ if period is not None:+ cfg["kmsDataKeyReusePeriodSeconds"] = period+ return cfg+++def _with_key(cfg, key):+ if isinstance(cfg, dict):+ return {k: key if v == _KEY else v for k, v in cfg.items()}+ return cfg+++def _enc_name(prefix):+ return f"{prefix}-{_uuid_mod.uuid4().hex[:8]}"+++def _sm_arn(name):+ return f"arn:aws:states:us-east-1:000000000000:stateMachine:{name}"+++@contextmanager+def _enc_machine(sfn, prefix, **kwargs):+ arn = sfn.create_state_machine(+ name=_enc_name(prefix), definition=_ENC_DEFINITION,+ roleArn=_ENC_ROLE, **kwargs)["stateMachineArn"]+ try:+ yield arn+ finally:+ sfn.delete_state_machine(stateMachineArn=arn)+++def _sfn_unvalidated():+ """A client without boto3's client-side parameter validation, so+ out-of-range values reach the server."""+ return make_client("stepfunctions", {"parameter_validation": False})+++def _sfn_raw(action, body):+ """POST a raw JSON 1.0 request, for values boto3 refuses to serialize."""+ import urllib.error+ import urllib.request++ req = urllib.request.Request(+ f"{ENDPOINT}/",+ data=json.dumps(body).encode("utf-8"),+ headers={+ "Content-Type": "application/x-amz-json-1.0",+ "X-Amz-Target": f"AWSStepFunctions.{action}",+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20200101/us-east-1/states/aws4_request, SignedHeaders=host;x-amz-date;x-amz-target, Signature=00",+ "X-Amz-Date": "20200101T000000Z",+ },+ method="POST",+ )+ try:+ with urllib.request.urlopen(req) as r:+ return r.getcode(), json.loads(r.read())+ except urllib.error.HTTPError as e:+ return e.code, json.loads(e.read())+++def _assert_sfn_error(exc_info, code, message=None):+ """The error code and HTTP status, and the exact message when given. The+ StateMachineAlreadyExists and StateMachineDoesNotExist wording is shared+ with other Step Functions calls and outside this change, so those checks+ pass no message."""+ response = exc_info.value.response+ assert response["Error"]["Code"] == code+ if message is not None:+ assert response["Error"]["Message"] == message+ assert response["ResponseMetadata"]["HTTPStatusCode"] == 400+++def _sfn_exists(sfn, arn):+ try:+ sfn.describe_state_machine(stateMachineArn=arn)+ except ClientError as exc:+ assert exc.response["Error"]["Code"] == "StateMachineDoesNotExist"+ return False+ return True+++def _encryption(sfn, arn):+ return sfn.describe_state_machine(stateMachineArn=arn)["encryptionConfiguration"]+++def test_sfn_encryption_configuration_defaults_to_aws_owned_key(sfn):+ """AWS: captured 2026-10-20 (sfn-encryption-configuration C1, C5)."""+ with _enc_machine(sfn, "enc-default") as arn:+ assert _encryption(sfn, arn) == _ENC_DEFAULT+ with _enc_machine(sfn, "enc-owned", encryptionConfiguration=_ENC_DEFAULT) as arn:+ assert _encryption(sfn, arn) == _ENC_DEFAULT+++def test_sfn_encryption_configuration_null_is_absent(sfn):+ """AWS: captured 2026-10-20 (2308-followup 6:config-null, raw request)."""+ name = _enc_name("enc-null")+ status, body = _sfn_raw("CreateStateMachine", {+ "name": name, "definition": _ENC_DEFINITION, "roleArn": _ENC_ROLE,+ "encryptionConfiguration": None})+ assert status == 200, body+ try:+ assert _encryption(sfn, body["stateMachineArn"]) == _ENC_DEFAULT+ finally:+ sfn.delete_state_machine(stateMachineArn=body["stateMachineArn"])+++def test_sfn_encryption_configuration_customer_managed_key_round_trip(sfn, enc_key):+ """AWS: captured 2026-10-20 (sfn-encryption-configuration C2)."""+ with _enc_machine(sfn, "enc-cmk", encryptionConfiguration=_cmk(enc_key)) as arn:+ assert _encryption(sfn, arn) == _cmk(enc_key)+++def test_sfn_encryption_configuration_create_defaults_period_to_300(sfn, enc_key):+ """AWS: captured 2026-10-20 (sfn-encryption-configuration C4)."""+ with _enc_machine(sfn, "enc-noper", encryptionConfiguration=_cmk(enc_key, None)) as arn:+ assert _encryption(sfn, arn) == _cmk(enc_key, 300)++[email protected]("created_with", [None, 600], ids=["over-aws-owned-key", "over-600"])+def test_sfn_encryption_configuration_update_defaults_period_to_300(sfn, enc_key, created_with):+ """AWS: captured 2026-10-20 (2308-followup 5:update-owned-to-cmk-no-period,+ 5:update-cmk600-to-cmk-no-period)."""+ kwargs = {} if created_with is None else {"encryptionConfiguration": _cmk(enc_key, created_with)}+ with _enc_machine(sfn, "enc-upd-noper", **kwargs) as arn:+ sfn.update_state_machine(stateMachineArn=arn, definition=_ENC_NEW_DEFINITION,+ encryptionConfiguration=_cmk(enc_key, None))+ assert _encryption(sfn, arn) == _cmk(enc_key, 300)+++def test_sfn_encryption_configuration_update_replaces_or_keeps_it(sfn, enc_key):+ """AWS: captured 2026-10-20 (sfn-encryption-configuration C8, C9)."""+ with _enc_machine(sfn, "enc-upd", encryptionConfiguration=_cmk(enc_key)) as arn:+ sfn.update_state_machine(stateMachineArn=arn, definition=_ENC_DEFINITION,+ encryptionConfiguration=_ENC_DEFAULT)+ assert _encryption(sfn, arn) == _ENC_DEFAULT+ sfn.update_state_machine(stateMachineArn=arn, definition=_ENC_DEFINITION,+ encryptionConfiguration=_cmk(enc_key, 600))+ sfn.update_state_machine(stateMachineArn=arn, roleArn=_ENC_ROLE)+ assert _encryption(sfn, arn) == _cmk(enc_key, 600)+++def test_sfn_encryption_configuration_update_without_definition_is_refused(sfn, enc_key):+ """AWS: captured 2026-10-20 (sfn-encryption-configuration C42)."""+ with _enc_machine(sfn, "enc-nodef", encryptionConfiguration=_cmk(enc_key)) as arn:+ with pytest.raises(ClientError) as exc:+ sfn.update_state_machine(stateMachineArn=arn, encryptionConfiguration=_cmk(enc_key, 600))+ _assert_sfn_error(exc, "MissingRequiredParameter",+ "The definition must be specified when updating the EncryptionConfiguration")+ described = sfn.describe_state_machine(stateMachineArn=arn)+ assert described["encryptionConfiguration"] == _cmk(enc_key)+ assert described["definition"] == _ENC_DEFINITION+++def test_sfn_encryption_configuration_versions_keep_their_snapshot(sfn, enc_key):+ """AWS: captured 2026-10-20 (sfn-encryption-configuration C10-C12)."""+ with _enc_machine(sfn, "enc-ver", encryptionConfiguration=_cmk(enc_key), publish=True) as arn:+ v1 = f"{arn}:1"+ v2 = sfn.update_state_machine(+ stateMachineArn=arn, definition=_ENC_DEFINITION,+ encryptionConfiguration=_ENC_DEFAULT, publish=True)["stateMachineVersionArn"]+ sfn.update_state_machine(stateMachineArn=arn, definition=_ENC_DEFINITION,+ encryptionConfiguration=_cmk(enc_key, 120))+ v3 = sfn.publish_state_machine_version(stateMachineArn=arn)["stateMachineVersionArn"]+ try:+ assert _encryption(sfn, v3) == _cmk(enc_key, 120)+ assert _encryption(sfn, v1) == _cmk(enc_key)+ assert _encryption(sfn, v2) == _ENC_DEFAULT+ finally:+ for version in (v1, v2, v3):+ sfn.delete_state_machine_version(stateMachineVersionArn=version)+++def test_sfn_encryption_configuration_on_describe_for_execution(sfn, enc_key):+ """AWS: captured 2026-10-20 (sfn-encryption-configuration C14)."""+ with _enc_machine(sfn, "enc-exec", encryptionConfiguration=_cmk(enc_key)) as arn:+ execution = sfn.start_execution(stateMachineArn=arn, input="{}")["executionArn"]+ described = sfn.describe_state_machine_for_execution(executionArn=execution)+ assert described["encryptionConfiguration"] == _cmk(enc_key)+++def test_sfn_encryption_configuration_is_part_of_create_idempotency(sfn, enc_key):+ """AWS: captured 2026-10-20 (sfn-encryption-configuration C15-C19)."""+ name = _enc_name("enc-idem")+ created = sfn.create_state_machine(name=name, definition=_ENC_DEFINITION, roleArn=_ENC_ROLE,+ encryptionConfiguration=_cmk(enc_key))+ arn = created["stateMachineArn"]+ try:+ again = sfn.create_state_machine(name=name, definition=_ENC_DEFINITION, roleArn=_ENC_ROLE,+ encryptionConfiguration=_cmk(enc_key))+ assert again["stateMachineArn"] == arn+ assert again["creationDate"] == created["creationDate"]+ for different in ({"encryptionConfiguration": _ENC_DEFAULT},+ {"encryptionConfiguration": _cmk(enc_key, 900)},+ {}):+ with pytest.raises(ClientError) as exc:+ sfn.create_state_machine(name=name, definition=_ENC_DEFINITION,+ roleArn=_ENC_ROLE, **different)+ _assert_sfn_error(exc, "StateMachineAlreadyExists")+ assert _encryption(sfn, arn) == _cmk(enc_key)+ finally:+ sfn.delete_state_machine(stateMachineArn=arn)+++def _enc_kwargs(form, key):+ return {+ "omitted": {},+ "aws-owned-key": {"encryptionConfiguration": _ENC_DEFAULT},+ "cmk-300": {"encryptionConfiguration": _cmk(key, 300)},+ "cmk-no-period": {"encryptionConfiguration": _cmk(key, None)},+ }[form]++[email protected]("first,second", [+ ("omitted", "aws-owned-key"),+ ("cmk-300", "cmk-no-period"),+ ("cmk-no-period", "cmk-300"),+])+def test_sfn_encryption_configuration_equivalent_forms_are_idempotent(sfn, enc_key, first, second):+ """AWS: captured 2026-10-20 (sfn-encryption-configuration C20; 2308-followup+ 5:recreate-no-period-on-stored-300, 5:recreate-300-on-created-without-period)."""+ name = _enc_name("enc-idem-eq")+ created = sfn.create_state_machine(name=name, definition=_ENC_DEFINITION, roleArn=_ENC_ROLE,+ **_enc_kwargs(first, enc_key))+ try:+ again = sfn.create_state_machine(name=name, definition=_ENC_DEFINITION, roleArn=_ENC_ROLE,+ **_enc_kwargs(second, enc_key))+ assert again["stateMachineArn"] == created["stateMachineArn"]+ assert again["creationDate"] == created["creationDate"]+ finally:+ sfn.delete_state_machine(stateMachineArn=created["stateMachineArn"])+++def _period_min(value):+ return (f"Value '{value}' at 'encryptionConfiguration.kmsDataKeyReusePeriodSeconds' "+ "failed to satisfy constraint: Member must have value greater than or equal to 60")+++def _period_max(value):+ return (f"Value '{value}' at 'encryptionConfiguration.kmsDataKeyReusePeriodSeconds' "+ "failed to satisfy constraint: Member must have value less than or equal to 900")+++_KEY_EMPTY = ("Value '' at 'encryptionConfiguration.kmsKeyId' failed to satisfy constraint: "+ "Member must have length greater than or equal to 1")+_LONG_KEY = "k" * 2049+_KEY_LONG = (f"Value '{_LONG_KEY}' at 'encryptionConfiguration.kmsKeyId' failed to satisfy "+ "constraint: Member must have length less than or equal to 2048")+_TYPE_NULL = ("Value null at 'encryptionConfiguration.type' failed to satisfy constraint: "+ "Member must not be null")+_TYPE_ENUM = ("Value 'SOME_OTHER_KEY' at 'encryptionConfiguration.type' failed to satisfy "+ "constraint: Member must satisfy enum value set: [AWS_OWNED_KEY, CUSTOMER_MANAGED_KMS_KEY]")+_NO_KEY = "Invalid Encryption Configuration: Must set a valid kmsKeyId."+_OWNED_WITH_KEY = ("Invalid Encryption Configuration: Custom kmsKeyId is not allowed "+ "when selecting AWS_OWNED_KEY.")+_OWNED_WITH_PERIOD = ("Invalid Encryption Configuration: Custom kmsDataKeyReusePeriodSeconds "+ "is not allowed when selecting AWS_OWNED_KEY.")+++def _one_error(problem):+ return f"1 validation error detected: {problem}"+++# (id, encryptionConfiguration, code, message, also captured on UpdateStateMachine)+# Create: sfn-encryption-configuration C6, C21-C27; 2308-followup 2:owned-period-*,+# 4:create-multi-*. Update: C33-C39; 2308-followup 4:update-multi-*.+_ENC_VALIDATION_ROWS = [+ ("no-type", {}, "ValidationException", _one_error(_TYPE_NULL), True),+ ("bad-type", {"type": "SOME_OTHER_KEY"}, "ValidationException", _one_error(_TYPE_ENUM), True),+ ("empty-key", {"type": _CMK, "kmsKeyId": ""}, "ValidationException", _one_error(_KEY_EMPTY), True),+ ("long-key", {"type": _CMK, "kmsKeyId": _LONG_KEY}, "ValidationException", _one_error(_KEY_LONG), True),+ ("period-59-alias", {"type": _CMK, "kmsKeyId": "alias/k", "kmsDataKeyReusePeriodSeconds": 59},+ "ValidationException", _one_error(_period_min(59)), True),+ ("period-59-key", {"type": _CMK, "kmsKeyId": _KEY, "kmsDataKeyReusePeriodSeconds": 59},+ "ValidationException", _one_error(_period_min(59)), True),+ ("period-901-alias", {"type": _CMK, "kmsKeyId": "alias/k", "kmsDataKeyReusePeriodSeconds": 901},+ "ValidationException", _one_error(_period_max(901)), True),+ ("period-901-key", {"type": _CMK, "kmsKeyId": _KEY, "kmsDataKeyReusePeriodSeconds": 901},+ "ValidationException", _one_error(_period_max(901)), True),+ ("cmk-without-key", {"type": _CMK}, "InvalidEncryptionConfiguration", _NO_KEY, True),+ ("aws-owned-key-with-key", {"type": "AWS_OWNED_KEY", "kmsKeyId": _KEY},+ "InvalidEncryptionConfiguration", _OWNED_WITH_KEY, False),+ ("aws-owned-key-period-300", {"type": "AWS_OWNED_KEY", "kmsDataKeyReusePeriodSeconds": 300},+ "InvalidEncryptionConfiguration", _OWNED_WITH_PERIOD, False),+ ("aws-owned-key-period-30", {"type": "AWS_OWNED_KEY", "kmsDataKeyReusePeriodSeconds": 30},+ "ValidationException", _one_error(_period_min(30)), False),+ ("aws-owned-key-period-1000", {"type": "AWS_OWNED_KEY", "kmsDataKeyReusePeriodSeconds": 1000},+ "ValidationException", _one_error(_period_max(1000)), False),+ ("empty-key-period-59", {"type": _CMK, "kmsKeyId": "", "kmsDataKeyReusePeriodSeconds": 59},+ "ValidationException",+ f"2 validation errors detected: {_period_min(59)}; {_KEY_EMPTY}", True),+ ("bad-type-empty-key-period-59",+ {"type": "SOME_OTHER_KEY", "kmsKeyId": "", "kmsDataKeyReusePeriodSeconds": 59},+ "ValidationException",+ f"3 validation errors detected: {_period_min(59)}; {_KEY_EMPTY}; {_TYPE_ENUM}", True),+]++# (id, encryptionConfiguration as sent on the wire, Message, also captured on Update)+# Create: sfn-encryption-configuration C28-C30; 2308-followup 6:config-number-1,+# 6:config-array-empty. Update: 2308-followup 4:update-serialization-*.+_ENC_SERIALIZATION_ROWS = [+ ("config-string", "AWS_OWNED_KEY", "Expected null", True),+ ("period-string", {"type": _CMK, "kmsKeyId": _KEY, "kmsDataKeyReusePeriodSeconds": "300"},+ "STRING_VALUE can not be converted to an Integer", True),+ ("period-true", {"type": _CMK, "kmsKeyId": _KEY, "kmsDataKeyReusePeriodSeconds": True},+ "TRUE_VALUE can not be converted to an Integer", True),+ ("config-number", 1, "Expected null", False),+ ("config-list", [], "Start of list found where not expected", False),+ # 2308-pr-uncertainties U1, U2, U3 (Create only)+ ("config-true", True, "Expected null", False),+ ("config-false", False, "Expected null", False),+ ("period-false", {"type": _CMK, "kmsKeyId": _KEY, "kmsDataKeyReusePeriodSeconds": False},+ "FALSE_VALUE can not be converted to an Integer", False),+ ("period-list", {"type": _CMK, "kmsKeyId": _KEY, "kmsDataKeyReusePeriodSeconds": []},+ "Start of list found where not expected", False),+ ("period-object", {"type": _CMK, "kmsKeyId": _KEY, "kmsDataKeyReusePeriodSeconds": {}},+ "Start of structure or map found where not expected.", False),+ ("type-number", {"type": 5}, "NUMBER_VALUE can not be converted to a String", False),+ ("type-list", {"type": []}, "Start of list found where not expected", False),+ ("type-object", {"type": {}}, "Start of structure or map found where not expected.", False),+ ("key-number", {"type": _CMK, "kmsKeyId": 5}, "NUMBER_VALUE can not be converted to a String", False),+ ("key-true", {"type": _CMK, "kmsKeyId": True}, "TRUE_VALUE can not be converted to a String", False),+ # 2308-pr-uncertainties-2 U21, U22: false in a String member; the member AWS reports+ # when two are mistyped is fixed (period, kmsKeyId, type), whatever the request order.+ ("key-false", {"type": _CMK, "kmsKeyId": False}, "FALSE_VALUE can not be converted to a String", False),+ ("type-false", {"type": False}, "FALSE_VALUE can not be converted to a String", False),+ ("type-then-key", {"type": 5, "kmsKeyId": True}, "TRUE_VALUE can not be converted to a String", False),+ ("key-then-type", {"kmsKeyId": True, "type": 5}, "TRUE_VALUE can not be converted to a String", False),+ ("period-then-type", {"kmsDataKeyReusePeriodSeconds": "x", "type": 5},+ "STRING_VALUE can not be converted to an Integer", False),+]+++def _rows(rows, update_only=False):+ return [pytest.param(*row[1:-1], id=row[0]) for row in rows if row[-1] or not update_only]++[email protected]("cfg,code,message", _rows(_ENC_VALIDATION_ROWS))+def test_sfn_create_refuses_invalid_encryption_configuration(sfn, enc_key, cfg, code, message):+ """AWS: captured 2026-10-20 (rows in _ENC_VALIDATION_ROWS)."""+ name = _enc_name("enc-bad")+ with pytest.raises(ClientError) as exc:+ _sfn_unvalidated().create_state_machine(+ name=name, definition=_ENC_DEFINITION, roleArn=_ENC_ROLE,+ encryptionConfiguration=_with_key(cfg, enc_key))+ _assert_sfn_error(exc, code, message)+ assert not _sfn_exists(sfn, _sm_arn(name))++[email protected]("cfg,code,message", _rows(_ENC_VALIDATION_ROWS, update_only=True))+def test_sfn_update_refuses_invalid_encryption_configuration(sfn, enc_key, cfg, code, message):+ """A refused update changes neither the definition nor the configuration.+ AWS: captured 2026-10-20 (rows in _ENC_VALIDATION_ROWS marked for Update)."""+ with _enc_machine(sfn, "enc-bad-upd", encryptionConfiguration=_cmk(enc_key)) as arn:+ with pytest.raises(ClientError) as exc:+ _sfn_unvalidated().update_state_machine(+ stateMachineArn=arn, definition=_ENC_NEW_DEFINITION,+ encryptionConfiguration=_with_key(cfg, enc_key))+ _assert_sfn_error(exc, code, message)+ described = sfn.describe_state_machine(stateMachineArn=arn)+ assert described["encryptionConfiguration"] == _cmk(enc_key)+ assert described["definition"] == _ENC_DEFINITION+++def _assert_serialization_error(status, body, message):+ assert status == 400, body+ assert body["__type"].rsplit("#", 1)[-1] == "SerializationException"+ assert body["Message"] == message+ assert "message" not in body++[email protected]("cfg,message", _rows(_ENC_SERIALIZATION_ROWS))+def test_sfn_create_refuses_mistyped_encryption_configuration(sfn, enc_key, cfg, message):+ """AWS: captured 2026-10-20 (rows in _ENC_SERIALIZATION_ROWS, raw requests)."""+ name = _enc_name("enc-ser")+ status, body = _sfn_raw("CreateStateMachine", {+ "name": name, "definition": _ENC_DEFINITION, "roleArn": _ENC_ROLE,+ "encryptionConfiguration": _with_key(cfg, enc_key)})+ _assert_serialization_error(status, body, message)+ assert not _sfn_exists(sfn, _sm_arn(name))++[email protected]("cfg,message", _rows(_ENC_SERIALIZATION_ROWS, update_only=True))+def test_sfn_update_refuses_mistyped_encryption_configuration(sfn, enc_key, cfg, message):+ """AWS: captured 2026-10-20 (2308-followup 4:update-serialization-*, raw requests)."""+ with _enc_machine(sfn, "enc-ser-upd", encryptionConfiguration=_cmk(enc_key)) as arn:+ status, body = _sfn_raw("UpdateStateMachine", {+ "stateMachineArn": arn, "definition": _ENC_NEW_DEFINITION,+ "encryptionConfiguration": _with_key(cfg, enc_key)})+ _assert_serialization_error(status, body, message)+ described = sfn.describe_state_machine(stateMachineArn=arn)+ assert described["encryptionConfiguration"] == _cmk(enc_key)+ assert described["definition"] == _ENC_DEFINITION+++def test_sfn_create_checks_encryption_shape_before_definition(sfn):+ """AWS: captured 2026-10-20 (2308-followup 4:create-empty-config-invalid-definition)."""+ name = _enc_name("enc-order-shape")+ with pytest.raises(ClientError) as exc:+ _sfn_unvalidated().create_state_machine(+ name=name, definition="this is not json", roleArn=_ENC_ROLE, encryptionConfiguration={})+ _assert_sfn_error(exc, "ValidationException", _one_error(_TYPE_NULL))+ assert not _sfn_exists(sfn, _sm_arn(name))+++def test_sfn_create_checks_encryption_before_existing_machine(sfn, enc_key):+ """AWS: captured 2026-10-20 (sfn-encryption-configuration C32)."""+ with _enc_machine(sfn, "enc-order-exists", encryptionConfiguration=_cmk(enc_key)) as arn:+ name = arn.rsplit(":", 1)[-1]+ for cfg, code, message in (+ ({"type": "SOME_OTHER_KEY"}, "ValidationException", _one_error(_TYPE_ENUM)),+ ({"type": _CMK}, "InvalidEncryptionConfiguration", _NO_KEY)):+ with pytest.raises(ClientError) as exc:+ sfn.create_state_machine(name=name, definition=_ENC_DEFINITION, roleArn=_ENC_ROLE,+ encryptionConfiguration=cfg)+ _assert_sfn_error(exc, code, message)+ assert _encryption(sfn, arn) == _cmk(enc_key)+++def test_sfn_update_checks_encryption_shape_before_missing_machine(sfn):+ """AWS: captured 2026-10-20 (2308-followup 4:update-missing-machine-empty-config)."""+ with pytest.raises(ClientError) as exc:+ _sfn_unvalidated().update_state_machine(stateMachineArn=_sm_arn(_enc_name("enc-never")),+ definition=_ENC_DEFINITION, encryptionConfiguration={})+ _assert_sfn_error(exc, "ValidationException", _one_error(_TYPE_NULL))+++def test_sfn_update_checks_missing_machine_before_encryption_type_fit(sfn):+ """AWS: captured 2026-10-20 (sfn-encryption-configuration C40)."""+ arn = _sm_arn(_enc_name("enc-never"))+ with pytest.raises(ClientError) as exc:+ sfn.update_state_machine(stateMachineArn=arn, definition=_ENC_DEFINITION,+ encryptionConfiguration={"type": _CMK})+ _assert_sfn_error(exc, "StateMachineDoesNotExist")++[email protected]("definition", [{"definition": "this is not json"}, {}],+ ids=["invalid-definition", "no-definition"])+def test_sfn_update_checks_encryption_type_fit_before_definition(sfn, enc_key, definition):+ """AWS: captured 2026-10-20 (sfn-encryption-configuration C41; 2308-followup+ 4:update-no-definition-invalid-config)."""+ with _enc_machine(sfn, "enc-order-upd", encryptionConfiguration=_cmk(enc_key)) as arn:+ with pytest.raises(ClientError) as exc:+ sfn.update_state_machine(stateMachineArn=arn, encryptionConfiguration={"type": _CMK},+ **definition)+ _assert_sfn_error(exc, "InvalidEncryptionConfiguration", _NO_KEY)+ described = sfn.describe_state_machine(stateMachineArn=arn)+ assert described["encryptionConfiguration"] == _cmk(enc_key)+ assert described["definition"] == _ENC_DEFINITION+++def test_sfn_encryption_configuration_persists_and_defaults_for_older_records(enc_key):+ """get_state/restore keeps the configuration; a record saved before the+ field existed describes as AWS_OWNED_KEY, and so do its versions.+ AWS: captured 2026-10-20 (sfn-encryption-configuration C1, C2 for the+ described values)."""+ from ministack.core.responses import (+ get_account_id,+ get_region,+ set_request_account_id,+ set_request_region,+ )+ from ministack.services import stepfunctions as m++ original_account, original_region = get_account_id(), get_region()+ saved = m.get_state()+ try:+ set_request_account_id("000000000000")+ set_request_region("us-east-1")+ m.reset()+ status, _, body = m._create_state_machine({+ "name": "enc-persist", "definition": _ENC_DEFINITION, "roleArn": _ENC_ROLE,+ "encryptionConfiguration": _cmk(enc_key)})+ assert status == 200+ cmk_arn = json.loads(body)["stateMachineArn"]+ status, _, body = m._create_state_machine({+ "name": "enc-legacy", "definition": _ENC_DEFINITION, "roleArn": _ENC_ROLE,+ "publish": True})+ assert status == 200+ legacy_arn = json.loads(body)["stateMachineArn"]++ state = m.get_state()+ scope = ("000000000000", "us-east-1")+ del state["state_machines"].get_scoped(*scope, legacy_arn)["encryptionConfiguration"]+ del state["state_machine_versions"].get_scoped(+ *scope, f"{legacy_arn}:1")["encryptionConfiguration"]+ m.reset()+ m.load_persisted_state(state)++ def described(arn):+ return json.loads(m._describe_state_machine({"stateMachineArn": arn})[2])++ assert described(cmk_arn)["encryptionConfiguration"] == _cmk(enc_key)+ assert described(legacy_arn)["encryptionConfiguration"] == _ENC_DEFAULT+ assert described(f"{legacy_arn}:1")["encryptionConfiguration"] == _ENC_DEFAULT+ finally:+ m.reset()+ m.load_persisted_state(saved)+ set_request_account_id(original_account)+ set_request_region(original_region)+++# --- Captured 2026-10-20, captures/2308-pr-uncertainties.json -------------------------------++[email protected]("period,stored", [(60, 60), (900, 900), (300.5, 300), (300.0, 300),+ (60.5, 60), (900.5, 900)],+ ids=["60", "900", "float", "integral-float", "60.5", "900.5"])+def test_sfn_encryption_period_bounds_and_numbers(sfn, enc_key, period, stored):+ """AWS: U4:period-60, U4:period-900, U3:period-float, U3:period-float-integral,+ and 2308-pr-uncertainties-2 U26:period-60.5, U26:period-900.5."""+ name = _enc_name("enc-period")+ status, body = _sfn_raw("CreateStateMachine", {+ "name": name, "definition": _ENC_DEFINITION, "roleArn": _ENC_ROLE,+ "encryptionConfiguration": {"type": _CMK, "kmsKeyId": enc_key,+ "kmsDataKeyReusePeriodSeconds": period}})+ assert status == 200, body+ try:+ assert sfn.describe_state_machine(stateMachineArn=_sm_arn(name))["encryptionConfiguration"] == \+ _cmk(enc_key, stored)+ finally:+ sfn.delete_state_machine(stateMachineArn=_sm_arn(name))+++def test_sfn_encryption_null_type_joins_other_constraint_errors(sfn):+ """AWS: U5:null-type-empty-key-period59."""+ name = _enc_name("enc-multi-null")+ with pytest.raises(ClientError) as exc:+ _sfn_unvalidated().create_state_machine(+ name=name, definition=_ENC_DEFINITION, roleArn=_ENC_ROLE,+ encryptionConfiguration={"kmsKeyId": "", "kmsDataKeyReusePeriodSeconds": 59})+ _assert_sfn_error(exc, "ValidationException", "3 validation errors detected: "+ + "; ".join([_period_min(59), _KEY_EMPTY, _TYPE_NULL]))+ assert not _sfn_exists(sfn, _sm_arn(name))+++def test_sfn_aws_owned_key_with_key_and_period_reports_the_key(sfn, enc_key):+ """AWS: U6:owned-key-and-period."""+ name = _enc_name("enc-owned-both")+ with pytest.raises(ClientError) as exc:+ sfn.create_state_machine(name=name, definition=_ENC_DEFINITION, roleArn=_ENC_ROLE,+ encryptionConfiguration={"type": "AWS_OWNED_KEY", "kmsKeyId": enc_key,+ "kmsDataKeyReusePeriodSeconds": 300})+ _assert_sfn_error(exc, "InvalidEncryptionConfiguration",+ "Invalid Encryption Configuration: Custom kmsKeyId is not allowed when selecting "+ "AWS_OWNED_KEY.")+++def test_sfn_encryption_explicit_nulls(sfn):+ """AWS: U7:cmk-kmsKeyId-null, U7:owned-kmsKeyId-null."""+ name = _enc_name("enc-null-key")+ status, body = _sfn_raw("CreateStateMachine", {+ "name": name, "definition": _ENC_DEFINITION, "roleArn": _ENC_ROLE,+ "encryptionConfiguration": {"type": _CMK, "kmsKeyId": None}})+ assert status == 400+ assert body["__type"].rsplit("#", 1)[-1] == "InvalidEncryptionConfiguration"+ assert body["message"] == "Invalid Encryption Configuration: Must set a valid kmsKeyId."+ owned = _enc_name("enc-null-owned")+ status, body = _sfn_raw("CreateStateMachine", {+ "name": owned, "definition": _ENC_DEFINITION, "roleArn": _ENC_ROLE,+ "encryptionConfiguration": {"type": "AWS_OWNED_KEY", "kmsKeyId": None,+ "kmsDataKeyReusePeriodSeconds": None}})+ assert status == 200, body+ try:+ assert sfn.describe_state_machine(stateMachineArn=_sm_arn(owned))["encryptionConfiguration"] == \+ {"type": "AWS_OWNED_KEY"}+ finally:+ sfn.delete_state_machine(stateMachineArn=_sm_arn(owned))+++def test_sfn_encryption_unknown_member_is_ignored(sfn, enc_key):+ """AWS: U9:unknown-member."""+ name = _enc_name("enc-extra")+ status, body = _sfn_raw("CreateStateMachine", {+ "name": name, "definition": _ENC_DEFINITION, "roleArn": _ENC_ROLE,+ "encryptionConfiguration": {**_cmk(enc_key), "extra": "x"}})+ assert status == 200, body+ try:+ assert sfn.describe_state_machine(stateMachineArn=_sm_arn(name))["encryptionConfiguration"] == \+ _cmk(enc_key)+ finally:+ sfn.delete_state_machine(stateMachineArn=_sm_arn(name))+++def test_sfn_encryption_serialization_comes_first(sfn):+ """AWS: U10:serialization-vs-invalid-definition, U10:serialization-vs-missing-machine."""+ status, body = _sfn_raw("CreateStateMachine", {+ "name": _enc_name("enc-ser-first"), "definition": "this is not json", "roleArn": _ENC_ROLE,+ "encryptionConfiguration": "AWS_OWNED_KEY"})+ _assert_serialization_error(status, body, "Expected null")+ status, body = _sfn_raw("UpdateStateMachine", {+ "stateMachineArn": _sm_arn(_enc_name("enc-never")), "definition": _ENC_DEFINITION,+ "encryptionConfiguration": "AWS_OWNED_KEY"})+ _assert_serialization_error(status, body, "Expected null")+++def test_sfn_encryption_update_with_role_but_no_definition_is_refused(sfn, enc_key):+ """AWS: U12:update-encryption-and-roleArn-no-definition, U13:missing-definition-raw-body."""+ with _enc_machine(sfn, "enc-role-only", encryptionConfiguration=_cmk(enc_key)) as arn:+ with pytest.raises(ClientError) as exc:+ sfn.update_state_machine(stateMachineArn=arn, roleArn=_ENC_ROLE,+ encryptionConfiguration=_cmk(enc_key, 600))+ _assert_sfn_error(exc, "MissingRequiredParameter",+ "The definition must be specified when updating the EncryptionConfiguration")+ status, body = _sfn_raw("UpdateStateMachine", {+ "stateMachineArn": arn, "encryptionConfiguration": _cmk(enc_key, 600)})+ assert status == 400+ assert body["message"] == "The definition must be specified when updating the EncryptionConfiguration"+ assert sfn.describe_state_machine(stateMachineArn=arn)["encryptionConfiguration"] == _cmk(enc_key)+++def test_sfn_describe_for_execution_keeps_the_configuration_the_execution_started_with(sfn, enc_key):+ """AWS: U14:for-execution-base-after-update, U14:for-execution-version-after-update."""+ name = _enc_name("enc-exec-snap")+ created = sfn.create_state_machine(name=name, definition=_ENC_DEFINITION, roleArn=_ENC_ROLE,+ encryptionConfiguration=_cmk(enc_key), publish=True)+ try:+ on_base = sfn.start_execution(stateMachineArn=created["stateMachineArn"])["executionArn"]+ on_version = sfn.start_execution(stateMachineArn=created["stateMachineVersionArn"])["executionArn"]+ sfn.update_state_machine(stateMachineArn=created["stateMachineArn"], definition=_ENC_NEW_DEFINITION,+ encryptionConfiguration={"type": "AWS_OWNED_KEY"})+ for execution_arn in (on_base, on_version):+ described = sfn.describe_state_machine_for_execution(executionArn=execution_arn)+ assert described["encryptionConfiguration"] == _cmk(enc_key)+ finally:+ sfn.delete_state_machine(stateMachineArn=created["stateMachineArn"])+++def test_sfn_encryption_float_period_is_truncated_before_the_range_check(sfn, enc_key):+ """AWS: captured 2026-10-20 (2308-pr-uncertainties-2 U26:period-59.9)."""+ name = _enc_name("enc-period-trunc")+ status, body = _sfn_raw("CreateStateMachine", {+ "name": name, "definition": _ENC_DEFINITION, "roleArn": _ENC_ROLE,+ "encryptionConfiguration": {"type": _CMK, "kmsKeyId": enc_key, "kmsDataKeyReusePeriodSeconds": 59.9}})+ assert status == 400+ assert body["__type"].rsplit("#", 1)[-1] == "ValidationException"+ assert body["message"] == _one_error(_period_min(59))+ assert not _sfn_exists(sfn, _sm_arn(name))+++def test_sfn_describe_for_execution_through_an_alias_reports_the_version(sfn, enc_key):+ """AWS: captured 2026-10-20 (2308-pr-uncertainties-2 U25:for-execution-via-alias)."""+ name = _enc_name("enc-exec-alias")+ created = sfn.create_state_machine(name=name, definition=_ENC_DEFINITION, roleArn=_ENC_ROLE,+ encryptionConfiguration=_cmk(enc_key), publish=True)+ alias = sfn.create_state_machine_alias(name="live", routingConfiguration=[+ {"stateMachineVersionArn": created["stateMachineVersionArn"], "weight": 100}])["stateMachineAliasArn"]+ try:+ sfn.update_state_machine(stateMachineArn=created["stateMachineArn"], definition=_ENC_NEW_DEFINITION,+ encryptionConfiguration={"type": "AWS_OWNED_KEY"})+ execution_arn = sfn.start_execution(stateMachineArn=alias)["executionArn"]+ described = sfn.describe_state_machine_for_execution(executionArn=execution_arn)+ assert described["encryptionConfiguration"] == _cmk(enc_key)+ finally:+ sfn.delete_state_machine_alias(stateMachineAliasArn=alias)+ sfn.delete_state_machine(stateMachineArn=created["stateMachineArn"])+