Skip to content

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

feat(stepfunctions): add state machine alias API (#472)

W. H. Wang4aa34e996fc8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ad664b02..dfd47956 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Added
+- **Step Functions alias API** — `CreateStateMachineAlias`, `UpdateStateMachineAlias`, `DeleteStateMachineAlias`, `DescribeStateMachineAlias`, `ListStateMachineAliases`, plus `DescribeStateMachine` support for alias ARNs (`arn:…:stateMachine:<name>:<aliasName>`). Aliases let callers address a state machine by a stable pointer whose `routingConfiguration` distributes invocations across one or two versions by weight. Validation matches AWS: alias name regex `^[0-9A-Za-z_-]+$` length 1-80, routing 1-2 entries with int `weight` in `[0, 100]` summing to 100, no duplicate version ARNs, every referenced version must exist on the same state machine. `DeleteStateMachineVersion` now scans for alias references and raises `ConflictException` when an alias still routes to the version — the alias-awareness cross-check deferred from the versioning PR. Same terraform-provider-aws v6 motivation — the provider unconditionally calls `ListStateMachineAliases` on every `aws_sfn_state_machine` refresh, so without this any `terraform plan` returned `InvalidAction`.
- **Step Functions versioning API** — `PublishStateMachineVersion`, `DeleteStateMachineVersion`, `ListStateMachineVersions`, plus `DescribeStateMachine` support for qualified version ARNs (`arn:…:stateMachine:<name>:<N>`) returning the snapshot captured at publish time. `CreateStateMachine` now accepts the `publish=True` parameter, returning `stateMachineVersionArn` for the auto-published v1 in the same call. AWS-style optimistic concurrency via `revisionId`: every Create/Update rotates the state machine's `revisionId`, and `PublishStateMachineVersion`'s optional `revisionId` is treated as a precondition — supplying a stale value raises `ConflictException`. Version numbers are monotonic per state machine and never reused after delete (a `lastVersionNumber` high-water mark on the base state machine enforces this, matching AWS's documented behaviour). Without these actions, terraform-provider-aws v6 fails on every `aws_sfn_state_machine` refresh because it unconditionally calls `ListStateMachineVersions` regardless of whether versioning was opted into.
- **CloudWatch Logs Delivery API** — `PutDeliverySource` / `GetDeliverySource` / `DeleteDeliverySource` / `DescribeDeliverySources`, `PutDeliveryDestination` / `GetDeliveryDestination` / `DeleteDeliveryDestination` / `DescribeDeliveryDestinations`, and `CreateDelivery` / `GetDelivery` / `DeleteDelivery` / `DescribeDeliveries` (12 actions total). This is the 2023-era replacement for subscription filters that vended-logs producers (Bedrock, AppSync, CodeWhisperer, …) use to ship logs into S3, CloudWatch Logs, or Firehose. Server-derived fields match AWS's contract: `service` is computed from a delivery source's `resourceArn` (e.g. `arn:aws:bedrock:…` → `bedrock`) and `deliveryDestinationType` from a destination's `destinationResourceArn` (`s3` → `S3`, `logs` → `CWL`, `firehose` → `FH`); callers cannot override either. `outputFormat` is validated against the AWS enum (`json` / `plain` / `w3c` / `raw` / `parquet`). `CreateDelivery` requires the `deliveryDestinationArn` to resolve to an already-registered destination (instead of silently defaulting to `CWL`) and rejects duplicate `(deliverySourceName, deliveryDestinationArn)` pairs with `ConflictException`, matching AWS's one-Delivery-per-pair contract.
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index e002fca2..6a704c1c 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -12,7 +12,10 @@ Supports: CreateStateMachine, DeleteStateMachine, DescribeStateMachine,
GetActivityTask,
TagResource, UntagResource, ListTagsForResource,
PublishStateMachineVersion, DeleteStateMachineVersion,
- ListStateMachineVersions.
+ ListStateMachineVersions,
+ CreateStateMachineAlias, UpdateStateMachineAlias,
+ DeleteStateMachineAlias, DescribeStateMachineAlias,
+ ListStateMachineAliases.
ASL state types: Pass, Task, Choice, Wait, Succeed, Fail, Parallel, Map.
Task states invoke Lambda functions via services.lambda_svc when available.
@@ -127,6 +130,12 @@ _activity_tasks = AccountScopedDict()
# Version ARN shape: arn:aws:states:<region>:<acct>:stateMachine:<name>:<N>
_state_machine_versions = AccountScopedDict()
+# alias_arn -> {stateMachineAliasArn, name, description,
+# routingConfiguration: [{stateMachineVersionArn, weight}],
+# creationDate, updateDate}
+# Alias ARN shape: arn:aws:states:<region>:<acct>:stateMachine:<name>:<aliasName>
+_state_machine_aliases = AccountScopedDict()
+
# ── Persistence ────────────────────────────────────────────
def get_state():
@@ -136,6 +145,7 @@ def get_state():
"tags": copy.deepcopy(_tags),
"activities": copy.deepcopy(_activities),
"state_machine_versions": copy.deepcopy(_state_machine_versions),
+ "state_machine_aliases": copy.deepcopy(_state_machine_aliases),
}
@@ -147,6 +157,7 @@ def restore_state(data):
_tags.update(data.get("tags", {}))
_activities.update(data.get("activities", {}))
_state_machine_versions.update(data.get("state_machine_versions", {}))
+ _state_machine_aliases.update(data.get("state_machine_aliases", {}))
# Executions that were RUNNING when the process died cannot resume —
# mark them FAILED, following the ECS precedent (tasks → STOPPED).
for exc in _executions.values():
@@ -259,6 +270,11 @@ async def handle_request(method, path, headers, body, query_params):
"PublishStateMachineVersion": _publish_state_machine_version,
"DeleteStateMachineVersion": _delete_state_machine_version,
"ListStateMachineVersions": _list_state_machine_versions,
+ "CreateStateMachineAlias": _create_state_machine_alias,
+ "UpdateStateMachineAlias": _update_state_machine_alias,
+ "DeleteStateMachineAlias": _delete_state_machine_alias,
+ "DescribeStateMachineAlias": _describe_state_machine_alias,
+ "ListStateMachineAliases": _list_state_machine_aliases,
}
handler = handlers.get(action)
@@ -376,6 +392,26 @@ def _describe_state_machine(data):
or base_sm.get("loggingConfiguration", {"level": "OFF"}),
"revisionId": version.get("stateMachineRevisionId", ""),
})
+ # DescribeStateMachine on an alias ARN: AWS accepts it and returns
+ # state-machine-shaped fields (definition/roleArn/...) resolved from
+ # the base state machine; per AWS's response shape for this API,
+ # routingConfiguration is NOT one of the returned fields (callers
+ # who want routing should use DescribeStateMachineAlias).
+ alias = _state_machine_aliases.get(arn) if arn else None
+ if alias:
+ base_sm = _state_machines.get(_state_machine_arn_from_alias_arn(arn)) or {}
+ return json_response({
+ "stateMachineArn": alias["stateMachineAliasArn"],
+ "name": base_sm.get("name", ""),
+ "definition": base_sm.get("definition", "{}"),
+ "roleArn": base_sm.get("roleArn", ""),
+ "type": base_sm.get("type", "STANDARD"),
+ "creationDate": alias.get("creationDate"),
+ "status": "ACTIVE",
+ "description": alias.get("description", ""),
+ "loggingConfiguration": base_sm.get("loggingConfiguration", {"level": "OFF"}),
+ "revisionId": base_sm.get("revisionId", ""),
+ })
return error_response_json(
"StateMachineDoesNotExist",
f"State machine {arn} not found", 400)
@@ -2890,6 +2926,7 @@ def reset():
_activities.clear()
_activity_tasks.clear()
_state_machine_versions.clear()
+ _state_machine_aliases.clear()
# ---------------------------------------------------------------------------
@@ -2963,6 +3000,19 @@ def _delete_state_machine_version(data):
# AWS semantics: DeleteStateMachineVersion on a nonexistent version
# is a no-op (200 OK), matching other idempotent delete APIs.
return json_response({})
+ # AWS rejects DeleteStateMachineVersion while any alias still routes
+ # to the version (ConflictException). Iterate aliases defensively —
+ # _state_machine_aliases is declared by the alias module, so if
+ # aliases haven't been imported/used, nothing to check.
+ for alias_arn, alias in _state_machine_aliases.items():
+ for entry in alias.get("routingConfiguration", []):
+ if entry.get("stateMachineVersionArn") == version_arn:
+ return error_response_json(
+ "ConflictException",
+ f"Version {version_arn} cannot be deleted while referenced "
+ f"by alias {alias_arn} (routingConfiguration).",
+ 400,
+ )
del _state_machine_versions[version_arn]
return json_response({})
@@ -2989,3 +3039,202 @@ def _list_state_machine_versions(data):
return json_response({
"stateMachineVersions": matching[:max_results],
})
+
+
+# ---------------------------------------------------------------------------
+# State machine alias CRUD (routes traffic across multiple versions)
+# ---------------------------------------------------------------------------
+
+def _validate_routing_config(routing, state_machine_arn):
+ """AWS routing rules: 1-2 entries, weights in [0,100] summing to 100,
+ no duplicate version entries, and every referenced version ARN must
+ belong to the same state machine and exist."""
+ if not isinstance(routing, list) or not (1 <= len(routing) <= 2):
+ return error_response_json(
+ "ValidationException",
+ "routingConfiguration must have 1 or 2 entries.", 400)
+ total = 0
+ seen_version_arns = set()
+ for entry in routing:
+ weight = entry.get("weight")
+ version_arn = entry.get("stateMachineVersionArn")
+ if weight is None or not isinstance(weight, int) or not (0 <= weight <= 100):
+ return error_response_json(
+ "ValidationException",
+ "routingConfiguration.weight must be an integer in [0, 100].", 400)
+ if not version_arn:
+ return error_response_json(
+ "ValidationException",
+ "routingConfiguration.stateMachineVersionArn is required.", 400)
+ if not version_arn.startswith(f"{state_machine_arn}:"):
+ return error_response_json(
+ "ValidationException",
+ "routingConfiguration version ARN must belong to the same state machine.", 400)
+ if version_arn not in _state_machine_versions:
+ return error_response_json(
+ "ResourceNotFound",
+ f"Version not found: {version_arn}", 400)
+ if version_arn in seen_version_arns:
+ return error_response_json(
+ "ValidationException",
+ "routingConfiguration cannot contain duplicate version entries.", 400)
+ seen_version_arns.add(version_arn)
+ total += weight
+ if total != 100:
+ return error_response_json(
+ "ValidationException",
+ f"routingConfiguration weights must sum to 100 (got {total}).", 400)
+ return None
+
+
+# Alias names must match AWS's documented regex: alphanumerics,
+# underscore, and hyphen only; 1-80 characters.
+_ALIAS_NAME_RE = re.compile(r"^[0-9A-Za-z_\-]+$")
+
+
+def _validate_alias_name(name):
+ """Return an error response if the alias name is malformed per AWS rules,
+ else None."""
+ if not isinstance(name, str) or not (1 <= len(name) <= 80):
+ return error_response_json(
+ "ValidationException",
+ "Alias name must be 1-80 characters.", 400)
+ if not _ALIAS_NAME_RE.match(name):
+ return error_response_json(
+ "ValidationException",
+ "Alias name must match pattern ^[0-9A-Za-z_-]+$.", 400)
+ return None
+
+
+def _state_machine_arn_from_alias_arn(alias_arn):
+ return alias_arn.rsplit(":", 1)[0]
+
+
+def _create_state_machine_alias(data):
+ name = data.get("name")
+ if not name:
+ return error_response_json("ValidationException", "name is required.", 400)
+ name_err = _validate_alias_name(name)
+ if name_err:
+ return name_err
+ routing = data.get("routingConfiguration")
+ if not routing:
+ return error_response_json(
+ "ValidationException",
+ "routingConfiguration is required.", 400)
+ # Reject malformed shapes (dict, scalar, etc.) before any indexing.
+ # AWS rejects these with ValidationException; without this, a caller
+ # who sends a dict (e.g. accidentally unwrapped) would hit a Python
+ # TypeError on routing[0] and surface a 500 instead.
+ if not isinstance(routing, list):
+ return error_response_json(
+ "ValidationException",
+ "routingConfiguration must be a list.", 400)
+ if not routing or not isinstance(routing[0], dict):
+ return error_response_json(
+ "ValidationException",
+ "routingConfiguration must contain at least one entry shaped "
+ "{stateMachineVersionArn, weight}.", 400)
+ # All routing entries must reference the same state machine. Derive
+ # the state-machine ARN from the first entry and validate.
+ first_version_arn = routing[0].get("stateMachineVersionArn")
+ if not first_version_arn:
+ return error_response_json(
+ "ValidationException",
+ "routingConfiguration.stateMachineVersionArn is required.", 400)
+ state_machine_arn = first_version_arn.rsplit(":", 1)[0]
+ if state_machine_arn not in _state_machines:
+ return error_response_json(
+ "StateMachineDoesNotExist",
+ f"State machine {state_machine_arn} not found", 400)
+
+ err = _validate_routing_config(routing, state_machine_arn)
+ if err:
+ return err
+
+ alias_arn = f"{state_machine_arn}:{name}"
+ if alias_arn in _state_machine_aliases:
+ return error_response_json(
+ "ConflictException",
+ f"Alias {name} already exists.", 400)
+
+ ts = now_iso()
+ _state_machine_aliases[alias_arn] = {
+ "stateMachineAliasArn": alias_arn,
+ "name": name,
+ "description": data.get("description", ""),
+ "routingConfiguration": [dict(r) for r in routing],
+ "creationDate": ts,
+ "updateDate": ts,
+ }
+ return json_response({
+ "stateMachineAliasArn": alias_arn,
+ "creationDate": ts,
+ })
+
+
+def _update_state_machine_alias(data):
+ alias_arn = data.get("stateMachineAliasArn")
+ alias = _state_machine_aliases.get(alias_arn)
+ if not alias:
+ return error_response_json(
+ "ResourceNotFound",
+ f"Alias {alias_arn} not found", 400)
+ if "description" in data:
+ alias["description"] = data["description"]
+ if "routingConfiguration" in data:
+ state_machine_arn = _state_machine_arn_from_alias_arn(alias_arn)
+ err = _validate_routing_config(data["routingConfiguration"], state_machine_arn)
+ if err:
+ return err
+ alias["routingConfiguration"] = [dict(r) for r in data["routingConfiguration"]]
+ ts = now_iso()
+ alias["updateDate"] = ts
+ return json_response({"updateDate": ts})
+
+
+def _delete_state_machine_alias(data):
+ alias_arn = data.get("stateMachineAliasArn")
+ # Match AWS semantics: delete is idempotent (no 404 on missing alias).
+ _state_machine_aliases.pop(alias_arn, None)
+ return json_response({})
+
+
+def _describe_state_machine_alias(data):
+ alias_arn = data.get("stateMachineAliasArn")
+ alias = _state_machine_aliases.get(alias_arn)
+ if not alias:
+ return error_response_json(
+ "ResourceNotFound",
+ f"Alias {alias_arn} not found", 400)
+ return json_response({
+ "stateMachineAliasArn": alias["stateMachineAliasArn"],
+ "name": alias["name"],
+ "description": alias.get("description", ""),
+ "routingConfiguration": [dict(r) for r in alias.get("routingConfiguration", [])],
+ "creationDate": alias["creationDate"],
+ "updateDate": alias.get("updateDate", alias["creationDate"]),
+ })
+
+
+def _list_state_machine_aliases(data):
+ state_machine_arn = data.get("stateMachineArn")
+ if state_machine_arn not in _state_machines:
+ return error_response_json(
+ "StateMachineDoesNotExist",
+ f"State machine {state_machine_arn} not found", 400)
+
+ matching = []
+ for alias_arn, alias in _state_machine_aliases.items():
+ if _state_machine_arn_from_alias_arn(alias_arn) != state_machine_arn:
+ continue
+ matching.append({
+ "stateMachineAliasArn": alias_arn,
+ "creationDate": alias["creationDate"],
+ })
+ matching.sort(key=lambda a: a["creationDate"], reverse=True)
+
+ max_results = data.get("maxResults") or len(matching)
+ return json_response({
+ "stateMachineAliases": matching[:max_results],
+ })
diff --git a/tests/test_sfn.py b/tests/test_sfn.py
index 3feaa2b3..6f8df4d5 100644
--- a/tests/test_sfn.py
+++ b/tests/test_sfn.py
@@ -2941,3 +2941,259 @@ def test_sfn_publish_state_machine_version_numbers_never_reused(sfn):
assert v5["stateMachineVersionArn"] == f"{sm_arn}:5"
finally:
sfn.delete_state_machine(stateMachineArn=sm_arn)
+
+
+# ---------------------------------------------------------------------------
+# Step Functions aliasing (Create/Describe/Update/Delete/List)
+# ---------------------------------------------------------------------------
+
+def test_sfn_state_machine_alias_single_version(sfn):
+ """Create an alias pointing 100% at one version, then update to two.
+
+ Without this family any AWS SDK call to ``ListStateMachineAliases``
+ returns ``InvalidAction: Unknown action``. (terraform only)
+ terraform-provider-aws 6.x calls this action unconditionally on
+ every ``aws_sfn_state_machine`` refresh, so the missing action also
+ broke ``terraform plan`` for any aws_sfn_state_machine resource.
+ """
+ uid = _uuid_mod.uuid4().hex[:8]
+ name = f"alias-test-{uid}"
+ sm = sfn.create_state_machine(
+ name=name,
+ definition=json.dumps({
+ "StartAt": "P",
+ "States": {"P": {"Type": "Pass", "End": True}},
+ }),
+ roleArn="arn:aws:iam::000000000000:role/r",
+ )
+ sm_arn = sm["stateMachineArn"]
+
+ try:
+ v1 = sfn.publish_state_machine_version(stateMachineArn=sm_arn)
+ v2 = sfn.publish_state_machine_version(stateMachineArn=sm_arn)
+
+ # Empty initial list.
+ listed = sfn.list_state_machine_aliases(stateMachineArn=sm_arn)
+ assert listed["stateMachineAliases"] == []
+
+ create = sfn.create_state_machine_alias(
+ name="stable",
+ description="Points 100% at v1",
+ routingConfiguration=[
+ {"stateMachineVersionArn": v1["stateMachineVersionArn"], "weight": 100},
+ ],
+ )
+ alias_arn = create["stateMachineAliasArn"]
+ assert alias_arn == f"{sm_arn}:stable"
+
+ described = sfn.describe_state_machine_alias(stateMachineAliasArn=alias_arn)
+ assert described["name"] == "stable"
+ assert described["routingConfiguration"] == [
+ {"stateMachineVersionArn": v1["stateMachineVersionArn"], "weight": 100},
+ ]
+
+ # Update to weighted two-version routing.
+ sfn.update_state_machine_alias(
+ stateMachineAliasArn=alias_arn,
+ routingConfiguration=[
+ {"stateMachineVersionArn": v1["stateMachineVersionArn"], "weight": 30},
+ {"stateMachineVersionArn": v2["stateMachineVersionArn"], "weight": 70},
+ ],
+ )
+ updated = sfn.describe_state_machine_alias(stateMachineAliasArn=alias_arn)
+ weights = {r["stateMachineVersionArn"]: r["weight"]
+ for r in updated["routingConfiguration"]}
+ assert weights[v1["stateMachineVersionArn"]] == 30
+ assert weights[v2["stateMachineVersionArn"]] == 70
+
+ listed = sfn.list_state_machine_aliases(stateMachineArn=sm_arn)
+ assert [a["stateMachineAliasArn"] for a in listed["stateMachineAliases"]] == [alias_arn]
+
+ sfn.delete_state_machine_alias(stateMachineAliasArn=alias_arn)
+ # Idempotent delete.
+ sfn.delete_state_machine_alias(stateMachineAliasArn=alias_arn)
+ finally:
+ sfn.delete_state_machine(stateMachineArn=sm_arn)
+
+
+def test_sfn_alias_rejects_weights_not_summing_to_100(sfn):
+ """Alias creation requires routing weights sum to 100."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ name = f"alias-weight-{uid}"
+ sm = sfn.create_state_machine(
+ name=name,
+ definition=json.dumps({"StartAt": "P", "States": {"P": {"Type": "Pass", "End": True}}}),
+ roleArn="arn:aws:iam::000000000000:role/r",
+ )
+ sm_arn = sm["stateMachineArn"]
+ try:
+ v1 = sfn.publish_state_machine_version(stateMachineArn=sm_arn)
+ with pytest.raises(ClientError) as exc:
+ sfn.create_state_machine_alias(
+ name="bad-weights",
+ routingConfiguration=[
+ {"stateMachineVersionArn": v1["stateMachineVersionArn"], "weight": 50},
+ ],
+ )
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+ finally:
+ sfn.delete_state_machine(stateMachineArn=sm_arn)
+
+
+def test_sfn_alias_rejects_invalid_name(sfn):
+ """Alias names must match AWS regex [0-9A-Za-z_-]+ within 1-80 chars."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ sm = sfn.create_state_machine(
+ name=f"alias-bad-name-{uid}",
+ definition=json.dumps({"StartAt": "P", "States": {"P": {"Type": "Pass", "End": True}}}),
+ roleArn="arn:aws:iam::000000000000:role/r",
+ )
+ sm_arn = sm["stateMachineArn"]
+ try:
+ v1 = sfn.publish_state_machine_version(stateMachineArn=sm_arn)
+ routing = [{"stateMachineVersionArn": v1["stateMachineVersionArn"], "weight": 100}]
+ # Space is not in the allowed pattern.
+ with pytest.raises(ClientError) as exc:
+ sfn.create_state_machine_alias(name="bad name", routingConfiguration=routing)
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+ # Empty is rejected by length guard (and botocore typically blocks
+ # the call client-side — but if it slips through our server
+ # enforces). Skipping the empty-name test because boto3 rejects
+ # ParamValidationError before reaching the wire.
+ # Length > 80 is rejected.
+ with pytest.raises(ClientError) as exc:
+ sfn.create_state_machine_alias(name="a" * 81, routingConfiguration=routing)
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+ finally:
+ sfn.delete_state_machine(stateMachineArn=sm_arn)
+
+
+def test_sfn_alias_rejects_duplicate_version_entries(sfn):
+ """routingConfiguration must not contain the same version ARN twice."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ sm = sfn.create_state_machine(
+ name=f"alias-dup-{uid}",
+ definition=json.dumps({"StartAt": "P", "States": {"P": {"Type": "Pass", "End": True}}}),
+ roleArn="arn:aws:iam::000000000000:role/r",
+ )
+ sm_arn = sm["stateMachineArn"]
+ try:
+ v1 = sfn.publish_state_machine_version(stateMachineArn=sm_arn)
+ with pytest.raises(ClientError) as exc:
+ sfn.create_state_machine_alias(
+ name="dup",
+ routingConfiguration=[
+ {"stateMachineVersionArn": v1["stateMachineVersionArn"], "weight": 50},
+ {"stateMachineVersionArn": v1["stateMachineVersionArn"], "weight": 50},
+ ],
+ )
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+ finally:
+ sfn.delete_state_machine(stateMachineArn=sm_arn)
+
+
+def test_sfn_describe_state_machine_on_alias_arn(sfn):
+ """DescribeStateMachine(alias_arn) returns the alias's routing plus
+ the base state machine's definition/roleArn."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ sm = sfn.create_state_machine(
+ name=f"desc-alias-{uid}",
+ definition=json.dumps({"StartAt": "P", "States": {"P": {"Type": "Pass", "End": True}}}),
+ roleArn="arn:aws:iam::000000000000:role/r",
+ )
+ sm_arn = sm["stateMachineArn"]
+ try:
+ v1 = sfn.publish_state_machine_version(stateMachineArn=sm_arn)
+ alias = sfn.create_state_machine_alias(
+ name="live",
+ description="100% v1 for now",
+ routingConfiguration=[
+ {"stateMachineVersionArn": v1["stateMachineVersionArn"], "weight": 100},
+ ],
+ )
+ alias_arn = alias["stateMachineAliasArn"]
+
+ described = sfn.describe_state_machine(stateMachineArn=alias_arn)
+ assert described["stateMachineArn"] == alias_arn
+ assert described["description"] == "100% v1 for now"
+ # Non-routing fields fall back to the base state machine.
+ assert described["definition"] == json.dumps(
+ {"StartAt": "P", "States": {"P": {"Type": "Pass", "End": True}}}
+ )
+ assert described["roleArn"] == "arn:aws:iam::000000000000:role/r"
+ # routingConfiguration is NOT part of DescribeStateMachine's response
+ # shape — AWS doesn't carry it, boto3 strips unknown fields. Callers
+ # who need routing data call DescribeStateMachineAlias instead.
+ assert "routingConfiguration" not in described
+ finally:
+ sfn.delete_state_machine_alias(stateMachineAliasArn=f"{sm_arn}:live")
+ sfn.delete_state_machine(stateMachineArn=sm_arn)
+
+
+def test_sfn_delete_state_machine_version_blocked_by_alias(sfn):
+ """DeleteStateMachineVersion raises ConflictException while an alias
+ still routes to that version."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ sm = sfn.create_state_machine(
+ name=f"del-blocked-{uid}",
+ definition=json.dumps({"StartAt": "P", "States": {"P": {"Type": "Pass", "End": True}}}),
+ roleArn="arn:aws:iam::000000000000:role/r",
+ )
+ sm_arn = sm["stateMachineArn"]
+ try:
+ v1 = sfn.publish_state_machine_version(stateMachineArn=sm_arn)
+ alias = sfn.create_state_machine_alias(
+ name="pin",
+ routingConfiguration=[
+ {"stateMachineVersionArn": v1["stateMachineVersionArn"], "weight": 100},
+ ],
+ )
+ alias_arn = alias["stateMachineAliasArn"]
+
+ # Blocked while alias still references v1.
+ with pytest.raises(ClientError) as exc:
+ sfn.delete_state_machine_version(
+ stateMachineVersionArn=v1["stateMachineVersionArn"],
+ )
+ assert exc.value.response["Error"]["Code"] == "ConflictException"
+
+ # Unblocks once alias removed.
+ sfn.delete_state_machine_alias(stateMachineAliasArn=alias_arn)
+ sfn.delete_state_machine_version(
+ stateMachineVersionArn=v1["stateMachineVersionArn"],
+ ) # no-raise
+ finally:
+ sfn.delete_state_machine(stateMachineArn=sm_arn)
+
+
+def test_sfn_create_alias_rejects_malformed_routing_config(sfn):
+ """A non-list routingConfiguration must surface as ValidationException
+ rather than crashing on routing[0] indexing."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ sm = sfn.create_state_machine(
+ name=f"alias-malformed-{uid}",
+ definition=json.dumps({"StartAt": "P", "States": {"P": {"Type": "Pass", "End": True}}}),
+ roleArn="arn:aws:iam::000000000000:role/r",
+ )
+ sm_arn = sm["stateMachineArn"]
+ try:
+ # boto3 client-side may reject malformed shapes before hitting
+ # the wire (it knows the SDK model). Test by hand-rolling the
+ # request via boto3's low-level invoke.
+ # Simpler: pass a list whose first entry isn't a dict.
+ with pytest.raises((ClientError, Exception)) as exc_info:
+ # Some shapes get caught by boto3 ParamValidationError; we
+ # accept either ClientError or ParamValidationError as proof
+ # that the request didn't reach our server crashed.
+ sfn.create_state_machine_alias(
+ name="bad",
+ routingConfiguration=[
+ {"weight": 100}, # missing stateMachineVersionArn
+ ],
+ )
+ # If it was a ClientError, confirm code; if ParamValidationError,
+ # boto3 caught it client-side which is also acceptable.
+ if isinstance(exc_info.value, ClientError):
+ assert exc_info.value.response["Error"]["Code"] == "ValidationException"
+ finally:
+ sfn.delete_state_machine(stateMachineArn=sm_arn)