Skip to content

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

fix(elbv2): store, return and validate listener rule transforms (#2346)

Kacper Harabaszde1e4cd7ab32
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 61ac6453..d3a318c3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,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.
+- **ELBv2 — listener rule transforms** — `CreateRule` and `ModifyRule` dropped `Transforms`, so Terraform re-planned every `aws_lb_listener_rule` with a `transform` block; `url-rewrite` and `host-header-rewrite` transforms are now stored and returned by `DescribeRules` (an empty list for a rule without any), replaced by `ModifyRule` and cleared by `ResetTransforms`, and `AWS::ElasticLoadBalancingV2::ListenerRule` creates, updates and removes them. Invalid transforms are refused with AWS's messages and check order, as captured against AWS: the request-model errors first, then a missing load balancer, one transform per type, the type's config, one rewrite, the `Replace` and `Regex` lengths and characters, and the `Regex` syntax, all before a missing listener or rule. `ModifyRule` refuses `Transforms` with `ResetTransforms`, a call with nothing to change, and any change to a default rule (`OperationNotPermitted`). CloudFormation checks `Transforms` against the resource schema before provisioning and reports the handler's reason for the rest. The data plane does not apply transforms: requests reach targets with their original path, query string and Host header. Contributed by @kharabasz.
- **S3 — replication rule options are kept and checked** — `PutBucketReplication` dropped `SourceSelectionCriteria` from each rule and `EncryptionConfiguration`, `ReplicationTime` and `Metrics` from its destination, so Terraform's `aws_s3_bucket_replication_configuration` planned a change on every run; `GetBucketReplication` now returns them as put, with `Minutes` as an integer. A put AWS refuses is refused with AWS's code, message and `ArgumentName`, in AWS's order, and stores nothing: `MalformedXML` for a missing `Status`, `Time` or `Minutes`, an unknown or repeated element or a `Minutes` that is not a 32-bit integer, `InvalidArgument` for `Minutes` other than 15, a `ReplicaKmsKeyID` that is empty or not a KMS key or alias ARN, and an event threshold that doesn't fit the `ReplicationTime` status, and `InvalidRequest` for `ReplicationTime` without `Metrics`, `SseKmsEncryptedObjects` and `EncryptionConfiguration` without each other, an `EncryptionConfiguration` without `ReplicaKmsKeyID`, an empty `SourceSelectionCriteria`, a key in another partition or region than the destination bucket, and `ReplicationTime`, `Metrics` or `ReplicaModifications` in a rule that uses `Prefix` instead of `Filter`. The options are stored only; they don't change which objects are replicated. 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.
diff --git a/README.md b/README.md
index 60b72a84..79549fa5 100644
--- a/README.md
+++ b/README.md
@@ -440,7 +440,7 @@ subnet = ec2.create_subnet(
| **Step Functions** | CreateStateMachine, DeleteStateMachine, DescribeStateMachine, UpdateStateMachine, ListStateMachines, StartExecution, StartSyncExecution, StopExecution, DescribeExecution, DescribeStateMachineForExecution, ListExecutions, GetExecutionHistory, SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat, CreateActivity, DeleteActivity, DescribeActivity, ListActivities, GetActivityTask, TestState, TagResource, UntagResource, ListTagsForResource | Full ASL interpreter; Retry/Catch; waitForTaskToken; Activities (worker pattern); Pass/Task/Choice/Wait/Succeed/Fail/Map/Parallel; TestState API with mock and inspectionLevel support; SFN_MOCK_CONFIG for AWS SFN Local compatible mock testing; intrinsic functions (States.StringToJson, States.JsonToString, States.JsonMerge, States.Format); nested startExecution.sync |
| **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateRouteResponse, GetRouteResponse, GetRouteResponses, UpdateRouteResponse, DeleteRouteResponse, CreateIntegrationResponse, GetIntegrationResponse, GetIntegrationResponses, UpdateIntegrationResponse, DeleteIntegrationResponse, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateDomainName, GetDomainName, GetDomainNames, UpdateDomainName, DeleteDomainName, CreateApiMapping, GetApiMapping, GetApiMappings, UpdateApiMapping, DeleteApiMapping, TagResource, UntagResource, GetTags, PostToConnection, GetConnection, DeleteConnection | **HTTP API** and **WebSocket API** (`protocolType=WEBSOCKET`); Lambda proxy (`AWS_PROXY`), HTTP proxy (`HTTP_PROXY`), and MOCK integrations; HTTP data plane via `{apiId}.execute-api.localhost` Host header or path-based `/_aws/execute-api/{apiId}/{stage}/{path}` (no DNS/Host override needed — works from browsers on macOS and strict clients); `$default` stage served from the URL root (no stage segment in the path); per-API `corsConfiguration` applied to preflights + dispatched responses; request parameter mapping for HTTP_PROXY (`append/overwrite/remove` for headers/querystring plus `overwrite:path`) with context variables including `$context.authorizer.jwt.claims`; JWT data-plane authorization for HTTP routes (issuer/audience/time/scope checks) and claim propagation to integrations; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; WebSocket data plane on the same two URL forms, with `$connect` / `$disconnect` / `$default` / custom-action routing, `$request.body.*` RouteSelectionExpression, `@connections` management API (PostToConnection / GetConnection / DeleteConnection), per-connection outbox for server-side push; `{param}` / `{proxy+}` matching; custom domain names and API mappings shared with API Gateway v1, routed by `Host`; JWT/Lambda authorizer CRUD; pin `apiId` across runs with the `ms-custom-id` tag |
| **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateDocumentationPart, GetDocumentationPart, GetDocumentationParts, UpdateDocumentationPart, DeleteDocumentationPart, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags, CreateRequestValidator, GetRequestValidators, GetRequestValidator, UpdateRequestValidator, DeleteRequestValidator | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), non-proxy Lambda (AWS — the handler's output is the response body, Lambda request mapping templates not modeled) and non-proxy `AWS` integrations whose URI targets SQS (`arn:aws:apigateway:{region}:sqs:path/{account}/{queue}`: a request template subset — `$input.body` / `$input.json('…')` / `$input.params('…')` / `$util.urlEncode(…)`, `$context.authorizer` values including Cognito claims, `#set`, comments and interpolated strings — renders the form-encoded SQS Query call, run in the URI's account and region, and the backend result or error is mapped through `integrationResponses`), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost` Host header, path-based `/_aws/execute-api/{apiId}/{stage}/{path}`, or legacy `/restapis/{apiId}/{stage}/_user_request_/{path}`; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; resource tree with `{param}` and `{proxy+}` path matching; routing is on the resource+method pair, so a request the matched resource does not serve falls through to a `{proxy+}` elsewhere in the tree (a methodless intermediate, a CORS-preflight-only node, or any undeclared verb), as it does on AWS; TOKEN and REQUEST Lambda authorizers on the data plane, with the returned IAM policy evaluated against each request's own method ARN and `authorizerResultTtlInSeconds` caching the policy per stage and identity source; JSON Patch for all PATCH operations; state persistence; pin `id` across runs with the `ms-custom-id` tag |
-| **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, SetSubnets, SetIpAddressType, SetSecurityGroups, RegisterTargets, DeregisterTargets, DescribeTargetHealth, AddTags, RemoveTags, DescribeTags | Control plane + data plane; ALB→Lambda live traffic routing; `path-pattern`, `host-header`, `http-method`, `query-string`, `http-header` rule conditions; `forward`, `redirect`, `fixed-response`, `authenticate-oidc` actions; data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix |
+| **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, SetSubnets, SetIpAddressType, SetSecurityGroups, RegisterTargets, DeregisterTargets, DescribeTargetHealth, AddTags, RemoveTags, DescribeTags | Control plane + data plane; ALB→Lambda live traffic routing; `path-pattern`, `host-header`, `http-method`, `query-string`, `http-header` rule conditions; `forward`, `redirect`, `fixed-response`, `authenticate-oidc` actions; `url-rewrite` and `host-header-rewrite` rule transforms stored and returned (not applied to traffic); data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix |
| **KMS** | CreateKey, ReplicateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateMac, VerifyMac, GenerateDataKey, GenerateDataKeyWithoutPlaintext, GenerateDataKeyPair, GenerateDataKeyPairWithoutPlaintext, GenerateRandom, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, UpdateKeyDescription, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags, GetParametersForImport, ImportKeyMaterial, DeleteImportedKeyMaterial, CreateGrant, ListGrants, RevokeGrant, RetireGrant | 41 actions; multi-Region keys: `CreateKey` with `MultiRegion` mints an `mrk-` key and `ReplicateKey` creates a same-id replica in another region sharing the key material (ciphertext from the primary decrypts against the replica; a primary with live replicas waits in `PendingReplicaDeletion`); CMK specs: RSA (2048/3072/4096), ECC (SECG_P256K1, NIST P-256/384/521), Edwards25519 (`ECC_NIST_EDWARDS25519` — pure Ed25519 via `ED25519_SHA_512` with `MessageType=RAW`; `ED25519_PH_SHA_512` advertised in `SigningAlgorithms` but returns `UnsupportedOperationException` until Ed25519ph lands), HMAC (`HMAC_224`/`HMAC_256`/`HMAC_384`/`HMAC_512` with `KeyUsage=GENERATE_VERIFY_MAC`), and symmetric keys; PKCS1v15, PSS, and ECDSA signing; real RFC 2104 HMAC via `GenerateMac`/`VerifyMac` (4096-byte message cap, `KMSInvalidMacException` on mismatch, `DryRun` supported); envelope encryption, incl. asymmetric data key pairs (`KeyPairSpec` adds RSA_3072); alias resolution; key rotation; key policies; tags; enable/disable/schedule deletion; grants (stored and listed, not evaluated for authorization); full Terraform `aws_kms_key` compatible; `cryptography` package included in Docker image |
| **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, AssociateDistributionWebACL, DisassociateDistributionWebACL, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, CreateMonitoringSubscription, GetMonitoringSubscription, DeleteMonitoringSubscription, CreateFunction, DeleteFunction, DescribeFunction, GetFunction, ListFunctions, PublishFunction, UpdateFunction, **KeyValueStore (mgmt)**: CreateKeyValueStore, DescribeKeyValueStore, ListKeyValueStores, UpdateKeyValueStore, DeleteKeyValueStore, **Policies**: CreateCachePolicy, GetCachePolicy, GetCachePolicyConfig, UpdateCachePolicy, DeleteCachePolicy, ListDistributionsByCachePolicyId, CreateOriginRequestPolicy, GetOriginRequestPolicy, GetOriginRequestPolicyConfig, UpdateOriginRequestPolicy, DeleteOriginRequestPolicy, ListDistributionsByOriginRequestPolicyId, CreateResponseHeadersPolicy, GetResponseHeadersPolicy, GetResponseHeadersPolicyConfig, UpdateResponseHeadersPolicy, DeleteResponseHeadersPolicy, ListDistributionsByResponseHeadersPolicyId, **Public keys / key groups**: CreatePublicKey, GetPublicKey, GetPublicKeyConfig, UpdatePublicKey, DeletePublicKey, ListPublicKeys, CreateKeyGroup, GetKeyGroup, GetKeyGroupConfig, UpdateKeyGroup, DeleteKeyGroup, ListKeyGroups, **SaaS Manager**: CreateConnectionGroup, GetConnectionGroup, GetConnectionGroupByRoutingEndpoint, UpdateConnectionGroup, DeleteConnectionGroup, ListConnectionGroups, CreateDistributionTenant, GetDistributionTenant, GetDistributionTenantByDomain, UpdateDistributionTenant, DeleteDistributionTenant, ListDistributionTenants, ListDistributionTenantsByCustomization, AssociateDistributionTenantWebACL, DisassociateDistributionTenantWebACL, CreateInvalidationForDistributionTenant, GetInvalidationForDistributionTenant, ListInvalidationsForDistributionTenant, VerifyDnsConfiguration, GetManagedCertificateDetails, ListDomainConflicts, UpdateDomainAssociation, ListDistributionsByConnectionMode, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin config round-trip; cache / origin request / response headers policies round-trip their full config with `ETag` / `If-Match` optimistic concurrency; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; the AWS-managed cache (7), origin request (8) and response headers (5) policies are listed and immutable; `CreateMonitoringSubscription` upserts; functions keep DEVELOPMENT/LIVE stages and `KeyValueStoreAssociations`, and `UpdateFunction` clears LIVE until `PublishFunction` runs again; **data plane**: a request to a distribution's `DomainName` (`d` + 13 characters, or `<label>.cloudfront.<MINISTACK_HOST>`) is served through its cache behaviors, policies, `viewer-request` / `viewer-response` CloudFront Functions (on Node) and an S3 or custom origin (read only as the bucket policy allows: OAC, OAI or public), with custom error responses for origin errors; not modelled: caching, WAF, logging, geo restrictions, signed URLs, Lambda@Edge, CORS preflight, and origins at AWS hostnames (502); **SaaS Manager** multi-tenant distributions: `DistributionConfig` round-trips `ConnectionMode` / `TenantConfig`, tenants require a `tenant-only` distribution, CNAMEs are unique across tenants and distribution aliases, a tenant without an explicit connection group lazily gets the account default group, and MiniStack collapses async workflows (tenants deploy, domains activate, DNS verifies, managed certificates issue immediately); key groups validate `Items` against real public keys, and deleting either while still referenced (`PublicKeyInUse` / `ResourceInUse`) is rejected |
| **CloudFront KeyValueStore (data plane)** | DescribeKeyValueStore, ListKeys, GetKey, PutKey, DeleteKey, UpdateKeys | Separate `cloudfront-keyvaluestore` SDK service (REST/JSON, signing name `cloudfront-keyvaluestore`); ETag-based optimistic concurrency on every mutating op; `UpdateKeys` is atomic (validates whole batch, rejects on first invalid entry); `ListKeys` paginates with opaque `NextToken` capped at 50 results per AWS spec; bridges to the management plane via the shared KVS ARN |
diff --git a/ministack/services/alb.py b/ministack/services/alb.py
index 196d2a91..31b1bcad 100644
--- a/ministack/services/alb.py
+++ b/ministack/services/alb.py
@@ -31,6 +31,7 @@ import re
import socket
import string
import time
+import warnings
from urllib.parse import parse_qs, urlencode
from xml.sax.saxutils import escape as _esc
@@ -412,7 +413,7 @@ def _error(code, message, status=400):
body = (
f'<ErrorResponse xmlns="{NS}">'
f'<Error><Type>{"Sender" if status < 500 else "Receiver"}</Type>'
- f'<Code>{code}</Code><Message>{message}</Message></Error>'
+ f'<Code>{code}</Code><Message>{_esc(message, {chr(34): "&quot;"})}</Message></Error>'
f'<RequestId>{new_uuid()}</RequestId>'
f'</ErrorResponse>'
).encode("utf-8")
@@ -605,9 +606,211 @@ def _condition_xml(c):
return xml + "</member>"
-def _rule_xml(r):
+# Rule transforms, stored and returned in the RuleTransform shape. The data
+# plane does not apply them: requests reach targets unrewritten. Codes,
+# messages and check order are as captured against AWS in us-east-1.
+_TRANSFORM_CONFIG_KEYS = {
+ "url-rewrite": "UrlRewriteConfig",
+ "host-header-rewrite": "HostHeaderRewriteConfig",
+}
+_REWRITE_MAX_LEN = 1024
+# Members in the order AWS lists their "validation error detected" messages.
+_TRANSFORM_MODEL_CONFIGS = (("HostHeaderRewriteConfig", "hostHeaderRewriteConfig"),
+ ("UrlRewriteConfig", "urlRewriteConfig"))
+# Groups AWS refuses that Python's re accepts: lookarounds, atomic groups,
+# comments, conditionals and named backreferences.
+_REGEX_REFUSED_GROUPS = ("(?=", "(?!", "(?<=", "(?<!", "(?>", "(?#", "(?(", "(?P=", "(?|")
+
+
+def _parse_transforms(params, prefix="Transforms"):
+ """Read Transforms.member.N from Query params into
+ [{"Type", "UrlRewriteConfig"|"HostHeaderRewriteConfig": {"Rewrites": [{"Regex", "Replace"}]}}].
+ Returns None when the request carries no Transforms, and [] for an empty
+ list (a blank ``Transforms=``). An absent Type, Regex or Replace is None,
+ and a config is present when any of its keys is, even a blank ``Rewrites=``."""
+ members = {}
+ head = re.compile(rf"^{re.escape(prefix)}\.member\.(\d+)\.(.+)$")
+ for key in params:
+ m = head.match(key)
+ if m:
+ members.setdefault(int(m.group(1)), {})[m.group(2)] = _p(params, key)
+ if not members:
+ return [] if prefix in params else None
+ transforms = []
+ for i in sorted(members):
+ fields = members[i]
+ transform = {"Type": fields.get("Type")}
+ for config in _TRANSFORM_CONFIG_KEYS.values():
+ rewrites = {}
+ # A rewrite member exists when any of its keys does, even one AWS ignores.
+ rw = re.compile(rf"^{config}\.Rewrites\.member\.(\d+)\.(.+)$")
+ for field, value in fields.items():
+ m = rw.match(field)
+ if m:
+ rewrites.setdefault(int(m.group(1)), {})[m.group(2)] = value
+ if rewrites or any(f.startswith(f"{config}.") for f in fields):
+ transform[config] = {"Rewrites": [
+ {"Regex": rewrites[j].get("Regex"), "Replace": rewrites[j].get("Replace")}
+ for j in sorted(rewrites)
+ ]}
+ transforms.append(transform)
+ return transforms
+
+
+def _transforms_model_error(transforms):
+ """The request-model check AWS runs before anything else: Type is set and
+ in the enum, and every rewrite has a Regex and a Replace. AWS lists at
+ most ten problems."""
+ errors = []
+ for i, transform in enumerate(transforms, 1):
+ member = f"transforms.{i}.member"
+ for config, path in _TRANSFORM_MODEL_CONFIGS:
+ for j, rewrite in enumerate((transform.get(config) or {}).get("Rewrites", []), 1):
+ for field in ("Regex", "Replace"):
+ if rewrite.get(field) is None:
+ errors.append(f"Value null at '{member}.{path}.rewrites.{j}.member.{field.lower()}' "
+ "failed to satisfy constraint: Member must not be null")
+ t_type = transform.get("Type")
+ if t_type is None:
+ errors.append(f"Value null at '{member}.type' failed to satisfy constraint: Member must not be null")
+ elif t_type not in _TRANSFORM_CONFIG_KEYS:
+ errors.append(f"Value '{t_type}' at '{member}.type' failed to satisfy constraint: "
+ "Member must satisfy enum value set: [url-rewrite, host-header-rewrite]")
+ if not errors:
+ return None
+ errors = errors[:10]
+ return (f"{len(errors)} validation error{'s' if len(errors) > 1 else ''} detected: "
+ + "; ".join(errors))
+
+
+def _regex_invalid(regex):
+ """Whether AWS refuses a rewrite Regex as invalid. Python's re checks the
+ syntax once the AWS spellings it lacks are rewritten: (?<name>...),
+ \\x{41}, \\z, (?R) and the inline flags i, m, s, x, u and U anywhere. AWS
+ refuses whitespace, backreferences, \\Z and a "{" that opens no {n} or
+ {n,m}, and accepts stacked quantifiers such as a** or a{2}{3}."""
+ if any(ch.isspace() for ch in regex):
+ return True
+ out, i, n, class_start = [], 0, len(regex), None
+ while i < n:
+ c = regex[i]
+ if c == "\\":
+ e = regex[i + 1:i + 2]
+ if not e or e in "0123456789kZ":
+ return True
+ m = re.match(r"\{([0-9A-Fa-f]{1,8})\}", regex[i + 2:]) if e == "x" else None
+ if m:
+ out.append(f"\\U{int(m.group(1), 16):08x}")
+ i += 2 + len(m.group(0))
+ continue
+ out.append("\\Z" if e == "z" and class_start is None else regex[i:i + 2])
+ i += 2
+ continue
+ if class_start is not None:
+ # A "]" right after "[" or "[^" is a literal; "[:alpha:]" is a POSIX class.
+ posix = re.match(r"\[:\^?[A-Za-z]*:\]", regex[i:]) if c == "[" else None
+ if posix:
+ out.append(posix.group(0))
+ i += len(posix.group(0))
+ continue
+ if c == "]" and i > class_start + 1 and not (i == class_start + 2 and regex[class_start + 1] == "^"):
+ class_start = None
+ out.append(c)
+ i += 1
+ continue
+ if c == "[":
+ class_start = i
+ elif regex.startswith(_REGEX_REFUSED_GROUPS, i):
+ return True
+ elif regex.startswith("(?R)", i):
+ i += 4
+ continue
+ elif regex.startswith("(?<", i):
+ out.append("(?P<")
+ i += 3
+ continue
+ elif c == "(" and (m := re.match(r"\(\?([a-zA-Z-]*)([:)])", regex[i:])):
+ # The flags AWS accepted; it refused Q, z, q, a, L, n, J and an empty (?).
+ if m.group(2) == ")" and not m.group(1) or set(m.group(1)) - set("imsxuU-"):
+ return True
+ out.append("(?:" if m.group(2) == ":" else "")
+ i += len(m.group(0))
+ continue
+ elif c == "{" and not re.match(r"\{\d+(?:,\d*)?\}", regex[i:]):
+ return True
+ out.append(c)
+ i += 1
+ if class_start is not None:
+ return True
+ # AWS accepts a quantifier stacked on another (a**, a{2}{3}); re refuses it,
+ # so drop each one re points at and look for any other error.
+ pattern = "".join(out)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ while True:
+ try:
+ re.compile(pattern)
+ return False
+ except re.error as exc:
+ if exc.msg != "multiple repeat" or exc.pos is None:
+ return True
+ stacked = re.match(r"\{\d+(?:,\d*)?\}|[*+?]", pattern[exc.pos:])
+ if not stacked:
+ return True
+ pattern = pattern[:exc.pos] + pattern[exc.pos + len(stacked.group(0)):]
+
+
+def _transforms_problem(transforms):
+ """Why AWS refuses a list of transforms that passed the model check, or None."""
+ types = [t["Type"] for t in transforms]
+ if len(set(types)) != len(types):
+ return "A rule can only have one transform of each type"
+ for transform in transforms:
+ t_type = transform["Type"]
+ config = _TRANSFORM_CONFIG_KEYS[t_type]
+ if config not in transform:
+ return f"For transforms of type '{t_type}', you must specify the following field(s): '{config}'"
+ other = [c for c in _TRANSFORM_CONFIG_KEYS.values() if c != config and c in transform]
+ if other:
+ return f"A transform of type '{t_type}' does not support the following field(s): '{other[0]}'"
+ rewrites = transform[config]["Rewrites"]
+ if len(rewrites) != 1:
+ return "Rule transforms must have exactly one Rewrite"
+ regex, replace = rewrites[0]["Regex"], rewrites[0]["Replace"]
+ if len(replace) > _REWRITE_MAX_LEN:
+ return "A transform rewrite Replace value must be between 0 and 1024 characters in length"
+ if not all("!" <= ch <= "~" for ch in replace):
+ return ("A transform rewrite Replace value may only consist of non-whitespace "
+ "printable ASCII characters")
+ if not regex or len(regex) > _REWRITE_MAX_LEN:
+ return "A transform rewrite Regex value must be between 1 and 1024 characters in length"
+ if not regex.isascii():
+ return ("Transform rewrite regex values can not be empty, and can only contain "
+ "non-whitespace ASCII 128 characters")
+ if _regex_invalid(regex):
+ return "One or more provided transform rewrite Regex values are invalid"
+ return None
+
+
+def _transform_xml(t):
+ inner = ""
+ for config in _TRANSFORM_CONFIG_KEYS.values():
+ if config in t:
+ rewrites = "".join(
+ f"<member><Regex>{_esc(r.get('Regex', ''))}</Regex>"
+ f"<Replace>{_esc(r.get('Replace', ''))}</Replace></member>"
+ for r in t[config].get("Rewrites", [])
+ )
+ inner += f"<{config}><Rewrites>{rewrites}</Rewrites></{config}>"
+ return f"<member>{inner}<Type>{_esc(t['Type'])}</Type></member>"
+
+
+def _rule_xml(r, with_transforms=True):
conds = "".join(_condition_xml(c) for c in r.get("Conditions", []))
acts = "".join(_action_xml(a) for a in r.get("Actions", []))
+ # SetRulePriorities' rules carry no Transforms element on AWS.
+ transforms = ("<Transforms>" + "".join(_transform_xml(t) for t in r.get("Transforms", []))
+ + "</Transforms>") if with_transforms else ""
return (
f"<member>"
f"<RuleArn>{r['RuleArn']}</RuleArn>"
@@ -615,6 +818,7 @@ def _rule_xml(r):
f"<Conditions>{conds}</Conditions>"
f"<Actions>{acts}</Actions>"
f"<IsDefault>{str(r.get('IsDefault',False)).lower()}</IsDefault>"
+ f"{transforms}"
f"</member>"
)
@@ -982,8 +1186,26 @@ def _modify_listener_attrs(params):
# Rule handlers
# ---------------------------------------------------------------------------
+def _load_balancer_missing(arn):
+ """Whether a listener or rule ARN names a load balancer that doesn't
+ exist. AWS answers ListenerNotFound or RuleNotFound for that right after
+ the model check; on a load balancer that exists, a missing listener or
+ rule is only reported after every other check."""
+ m = re.match(r"^(arn:[^:]+:elasticloadbalancing:[^:]*:[^:]*:)listener(?:-rule)?/([^/]+/[^/]+/[^/]+)/", arn)
+ return bool(m) and f"{m.group(1)}loadbalancer/{m.group(2)}" not in _lbs
+
+
def _create_rule(params):
l_arn = _p(params, "ListenerArn")
+ transforms = _parse_transforms(params) or []
+ problem = _transforms_model_error(transforms)
+ if problem:
+ return _error("ValidationError", problem)
+ if _load_balancer_missing(l_arn):
+ return _error("ListenerNotFound", f"Listener '{l_arn}' not found.")
+ problem = _transforms_problem(transforms)
+ if problem:
+ return _error("ValidationError", problem)
if l_arn not in _listeners:
return _error("ListenerNotFound", f"Listener '{l_arn}' not found.")
listener = _listeners[l_arn]
@@ -1000,6 +1222,7 @@ def _create_rule(params):
"Conditions": _parse_conditions(params),
"Actions": _parse_actions(params, "Actions"),
"IsDefault": False,
+ "Transforms": transforms,
}
_rules[rule_arn] = rule
_tags[rule_arn] = _parse_tags(params)
@@ -1019,15 +1242,36 @@ def _describe_rules(params):
def _modify_rule(params):
arn = _p(params, "RuleArn")
+ transforms = _parse_transforms(params)
+ reset_transforms = _p(params, "ResetTransforms").lower() == "true"
+ problem = _transforms_model_error(transforms or [])
+ if problem:
+ return _error("ValidationError", problem)
+ if _load_balancer_missing(arn):
+ return _error("RuleNotFound", f"Rule '{arn}' not found.")
+ # An empty Transforms list counts as given here, but changes nothing below.
+ if transforms is not None and reset_transforms:
+ return _error("ValidationError", "Transforms cannot be provided when resetting transforms")
+ problem = _transforms_problem(transforms or [])
+ if problem:
+ return _error("ValidationError", problem)
+ conds = _parse_conditions(params)
+ acts = _parse_actions(params, "Actions")
+ if not (conds or acts or transforms or reset_transforms):
+ return _error("ValidationError", "You must provide either conditions, actions, or transforms")
rule = _rules.get(arn)
if not rule:
return _error("RuleNotFound", f"Rule '{arn}' not found.")
- conds = _parse_conditions(params)
+ if rule.get("IsDefault"):
+ return _error("OperationNotPermitted", f"Default rule '{arn}' cannot be modified")
if conds:
rule["Conditions"] = conds
- acts = _parse_actions(params, "Actions")
if acts:
rule["Actions"] = acts
+ if transforms:
+ rule["Transforms"] = transforms
+ elif reset_transforms:
+ rule["Transforms"] = []
return _xml(200, "ModifyRule", f"<Rules>{_rule_xml(rule)}</Rules>")
@@ -1052,7 +1296,7 @@ def _set_rule_priorities(params):
updated.append(_rules[arn])
i += 1
return _xml(200, "SetRulePriorities",
- f"<Rules>{''.join(_rule_xml(r) for r in updated)}</Rules>")
+ f"<Rules>{''.join(_rule_xml(r, with_transforms=False) for r in updated)}</Rules>")
# ---------------------------------------------------------------------------
@@ -1278,8 +1522,13 @@ async def handle_request(method, path, headers, body, query_params):
params = dict(query_params)
if method == "POST" and body:
raw = body if isinstance(body, str) else body.decode("utf-8", errors="replace")
- for k, v in parse_qs(raw).items():
- params[k] = v
+ # Blank values are kept for Transforms only: an empty Replace, Regex,
+ # Rewrites or Transforms list is a different request from an absent one.
+ for k, v in parse_qs(raw, keep_blank_values=True).items():
+ if not k.startswith("Transforms"):
+ v = [x for x in v if x]
+ if v:
+ params[k] = v
action = _p(params, "Action")
handler = _ACTION_MAP.get(action)
if not handler:
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 56ac9d44..634a8952 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -9727,6 +9727,121 @@ def _flatten_listener_rule_conditions(cfn_conditions):
return out
+_LISTENER_RULE_TRANSFORM_CONFIGS = ("HostHeaderRewriteConfig", "UrlRewriteConfig")
+
+
+def _schema_type(value):
+ """The type name CloudFormation's schema check reports for a template value."""
+ return "JSONArray" if isinstance(value, list) else "JSONObject" if isinstance(value, dict) else "String"
+
+
+def _schema_string_errors(obj, keys, path):
+ """String members holding an object or a list; numbers and booleans reach
+ the schema check as strings."""
+ return [(f"{path}/{key}", f"Property [{key}] expected type: String, found: {_schema_type(obj[key])}")
+ for key in keys if isinstance(obj.get(key), (dict, list))]
+
+
+def _listener_rule_rewrite_config_errors(config, path):
+ errors = []
+ if not isinstance(config, dict):
+ return [(path, f"Property [{path.rsplit('/', 1)[-1]}] expected type: JSONObject, found: {_schema_type(config)}")]
+ errors += [(path, f"Unsupported property [{key}]") for key in config if key != "Rewrites"]
+ if "Rewrites" not in config:
+ return errors + [(path, "Required property [Rewrites] not found")]
+ rewrites = config["Rewrites"]
+ if not isinstance(rewrites, list):
+ return errors + [(f"{path}/Rewrites",
+ f"Property [Rewrites] expected type: JSONArray, found: {_schema_type(rewrites)}")]
+ canonical = [json.dumps(rewrite, sort_keys=True) for rewrite in rewrites]
+ if len(set(canonical)) != len(canonical):
+ errors.append((f"{path}/Rewrites", f"#/{path}/Rewrites: array items are not unique"))
+ for j, rewrite in enumerate(rewrites):
+ at = f"{path}/Rewrites/{j}"
+ if not isinstance(rewrite, dict):
+ errors.append((at, f"Property [{j}] expected type: JSONObject, found: {_schema_type(rewrite)}"))
+ continue
+ errors += [(at, f"Required property [{key}] not found") for key in ("Regex", "Replace") if key not in rewrite]
+ errors += _schema_string_errors(rewrite, ("Regex", "Replace"), at)
+ errors += [(at, f"Unsupported property [{key}]") for key in rewrite if key not in ("Regex", "Replace")]
+ return errors
+
+
+def listener_rule_transforms_schema_errors(transforms):
+ """(path under Properties, reason) for each way ``Transforms`` breaks the
+ AWS::ElasticLoadBalancingV2::ListenerRule resource schema. CloudFormation
+ checks the schema before provisioning anything and reports each problem
+ as a PROPERTY_VALIDATION event; the reasons are AWS's."""
+ if transforms is _NO_VALUE_SENTINEL():
+ return []
+ if not isinstance(transforms, list):
+ return [("Transforms", f"Property [Transforms] expected type: JSONArray, found: {_schema_type(transforms)}")]
+ errors = []
+ # The schema marks Transforms "insertionOrder": false, and AWS reports the
+ # items' indices after sorting them by their JSON with sorted keys.
+ for i, item in enumerate(sorted(transforms, key=lambda t: json.dumps(t, sort_keys=True))):
+ path = f"Transforms/{i}"
+ if not isinstance(item, dict):
+ # Neither oneOf branch's "required" applies to a non-object, so both match.
+ errors += [(path, f"Property [{i}] expected type: JSONObject, found: {_schema_type(item)}"),
+ (path, f"#/Transforms/{i}: #: 2 subschemas matched instead of one")]
+ continue
+ if "Type" not in item:
+ errors.append((path, "Required property [Type] not found"))
+ errors += _schema_string_errors(item, ("Type",), path)
+ errors += [(path, f"Unsupported property [{key}]") for key in item
+ if key != "Type" and key not in _LISTENER_RULE_TRANSFORM_CONFIGS]
+ configs = [c for c in _LISTENER_RULE_TRANSFORM_CONFIGS if c in item]
+ if not configs:
+ errors += [(path, f"Required property [{c}] not found") for c in _LISTENER_RULE_TRANSFORM_CONFIGS]
+ elif len(configs) > 1:
+ errors.append((path, f"#/Transforms/{i}: #: 2 subschemas matched instead of one"))
+ for config in configs:
+ errors += _listener_rule_rewrite_config_errors(item[config], f"{path}/{config}")
+ canonical = [json.dumps(item, sort_keys=True) for item in transforms]
+ if len(set(canonical)) != len(canonical):
+ errors.append(("Transforms", "#/Transforms: array items are not unique"))
+ return errors
+
+
+def _template_string(value):
+ """A template scalar as the handler receives it: booleans as true/false."""
+ return str(value).lower() if isinstance(value, bool) else str(value)
+
+
+def _elbv2_handler_error(message):
+ """The resource status reason AWS's ListenerRule handler reports for an
+ ELBv2 request it refuses: the service message with the SDK's details."""
+ return ValueError(f'Resource handler returned message: "{_sdk_error(message, "ElasticLoadBalancingV2", 400)}" '
+ f"(RequestToken: {new_uuid()}, HandlerErrorCode: InvalidRequest)")
+
+
+def _elbv2_listener_rule_transforms(props):
+ """CFN ``Transforms`` in the API's RuleTransform shape, as the ALB service
+ stores CreateRule's. The stack has checked them against the resource
+ schema; the handler then sends them to the API, which refuses them with
+ its own messages. Template scalars reach it as strings. Transforms built
+ from another resource's values are only known here, so the schema is
+ checked again."""
+ schema = listener_rule_transforms_schema_errors(props.get("Transforms") or [])
+ if schema:
+ raise ValueError(schema[0][1])
+ transforms = []
+ for raw in props.get("Transforms") or []:
+ transform = {"Type": _template_string(raw["Type"])}
+ for config in _alb._TRANSFORM_CONFIG_KEYS.values():
+ if config in raw:
+ transform[config] = {"Rewrites": [
+ {"Regex": _template_string(r["Regex"]), "Replace": _template_string(r["Replace"])}
+ for r in raw[config]["Rewrites"]
+ ]}
+ transforms.append(transform)
+ problem = _alb._transforms_model_error(transforms) or _alb._transforms_problem(transforms)
+ if problem:
+ raise _elbv2_handler_error(problem)
+ return transforms
+
+
def _elbv2_listener_rule_create(logical_id, props, stack_name):
"""Provision an AWS::ElasticLoadBalancingV2::ListenerRule. Conditions and
Actions match the shape MS' ALB stores in `_alb._rules`.
@@ -9741,6 +9856,7 @@ def _elbv2_listener_rule_create(logical_id, props, stack_name):
lb_name = _alb._lbs[lb_arn]["LoadBalancerName"]
lb_id = _alb._load_balancer_id_from_arn(lb_arn)
l_id = _alb._listener_id_from_arn(l_arn)
+ transforms = _elbv2_listener_rule_transforms(props)
import random as _random
import string as _string
rule_id = "".join(_random.choices(_string.ascii_lowercase + _string.digits, k=16))
@@ -9755,6 +9871,7 @@ def _elbv2_listener_rule_create(logical_id, props, stack_name):
"Conditions": _flatten_listener_rule_conditions(props.get("Conditions") or []),
"Actions": _elbv2_listener_actions(props, None, prop="Actions"),
"IsDefault": False,
+ "Transforms": transforms,
}
_alb._rules[rule_arn] = rule
return rule_arn, {"RuleArn": rule_arn}
@@ -9767,8 +9884,8 @@ def _elbv2_listener_rule_delete(physical_id, props):
def _elbv2_listener_rule_update(physical_id, old_props, new_props, stack_name,
logical_id=None):
"""Update a listener rule in place, keeping its ARN (what ``Ref``
- returns). ``Actions``, ``Conditions`` and ``Priority`` are "Update
- requires: No interruption" and only ``ListenerArn`` requires replacement
+ returns). ``Actions``, ``Conditions``, ``Priority`` and ``Transforms`` are
+ "Update requires: No interruption" and only ``ListenerArn`` requires replacement
(https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listenerrule.html);
a rule ARN carries its listener, so moving one is a replacement under a
new physical id. ``Tags`` are left alone, because the create handler does
@@ -9782,9 +9899,11 @@ def _elbv2_listener_rule_update(physical_id, old_props, new_props, stack_name,
_delete_predecessor(_elbv2_listener_rule_delete, physical_id, old_props)
return created
+ transforms = _elbv2_listener_rule_transforms(new_props)
rule["Priority"] = str(new_props.get("Priority", 1))
rule["Conditions"] = _flatten_listener_rule_conditions(new_props.get("Conditions") or [])
rule["Actions"] = _elbv2_listener_actions(new_props, None, prop="Actions")
+ rule["Transforms"] = transforms
return physical_id, {"RuleArn": physical_id}
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index c87a5a56..e7fcd16f 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -621,10 +621,14 @@ def _static_property(raw, resources_defs, param_values, conditions, mappings, st
def _validation_errors(resources_defs, ordered, param_values, conditions, mappings, stack_name, stack_id,
owned_buckets=frozenset()):
"""Pre-deployment validation errors as ``(logical_id, type, validation name,
- path, reason)``: properties outside their schema enum, and AWS::S3::Bucket
- names the stack can't take (NAME_CONFLICT_VALIDATION, observed on AWS); a
- bucket the stack already owns is not a conflict for its update."""
- from ministack.services.cloudformation.provisioners import s3_bucket_name_conflict
+ path, reason)``: properties outside their schema enum, ListenerRule
+ Transforms that break the resource schema, and AWS::S3::Bucket names the
+ stack can't take (NAME_CONFLICT_VALIDATION, observed on AWS); a bucket the
+ stack already owns is not a conflict for its update."""
+ from ministack.services.cloudformation.provisioners import (
+ listener_rule_transforms_schema_errors,
+ s3_bucket_name_conflict,
+ )
errors = []
for logical_id in ordered:
@@ -643,6 +647,12 @@ def _validation_errors(resources_defs, ordered, param_values, conditions, mappin
# The enum check's validation name is not observed; PROPERTY_VALIDATION is inferred.
errors += [(logical_id, rtype, "PROPERTY_VALIDATION", f"/Resources/{logical_id}/Properties/{prop}", reason)
for prop, reason in _property_enum_errors(rtype, props)]
+ if (rtype == "AWS::ElasticLoadBalancingV2::ListenerRule" and "Transforms" in raw_props
+ and not any(name in resources_defs for name, _ in _intrinsic_references(raw_props["Transforms"]))):
+ transforms = _static_property(raw_props["Transforms"], resources_defs, param_values, conditions,
+ mappings, stack_name, stack_id)
+ errors += [(logical_id, rtype, "PROPERTY_VALIDATION", f"/Resources/{logical_id}/Properties/{path}", reason)
+ for path, reason in listener_rule_transforms_schema_errors(transforms)]
if rtype == "AWS::S3::Bucket" and raw_props.get("BucketName"):
name = _static_property(raw_props["BucketName"], resources_defs, param_values, conditions,
mappings, stack_name, stack_id)
diff --git a/tests/test_alb.py b/tests/test_alb.py
index dbdd3dc5..54b38fd2 100644
--- a/tests/test_alb.py
+++ b/tests/test_alb.py
@@ -1,6 +1,7 @@
import io
import json
import os
+import re
import time
import urllib.request as _req
import uuid as _uuid_mod
@@ -2070,3 +2071,648 @@ def test_elbv2_listener_rejects_more_than_one_default_certificate(elbv2, tls_lb)
described = elbv2.describe_listeners(ListenerArns=[l_arn])["Listeners"][0]
assert described["Port"] == 443
assert described["Certificates"] == [{"CertificateArn": _TLS_CERT}]
+
+
+def _url_rewrite(regex="^/app/(.*)$", replace="/$1"):
+ return {"Type": "url-rewrite",
+ "UrlRewriteConfig": {"Rewrites": [{"Regex": regex, "Replace": replace}]}}
+
+
+def _host_rewrite(regex="^www\\.example\\.com$", replace="internal.example.com"):
+ return {"Type": "host-header-rewrite",
+ "HostHeaderRewriteConfig": {"Rewrites": [{"Regex": regex, "Replace": replace}]}}
+
+
+def _rewrite(regex="^/a$", replace="/b"):
+ return {"Regex": regex, "Replace": replace}
+
+
+def raw_elbv2():
+ """A client without boto3's client-side parameter validation, so invalid
+ transforms reach the server, as in the AWS captures."""
+ from conftest import make_client
+
+ return make_client("elbv2", {"parameter_validation": False})
+
+
+def transform_listener(elbv2):
+ """A load balancer and listener for rule-transform tests, torn down afterwards."""
+ name = f"tx-{_uuid_mod.uuid4().hex[:8]}"
+ lb_arn = elbv2.create_load_balancer(Name=name)["LoadBalancers"][0]["LoadBalancerArn"]
+ l_arn = elbv2.create_listener(
+ LoadBalancerArn=lb_arn, Protocol="HTTP", Port=80,
+ DefaultActions=[{"Type": "fixed-response", "FixedResponseConfig": {"StatusCode": "404"}}],
+ )["Listeners"][0]["ListenerArn"]
+ try:
+ yield l_arn
+ finally:
+ for rule in elbv2.describe_rules(ListenerArn=l_arn)["Rules"]:
+ if not rule["IsDefault"]:
+ elbv2.delete_rule(RuleArn=rule["RuleArn"])
+ elbv2.delete_listener(ListenerArn=l_arn)
+ elbv2.delete_load_balancer(LoadBalancerArn=lb_arn)
+
+
+_TX_PRIORITY = iter(range(1, 50000))
+
+
+def _transform_rule(client, l_arn, **kwargs):
+ return client.create_rule(
+ ListenerArn=l_arn, Priority=next(_TX_PRIORITY),
+ Conditions=[{"Field": "path-pattern", "Values": ["/app/*"]}],
+ Actions=[{"Type": "fixed-response", "FixedResponseConfig": {"StatusCode": "200"}}],
+ **kwargs,
+ )["Rules"][0]
+
+
+def _described_rule(elbv2, rule_arn):
+ return elbv2.describe_rules(RuleArns=[rule_arn])["Rules"][0]
+
+
+def _default_rule(elbv2, l_arn):
+ return next(r for r in elbv2.describe_rules(ListenerArn=l_arn)["Rules"] if r["IsDefault"])
+
+
+def _non_default_rules(elbv2, l_arn):
+ return [r for r in elbv2.describe_rules(ListenerArn=l_arn)["Rules"] if not r["IsDefault"]]
+
+
+def _refused(exc_info, message, code="ValidationError"):
+ error = exc_info.value.response["Error"]
+ assert (exc_info.value.response["ResponseMetadata"]["HTTPStatusCode"], error["Type"], error["Code"]) == (
+ 400, "Sender", code)
+ if message is not None:
+ assert error["Message"] == message
+
+
+def _by_type(transforms):
+ """AWS returns a rule's transforms from DescribeRules and ModifyRule in an
+ order of its own, so comparisons outside CreateRule sort them."""
+ return sorted(transforms, key=lambda t: t["Type"])
+
+
+def test_elbv2_rule_transforms_are_stored_returned_replaced_and_reset(elbv2, transform_listener):
+ """AWS: captured 2026-10-20 and 2026-10-21 (elbv2-rule-transforms C1-C6, C37, C40;
+ 2310-uncertainties U1:order)."""
+ both = [_url_rewrite(), _host_rewrite()]
+ rule = _transform_rule(elbv2, transform_listener, Transforms=both)
+ assert rule["Transforms"] == both
+ assert _by_type(_described_rule(elbv2, rule["RuleArn"])["Transforms"]) == _by_type(both)
+ # CreateRule echoes the request order, whichever type comes first.
+ reverse = _transform_rule(elbv2, transform_listener, Transforms=both[::-1])
+ assert reverse["Transforms"] == both[::-1]
+
+ replacement = [_url_rewrite(regex="^/app/legacy$", replace="")]
+ modified = elbv2.modify_rule(RuleArn=rule["RuleArn"], Transforms=replacement)["Rules"][0]
+ assert modified["Transforms"] == replacement
+ assert _described_rule(elbv2, rule["RuleArn"])["Transforms"] == replacement
+
+ elbv2.modify_rule(RuleArn=rule["RuleArn"], Conditions=[{"Field": "path-pattern", "Values": ["/v2/*"]}])
+ assert _described_rule(elbv2, rule["RuleArn"])["Transforms"] == replacement
+
+ reset = elbv2.modify_rule(RuleArn=rule["RuleArn"], ResetTransforms=True)["Rules"][0]
+ assert reset["Transforms"] == []
+ assert _described_rule(elbv2, rule["RuleArn"])["Transforms"] == []
+ # Resetting a rule without transforms is accepted too.
+ assert elbv2.modify_rule(RuleArn=rule["RuleArn"], ResetTransforms=True)["Rules"][0]["Transforms"] == []
+
+ # ResetTransforms=False with Transforms is a plain replace.
+ replaced = elbv2.modify_rule(RuleArn=rule["RuleArn"], Transforms=[_host_rewrite()],
+ ResetTransforms=False)["Rules"][0]
+ assert replaced["Transforms"] == [_host_rewrite()]
+
+
+def test_elbv2_rules_without_transforms_return_an_empty_list(elbv2, transform_listener):
+ """AWS: captured 2026-10-20 (elbv2-rule-transforms C7, C8, C39). The XML carries
+ an empty <Transforms/> element."""
+ assert _transform_rule(elbv2, transform_listener)["Transforms"] == []
+ assert _transform_rule(elbv2, transform_listener, Transforms=[])["Transforms"] == []
+ assert _default_rule(elbv2, transform_listener)["Transforms"] == []
+
+
+def test_elbv2_rule_transform_rewrite_bounds_are_accepted(elbv2, raw_elbv2, transform_listener):
+ """AWS: captured 2026-10-20 and 2026-10-21 (elbv2-rule-transforms C4, C29;
+ 2310-uncertainties U7:host empty-replace and max-lengths)."""
+ for transform in (_url_rewrite(regex="a" * 1024, replace="b" * 1024),
+ _host_rewrite(regex="a" * 1024, replace="b" * 1024),
+ _host_rewrite(replace="")):
+ rule = _transform_rule(raw_elbv2, transform_listener, Transforms=[transform])
+ assert rule["Transforms"] == [transform]
+ assert _described_rule(elbv2, rule["RuleArn"])["Transforms"] == [transform]
+
+
+_INVALID_TRANSFORMS = [
+ ("unknown-type",
+ [{"Type": "path-rewrite", "UrlRewriteConfig": {"Rewrites": [_rewrite()]}}],
+ "1 validation error detected: Value 'path-rewrite' at 'transforms.1.member.type' failed to satisfy "
+ "constraint: Member must satisfy enum value set: [url-rewrite, host-header-rewrite]"),
+ ("duplicate-type", [_url_rewrite(), _url_rewrite(regex="^/b$")],
+ "A rule can only have one transform of each type"),
+ ("duplicate-host", [_host_rewrite(), _host_rewrite(regex="^b$")],
+ "A rule can only have one transform of each type"),
+ ("missing-config", [{"Type": "url-rewrite"}],
+ "For transforms of type 'url-rewrite', you must specify the following field(s): 'UrlRewriteConfig'"),
+ ("host-missing-config", [{"Type": "host-header-rewrite"}],
+ "For transforms of type 'host-header-rewrite', you must specify the following field(s): "
+ "'HostHeaderRewriteConfig'"),
+ ("other-config-only",
+ [{"Type": "url-rewrite", "HostHeaderRewriteConfig": {"Rewrites": [_rewrite()]}}],
+ "For transforms of type 'url-rewrite', you must specify the following field(s): 'UrlRewriteConfig'"),
+ ("wrong-config",
+ [{**_url_rewrite(), "HostHeaderRewriteConfig": {"Rewrites": [_rewrite()]}}],
+ "A transform of type 'url-rewrite' does not support the following field(s): 'HostHeaderRewriteConfig'"),
+ ("host-wrong-config",
+ [{**_host_rewrite(), "UrlRewriteConfig": {"Rewrites": [_rewrite()]}}],
+ "A transform of type 'host-header-rewrite' does not support the following field(s): 'UrlRewriteConfig'"),
+ ("two-rewrites",
+ [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [_rewrite(), _rewrite("^/c$", "/d")]}}],
+ "Rule transforms must have exactly one Rewrite"),
+ ("no-rewrites", [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": []}}],
+ "Rule transforms must have exactly one Rewrite"),
+ ("empty-regex", [_url_rewrite(regex="")],
+ "A transform rewrite Regex value must be between 1 and 1024 characters in length"),
+ ("long-regex", [_url_rewrite(regex="a" * 1025)],
+ "A transform rewrite Regex value must be between 1 and 1024 characters in length"),
+ ("long-replace", [_url_rewrite(replace="a" * 1025)],
+ "A transform rewrite Replace value must be between 0 and 1024 characters in length"),
+ ("invalid-regex", [_url_rewrite(regex="([")],
+ "One or more provided transform rewrite Regex values are invalid"),
+ ("null-type", [{"UrlRewriteConfig": {"Rewrites": [_rewrite()]}}],
+ "1 validation error detected: Value null at 'transforms.1.member.type' failed to satisfy constraint: "
+ "Member must not be null"),
+ ("null-regex", [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [{"Replace": "/b"}]}}],
+ "1 validation error detected: Value null at 'transforms.1.member.urlRewriteConfig.rewrites.1.member.regex' "
+ "failed to satisfy constraint: Member must not be null"),
+ ("null-replace", [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [{"Regex": "^/a$"}]}}],
+ "1 validation error detected: Value null at 'transforms.1.member.urlRewriteConfig.rewrites.1.member.replace' "
+ "failed to satisfy constraint: Member must not be null"),
+ ("host-null-regex",
+ [{"Type": "host-header-rewrite", "HostHeaderRewriteConfig": {"Rewrites": [{"Replace": "b"}]}}],
+ "1 validation error detected: Value null at "
+ "'transforms.1.member.hostHeaderRewriteConfig.rewrites.1.member.regex' "
+ "failed to satisfy constraint: Member must not be null"),
+]
+
+
[email protected]("transforms, message", [c[1:] for c in _INVALID_TRANSFORMS],
+ ids=[c[0] for c in _INVALID_TRANSFORMS])
+def test_elbv2_invalid_rule_transforms_are_rejected(elbv2, raw_elbv2, transform_listener, transforms, message):
+ """AWS: captured 2026-10-20 and 2026-10-21 (elbv2-rule-transforms C9-C26, C30-C34,
+ C45; 2310-uncertainties U7:host). CreateRule creates nothing and ModifyRule
+ leaves the rule as it was."""
+ with pytest.raises(ClientError) as exc:
+ _transform_rule(raw_elbv2, transform_listener, Transforms=transforms)
+ _refused(exc, message)
+ assert _non_default_rules(elbv2, transform_listener) == []
+
+ rule = _transform_rule(elbv2, transform_listener, Transforms=[_url_rewrite()])
+ with pytest.raises(ClientError) as exc:
+ raw_elbv2.modify_rule(RuleArn=rule["RuleArn"], Transforms=transforms,
+ Conditions=[{"Field": "path-pattern", "Values": ["/changed/*"]}])
+ _refused(exc, message)
+ after = _described_rule(elbv2, rule["RuleArn"])
+ assert after["Transforms"] == [_url_rewrite()]
+ assert after["Conditions"][0]["Values"] == ["/app/*"]
+
+
+_NULL_TYPE = "Value null at 'transforms.{}.member.type' failed to satisfy constraint: Member must not be null"
+
+
[email protected]("transforms, message", [
+ ([{"UrlRewriteConfig": {"Rewrites": [_rewrite()]}}] * 2,
+ f"2 validation errors detected: {_NULL_TYPE.format(1)}; {_NULL_TYPE.format(2)}"),
+ ([{"UrlRewriteConfig": {"Rewrites": [_rewrite()]}}] * 11,
+ "10 validation errors detected: " + "; ".join(_NULL_TYPE.format(i) for i in range(1, 11))),
+ ([{"Type": "path-rewrite", "UrlRewriteConfig": {"Rewrites": [{"Regex": "^/a$"}]}}],
+ "2 validation errors detected: Value null at 'transforms.1.member.urlRewriteConfig.rewrites.1.member.replace' "
+ "failed to satisfy constraint: Member must not be null; Value 'path-rewrite' at 'transforms.1.member.type' "
+ "failed to satisfy constraint: Member must satisfy enum value set: [url-rewrite, host-header-rewrite]"),
+ ([{"Type": "url-rewrite", "HostHeaderRewriteConfig": {"Rewrites": [{"Replace": "b"}]},
+ "UrlRewriteConfig": {"Rewrites": [{"Regex": "^/a$"}]}}],
+ "2 validation errors detected: Value null at 'transforms.1.member.hostHeaderRewriteConfig.rewrites.1.member."
+ "regex' failed to satisfy constraint: Member must not be null; Value null at 'transforms.1.member."
+ "urlRewriteConfig.rewrites.1.member.replace' failed to satisfy constraint: Member must not be null"),
+ ([{"HostHeaderRewriteConfig": {"Rewrites": [{"Replace": "b"}]},
+ "UrlRewriteConfig": {"Rewrites": [{"Regex": "^/a$"}]}}],
+ "3 validation errors detected: Value null at 'transforms.1.member.hostHeaderRewriteConfig.rewrites.1.member."
+ "regex' failed to satisfy constraint: Member must not be null; Value null at 'transforms.1.member."
+ "urlRewriteConfig.rewrites.1.member.replace' failed to satisfy constraint: Member must not be null; "
+ f"{_NULL_TYPE.format(1)}"),
+ ([{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [{"Replace": "/b"}, {"Replace": "/c"}]}}],
+ "2 validation errors detected: Value null at 'transforms.1.member.urlRewriteConfig.rewrites.1.member.regex' "
+ "failed to satisfy constraint: Member must not be null; Value null at "
+ "'transforms.1.member.urlRewriteConfig.rewrites.2.member.regex' failed to satisfy constraint: "
+ "Member must not be null"),
+ ([{"Type": "", "UrlRewriteConfig": {"Rewrites": [_rewrite()]}}],
+ "1 validation error detected: Value '' at 'transforms.1.member.type' failed to satisfy constraint: "
+ "Member must satisfy enum value set: [url-rewrite, host-header-rewrite]"),
+ # The model check runs before any other: the unknown type wins over the duplicate.
+ ([_url_rewrite(), _url_rewrite(regex="^/b$"),
+ {"Type": "path-rewrite", "UrlRewriteConfig": {"Rewrites": [_rewrite()]}}],
+ "1 validation error detected: Value 'path-rewrite' at 'transforms.3.member.type' failed to satisfy "
+ "constraint: Member must satisfy enum value set: [url-rewrite, host-header-rewrite]"),
+], ids=["two-null-types", "eleven-null-types", "replace-before-type", "host-before-url",
+ "type-last", "rewrite-order", "blank-type", "model-before-duplicate"])
+def test_elbv2_rule_transform_model_errors_are_listed_together(raw_elbv2, transform_listener, transforms, message):
+ """AWS: captured 2026-10-21 (2310-uncertainties U6:create, 2310-uncertainties-2
+ V3:order). Every missing or unknown member is listed, at most ten."""
+ with pytest.raises(ClientError) as exc:
+ _transform_rule(raw_elbv2, transform_listener, Transforms=transforms)
+ _refused(exc, message)
+
+
+_DUPLICATE = "A rule can only have one transform of each type"
+_REGEX_LENGTH = "A transform rewrite Regex value must be between 1 and 1024 characters in length"
+_REPLACE_LENGTH = "A transform rewrite Replace value must be between 0 and 1024 characters in length"
+_REGEX_INVALID = "One or more provided transform rewrite Regex values are invalid"
+_REGEX_ASCII = ("Transform rewrite regex values can not be empty, and can only contain "
+ "non-whitespace ASCII 128 characters")
+_REPLACE_CHARS = "A transform rewrite Replace value may only consist of non-whitespace printable ASCII characters"
+
+
[email protected]("transforms, message", [
+ ([_url_rewrite(regex=""), _url_rewrite()], _DUPLICATE),
+ ([_url_rewrite(regex="(["), _url_rewrite()], _DUPLICATE),
+ ([{"Type": "url-rewrite"}, _url_rewrite()], _DUPLICATE),
+ ([_url_rewrite(), host_rw := _host_rewrite(), _url_rewrite(regex="^/c$")], _DUPLICATE),
+ ([_url_rewrite(regex=""), {"Type": "host-header-rewrite"}], _REGEX_LENGTH),
+ ([_url_rewrite(replace="a" * 1025), {**host_rw, "UrlRewriteConfig": {"Rewrites": [_rewrite()]}}],
+ _REPLACE_LENGTH),
+ ([{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [_rewrite(), _rewrite()]}},
+ {"Type": "host-header-rewrite"}], "Rule transforms must have exactly one Rewrite"),
+ ([_url_rewrite(regex="(["), _host_rewrite(regex="")], _REGEX_INVALID),
+ ([_host_rewrite(regex=""), _url_rewrite(regex="([")], _REGEX_LENGTH),
+ ([{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": []},
+ "HostHeaderRewriteConfig": {"Rewrites": [_rewrite()]}}],
+ "A transform of type 'url-rewrite' does not support the following field(s): 'HostHeaderRewriteConfig'"),
+ ([{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [_rewrite(regex=""), _rewrite()]}}],
+ "Rule transforms must have exactly one Rewrite"),
+ ([_url_rewrite(regex="", replace="a" * 1025)], _REPLACE_LENGTH),
+ ([_url_rewrite(regex="([", replace="a" * 1025)], _REPLACE_LENGTH),
+ ([_url_rewrite(regex="([" + "a" * 1023)], _REGEX_LENGTH),
+ ([_url_rewrite(regex="\u20ac" * 1025)], _REGEX_LENGTH),
+ ([_url_rewrite(regex="\u00e9", replace="a" * 1025)], _REPLACE_LENGTH),
+ ([_url_rewrite(regex="\u00e9(")], _REGEX_ASCII),
+ ([_url_rewrite(regex="(\u00e9")], _REGEX_ASCII),
+ ([_url_rewrite(regex="\u00e9"), _host_rewrite(regex="")], _REGEX_ASCII),
+ ([_url_rewrite(regex="(["), _host_rewrite(regex="\u00e9")], _REGEX_INVALID),
+ ([_url_rewrite(regex="([", replace="a b")], _REPLACE_CHARS),
+ ([_url_rewrite(regex="", replace="a b")], _REPLACE_CHARS),
+ ([_url_rewrite(regex="\u00e9", replace="a b")], _REPLACE_CHARS),
+ ([_url_rewrite(replace="a b"), _url_rewrite()], _DUPLICATE),
+ ([_url_rewrite(replace="a b"), _host_rewrite(regex="")], _REPLACE_CHARS),
+ ([_url_rewrite(replace=" " * 1025)], _REPLACE_LENGTH),
+], ids=["duplicate-before-length", "duplicate-before-syntax", "duplicate-before-config", "duplicate-of-three",
+ "first-transform-first", "replace-length-first", "rewrite-count-first", "syntax-in-first",
+ "length-in-first", "unsupported-before-count", "count-before-length", "replace-before-regex",
+ "replace-before-syntax", "length-before-syntax", "length-before-ascii", "replace-before-ascii",
+ "ascii-before-syntax", "ascii-before-syntax-2", "ascii-in-first", "syntax-before-ascii-in-second",
+ "replace-chars-before-syntax", "replace-chars-before-length", "replace-chars-before-ascii",
+ "duplicate-before-replace-chars", "replace-chars-in-first", "replace-length-before-chars"])
+def test_elbv2_rule_transform_checks_run_in_aws_order(raw_elbv2, transform_listener, transforms, message):
+ """AWS: captured 2026-10-21 (2310-uncertainties U2:regex and U6:create, 2310-uncertainties-2
+ V1:ascii and V3:order, 2310-uncertainties-3 W2:replace-order). The duplicate-type check
+ covers every transform first; the rest run transform by transform."""
+ with pytest.raises(ClientError) as exc:
+ _transform_rule(raw_elbv2, transform_listener, Transforms=transforms)
+ _refused(exc, message)
+
+
+# Regex values AWS accepted and refused, captured 2026-10-21.
+_REGEX_ACCEPTED = [
+ "\\d+", "\\w+", "\\s", "[[:alpha:]]", "(?<n>x)", "(?P<n>x)", "a+?", "a++", "a*+", "\\b", "(?i)a", "a{2,3}",
+ "a**", "a|", "|", "(?:a)", "\\x41", "\\u0041", "\\A", "\\z", "$", "^", ".*", "(?s).", "(?m)^a", "(?R)",
+ "a{1001}", "]", "}", "a\x7fb", "(?R)a", "a**b", "a{2}{3}", "(?i:a)", "(?-i)a", "(?U)a", "[a-z&&b]", "[\\w-]",
+ "x{1000}", "x{1001,}", "\\x{41}", "\\(?=a", "[(?=a]", "a{1,2}{3}", "(?i)(?x)a", "(?ix)a", "(?xi)a", "\\z\\A",
+ "\\B", "\\v", "\\f", "\\a", "\\t", "\\n", "\\r", "\\$", "\\/", "\\-", "(?u)a", "(?:)a",
+ "a*{2}", "a+*", "a?*", "a{2}*", "a**b(c)", "[[:foo:]]", "[[:ALPHA:]]", "[[:digit:][:space:]]", "[[:^alpha:]]",
+ "[[=a=]]", "[[.a.]]",
+]
+_REGEX_REFUSED = [
+ "(?=a)", "(?!a)", "(?<=a)b", "(?<!a)b", "(a)\\1", "(?>a)", "\\p{L}", "\\pL", "\\X", "\\Q.\\E", "a{,3}", "a{3,2}",
+ "\\", "*a", "[a-", "[z-a]", ")", "(", "(?<n>x)\\k<n>", "\\1", "\\cA", "\\Z", "(?#c)a", "(?x) a", "\\G", "\\R",
+ "\\h", "\\K", "(?|a)", "\\N", "[", "{", "a{", "a{1", "\\e", "\\o{101}", "\\101", "(?P=n)", "(?P<n>x)(?P=n)",
+ "\\Z\\z", "[\\d-z]", "[^]", "([" + "a" * 1022, "(?<n>x)(?P=n)", "\\Qa", "(?P<n>x)|(?P<n>y)", "(a)(?(1)b|c)",
+ "\\0", "\\08", "\\p{Greek}", "\\d{,3}", "(?=", "a b", "a\tb", " ", "a\nb", "( ",
+ "(?Q)a", "(?z)a", "(?q:a)", "(?a)a", "(?L)a", "(?n)a", "(?J)a", "(?)a",
+ "a**(", "a**[", "a**)", "a{2}{3}(", "[[:alpha:]",
+]
+
+
+def test_elbv2_rule_transform_regex_syntax_follows_aws(elbv2, raw_elbv2, transform_listener):
+ """AWS: captured 2026-10-21 (2310-uncertainties U2:regex, 2310-uncertainties-2
+ V1:ascii and V2:regex-more, 2310-uncertainties-4 X1:api, 2310-uncertainties-5
+ Y1:regex). Each Regex is sent on its own url-rewrite."""
+ wrong = []
+ for regex in _REGEX_ACCEPTED + _REGEX_REFUSED:
+ try:
+ rule = _transform_rule(raw_elbv2, transform_listener, Transforms=[_url_rewrite(regex=regex)])
+ elbv2.delete_rule(RuleArn=rule["RuleArn"])
+ got = None
+ except ClientError as exc:
+ got = exc.response["Error"]["Message"]
+ if got != (None if regex in _REGEX_ACCEPTED else _REGEX_INVALID):
+ wrong.append((regex, got))
+ assert wrong == []
+
+
[email protected]("transform, message", [
+ (_url_rewrite(regex="\u00e9"), _REGEX_ASCII),
+ (_url_rewrite(regex="\u20ac" * 1024), _REGEX_ASCII),
+ (_url_rewrite(replace="/\u00e9"), _REPLACE_CHARS),
+ (_url_rewrite(replace="/a b"), _REPLACE_CHARS),
+ (_url_rewrite(replace=" "), _REPLACE_CHARS),
+ (_url_rewrite(replace="\t"), _REPLACE_CHARS),
+ (_url_rewrite(replace="a\x7fb"), _REPLACE_CHARS),
+ (_host_rewrite(regex="a b"), _REGEX_INVALID),
+ (_host_rewrite(replace="\u00e9"), _REPLACE_CHARS),
+ (_host_rewrite(regex="(["), _REGEX_INVALID),
+], ids=["regex-non-ascii", "regex-1024-non-ascii", "replace-non-ascii", "replace-space", "replace-only-space",
+ "replace-tab", "replace-del", "host-regex-space", "host-replace-non-ascii", "host-invalid-regex"])
+def test_elbv2_rule_transform_characters_are_checked(raw_elbv2, transform_listener, transform, message):
+ """AWS: captured 2026-10-21 (2310-uncertainties U2:regex, 2310-uncertainties-2 V1:ascii,
+ 2310-uncertainties-3 W2:replace-order)."""
+ with pytest.raises(ClientError) as exc:
+ _transform_rule(raw_elbv2, transform_listener, Transforms=[transform])
+ _refused(exc, message)
+
+
+def test_elbv2_rule_transform_replace_takes_any_printable_ascii(raw_elbv2, transform_listener):
+ """AWS: captured 2026-10-21 (2310-uncertainties U2:regex replace_with_regex_^/a$,
+ 2310-uncertainties-3 W2:replace-order replace-tilde-bang)."""
+ for replace in ("$1", "$10", "${1}", "${name}", "$", "\\1", "\\", "$$", "{host}", "#{host}", "~!"):
+ rule = _transform_rule(raw_elbv2, transform_listener, Transforms=[_url_rewrite(regex="^/a$", replace=replace)])
+ assert rule["Transforms"][0]["UrlRewriteConfig"]["Rewrites"][0]["Replace"] == replace
+
+
+def test_elbv2_modify_rule_transforms_and_reset_transforms_conflict(elbv2, raw_elbv2, transform_listener):
+ """AWS: captured 2026-10-20 and 2026-10-21 (elbv2-rule-transforms C27;
+ 2310-uncertainties U4:nothing-to-modify, U6:modify). The conflict comes after
+ the model check and before the other transform checks, and an empty
+ Transforms list counts."""
+ rule = _transform_rule(elbv2, transform_listener, Transforms=[_url_rewrite()])
+ conflict = "Transforms cannot be provided when resetting transforms"
+ for transforms, message in (
+ ([_host_rewrite()], conflict),
+ ([], conflict),
+ ([_url_rewrite(), _url_rewrite(regex="")], conflict),
+ ([_url_rewrite(regex="([")], conflict),
+ ([{"Type": "path-rewrite", "UrlRewriteConfig": {"Rewrites": [_rewrite()]}}],
+ "1 validation error detected: Value 'path-rewrite' at 'transforms.1.member.type' failed to satisfy "
+ "constraint: Member must satisfy enum value set: [url-rewrite, host-header-rewrite]")):
+ with pytest.raises(ClientError) as exc:
+ raw_elbv2.modify_rule(RuleArn=rule["RuleArn"], Transforms=transforms, ResetTransforms=True)
+ _refused(exc, message)
+ assert _described_rule(elbv2, rule["RuleArn"])["Transforms"] == [_url_rewrite()]
+
+
+def test_elbv2_modify_rule_needs_something_to_change(elbv2, raw_elbv2, transform_listener):
+ """AWS: captured 2026-10-20 and 2026-10-21 (elbv2-rule-transforms C38;
+ 2310-uncertainties U4:nothing-to-modify). An empty Transforms list changes
+ nothing, alone or next to Conditions or Actions."""
+ rule = _transform_rule(elbv2, transform_listener, Transforms=[_url_rewrite()])
+ nothing = "You must provide either conditions, actions, or transforms"
+ for params in ({}, {"ResetTransforms": False}, {"Transforms": []},
+ {"Transforms": [], "ResetTransforms": False}):
+ with pytest.raises(ClientError) as exc:
+ raw_elbv2.modify_rule(RuleArn=rule["RuleArn"], **params)
+ _refused(exc, nothing)
+ assert _described_rule(elbv2, rule["RuleArn"])["Transforms"] == [_url_rewrite()]
+
+ changed = elbv2.modify_rule(RuleArn=rule["RuleArn"], Transforms=[],
+ Conditions=[{"Field": "path-pattern", "Values": ["/u4/*"]}])["Rules"][0]
+ assert changed["Transforms"] == [_url_rewrite()]
+ assert changed["Conditions"][0]["Values"] == ["/u4/*"]
+ elbv2.modify_rule(RuleArn=rule["RuleArn"], Transforms=[],
+ Actions=[{"Type": "fixed-response", "FixedResponseConfig": {"StatusCode": "201"}}])
+ after = _described_rule(elbv2, rule["RuleArn"])
+ assert after["Transforms"] == [_url_rewrite()]
+ assert after["Actions"][0]["FixedResponseConfig"]["StatusCode"] == "201"
+
+
+def test_elbv2_default_rule_cannot_be_modified(elbv2, raw_elbv2, transform_listener):
+ """AWS: captured 2026-10-20 and 2026-10-21 (elbv2-rule-transforms C28, C35, C36;
+ 2310-uncertainties U3:default-rule). The transform checks, the conflict and
+ "You must provide ..." come first."""
+ default = _default_rule(elbv2, transform_listener)
+ arn = default["RuleArn"]
+ not_permitted = f"Default rule '{arn}' cannot be modified"
+ for params, code, message in (
+ ({"Transforms": [_url_rewrite()]}, "OperationNotPermitted", not_permitted),
+ ({"ResetTransforms": True}, "OperationNotPermitted", not_permitted),
+ ({"Conditions": [{"Field": "path-pattern", "Values": ["/d/*"]}]}, "OperationNotPermitted",
+ not_permitted),
+ ({"Actions": [{"Type": "fixed-response", "FixedResponseConfig": {"StatusCode": "404"}}]},
+ "OperationNotPermitted", not_permitted),
+ ({"Conditions": [{"Field": "path-pattern", "Values": ["/d/*"]}], "Transforms": [_url_rewrite()]},
+ "OperationNotPermitted", not_permitted),
+ ({"Transforms": [_url_rewrite()], "ResetTransforms": True}, "ValidationError",
+ "Transforms cannot be provided when resetting transforms"),
+ ({"Transforms": [], "ResetTransforms": True}, "ValidationError",
+ "Transforms cannot be provided when resetting transforms"),
+ ({"Transforms": [_url_rewrite(), _url_rewrite(regex="^/b$")]}, "ValidationError", _DUPLICATE),
+ ({"Transforms": [{"UrlRewriteConfig": {"Rewrites": [_rewrite()]}}]}, "ValidationError",
+ f"1 validation error detected: {_NULL_TYPE.format(1)}"),
+ ({}, "ValidationError", "You must provide either conditions, actions, or transforms"),
+ ({"ResetTransforms": False}, "ValidationError",
+ "You must provide either conditions, actions, or transforms"),
+ ({"Transforms": []}, "ValidationError", "You must provide either conditions, actions, or transforms")):
+ with pytest.raises(ClientError) as exc:
+ raw_elbv2.modify_rule(RuleArn=arn, **params)
+ _refused(exc, message, code)
+ assert _default_rule(elbv2, transform_listener) == default
+
+
+_LOOKUP_INPUTS = [
+ ("missing-config", [{"Type": "url-rewrite"}],
+ "For transforms of type 'url-rewrite', you must specify the following field(s): 'UrlRewriteConfig'"),
+ ("no-rewrites", [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": []}}],
+ "Rule transforms must have exactly one Rewrite"),
+ ("empty-regex", [_url_rewrite(regex="")], _REGEX_LENGTH),
+ ("long-replace", [_url_rewrite(replace="a" * 1025)], _REPLACE_LENGTH),
+ ("invalid-regex", [_url_rewrite(regex="([")], _REGEX_INVALID),
+ ("duplicate-type", [_url_rewrite(), _url_rewrite(regex="^/b$")], _DUPLICATE),
+ ("null-type", [{"UrlRewriteConfig": {"Rewrites": [_rewrite()]}}],
+ f"1 validation error detected: {_NULL_TYPE.format(1)}"),
+ ("null-replace", [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [{"Regex": "^/a$"}]}}],
+ "1 validation error detected: Value null at 'transforms.1.member.urlRewriteConfig.rewrites.1.member.replace' "
+ "failed to satisfy constraint: Member must not be null"),
+]
+
+
[email protected]("transforms, message", [c[1:] for c in _LOOKUP_INPUTS], ids=[c[0] for c in _LOOKUP_INPUTS])
+def test_elbv2_rule_transforms_are_checked_before_the_lookup(raw_elbv2, transform_listener, transforms, message):
+ """AWS: captured 2026-10-20 and 2026-10-21 (elbv2-rule-transforms C41, C42;
+ 2310-uncertainties U5:missing-listener, U5:missing-rule). On a load balancer
+ that exists, a missing listener or rule is reported after the transforms."""
+ missing_listener = transform_listener.rsplit("/", 1)[0] + "/0123456789abcdef"
+ with pytest.raises(ClientError) as exc:
+ _transform_rule(raw_elbv2, missing_listener, Transforms=transforms)
+ _refused(exc, message)
+ default = _default_rule(raw_elbv2, transform_listener)["RuleArn"]
+ with pytest.raises(ClientError) as exc:
+ raw_elbv2.modify_rule(RuleArn=default.rsplit("/", 1)[0] + "/0123456789abcdef", Transforms=transforms)
+ _refused(exc, message)
+
+
+def test_elbv2_missing_listener_or_rule_after_the_transform_checks(raw_elbv2, transform_listener):
+ """AWS: captured 2026-10-21 (2310-uncertainties U5:missing-listener, U5:missing-rule,
+ 2310-uncertainties-3 W1:unknown-lb). The not-found messages are MiniStack's
+ own, shared with other calls, so only the codes are checked. A load balancer
+ that doesn't exist is reported right after the model check."""
+ missing_listener = transform_listener.rsplit("/", 1)[0] + "/0123456789abcdef"
+ for transforms in ([_url_rewrite()], [], None):
+ with pytest.raises(ClientError) as exc:
+ _transform_rule(raw_elbv2, missing_listener, **({} if transforms is None else {"Transforms": transforms}))
+ _refused(exc, None, "ListenerNotFound")
+ parts = transform_listener.split("/")
+ parts[3] = "0000000000000000"
+ with pytest.raises(ClientError) as exc:
+ _transform_rule(raw_elbv2, "/".join(parts), Transforms=[_url_rewrite(), _url_rewrite(regex="^/b$")])
+ _refused(exc, None, "ListenerNotFound")
+
+ missing_rule = _default_rule(raw_elbv2, transform_listener)["RuleArn"].rsplit("/", 1)[0] + "/0123456789abcdef"
+ for params in ({"Transforms": [_url_rewrite()]}, {"ResetTransforms": True},
+ {"Conditions": [{"Field": "path-pattern", "Values": ["/x/*"]}]}):
+ with pytest.raises(ClientError) as exc:
+ raw_elbv2.modify_rule(RuleArn=missing_rule, **params)
+ _refused(exc, None, "RuleNotFound")
+ for params, message in (({"Transforms": [_url_rewrite()], "ResetTransforms": True},
+ "Transforms cannot be provided when resetting transforms"),
+ ({}, "You must provide either conditions, actions, or transforms"),
+ ({"Transforms": []}, "You must provide either conditions, actions, or transforms")):
+ with pytest.raises(ClientError) as exc:
+ raw_elbv2.modify_rule(RuleArn=missing_rule, **params)
+ _refused(exc, message)
+ parts = missing_rule.split("/")
+ parts[3] = "0000000000000000"
+ unknown_lb_rule = "/".join(parts)
+ for params in ({"Transforms": [_url_rewrite(), _url_rewrite(regex="^/b$")]},
+ {"Transforms": [{"Type": "url-rewrite"}]},
+ {"Transforms": [_url_rewrite()], "ResetTransforms": True}, {}, {"Transforms": []},
+ {"ResetTransforms": True}):
+ with pytest.raises(ClientError) as exc:
+ raw_elbv2.modify_rule(RuleArn=unknown_lb_rule, **params)
+ _refused(exc, None, "RuleNotFound")
+ null_type = [{"UrlRewriteConfig": {"Rewrites": [_rewrite()]}}]
+ with pytest.raises(ClientError) as exc:
+ raw_elbv2.modify_rule(RuleArn=unknown_lb_rule, Transforms=null_type)
+ _refused(exc, f"1 validation error detected: {_NULL_TYPE.format(1)}")
+ parts = transform_listener.split("/")
+ parts[3] = "0000000000000000"
+ with pytest.raises(ClientError) as exc:
+ _transform_rule(raw_elbv2, "/".join(parts), Transforms=null_type)
+ _refused(exc, f"1 validation error detected: {_NULL_TYPE.format(1)}")
+ for transforms in ([{"Type": "url-rewrite"}], [_url_rewrite(regex="([")]):
+ with pytest.raises(ClientError) as exc:
+ _transform_rule(raw_elbv2, "/".join(parts), Transforms=transforms)
+ _refused(exc, None, "ListenerNotFound")
+
+
+def test_elbv2_set_rule_priorities_returns_rules_without_transforms(elbv2, transform_listener):
+ """AWS: captured 2026-10-21 (2310-uncertainties U8:set-rule-priorities). The
+ response's rules carry no Transforms element, with or without transforms."""
+ rule = _transform_rule(elbv2, transform_listener, Transforms=[_url_rewrite(), _host_rewrite()])
+ moved = elbv2.set_rule_priorities(RulePriorities=[{"RuleArn": rule["RuleArn"], "Priority": 40000}])["Rules"][0]
+ assert moved["Priority"] == "40000"
+ assert "Transforms" not in moved
+ assert _by_type(_described_rule(elbv2, rule["RuleArn"])["Transforms"]) == _by_type(
+ [_url_rewrite(), _host_rewrite()])
+
+
+def test_elbv2_rule_transforms_survive_a_state_round_trip(monkeypatch, tmp_path):
+ """Rules persist as dicts, so their Transforms come back after a save and restore."""
+ from ministack.core import persistence
+ from ministack.services import alb
+
+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)
+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))
+ alb.reset()
+ try:
+ lb_arn = re.search(rb"<LoadBalancerArn>([^<]+)", alb._create_lb(
+ {"Name": ["persist-tx"]})[2]).group(1).decode()
+ l_arn = re.search(rb"<ListenerArn>([^<]+)", alb._create_listener(
+ {"LoadBalancerArn": [lb_arn], "Port": ["80"]})[2]).group(1).decode()
+ prefix = "Transforms.member.1.UrlRewriteConfig.Rewrites.member.1"
+ status, _, body = alb._create_rule({
+ "ListenerArn": [l_arn], "Priority": ["5"],
+ "Transforms.member.1.Type": ["url-rewrite"],
+ f"{prefix}.Regex": ["^/app/(.*)$"], f"{prefix}.Replace": ["/$1"],
+ })
+ assert status == 200, body
+ rule_arn = re.search(rb"<RuleArn>([^<]+)", body).group(1).decode()
+
+ persistence.save_state("alb", alb.get_state())
+ alb.reset()
+ alb.load_persisted_state(persistence.load_state("alb"))
+
+ assert alb._rules[rule_arn]["Transforms"] == [
+ {"Type": "url-rewrite",
+ "UrlRewriteConfig": {"Rewrites": [{"Regex": "^/app/(.*)$", "Replace": "/$1"}]}},
+ ]
+ finally:
+ alb.reset()
+
+
+def _elbv2_query(params):
+ """POST a raw ELBv2 Query request, for wire forms boto3 never sends."""
+ from urllib.parse import urlencode as _urlencode
+
+ req = _req.Request(_endpoint + "/", data=_urlencode({"Version": "2015-12-01", **params}).encode(), headers={
+ "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/elasticloadbalancing/aws4_request, "
+ "SignedHeaders=host, Signature=0"})
+ try:
+ with _req.urlopen(req) as resp:
+ return resp.status, resp.read().decode()
+ except HTTPError as exc:
+ return exc.code, exc.read().decode()
+
+
[email protected]("fields, message", [
+ ({"Type": "url-rewrite", "UrlRewriteConfig.Rewrites.member.1.Foo": "x"},
+ "2 validation errors detected: Value null at 'transforms.1.member.urlRewriteConfig.rewrites.1.member.regex' "
+ "failed to satisfy constraint: Member must not be null; Value null at "
+ "'transforms.1.member.urlRewriteConfig.rewrites.1.member.replace' failed to satisfy constraint: "
+ "Member must not be null"),
+ ({"Type": "url-rewrite", "UrlRewriteConfig.Rewrites.member.1.Regex": "^/a$",
+ "UrlRewriteConfig.Rewrites.member.1.Foo": "x"},
+ "1 validation error detected: Value null at 'transforms.1.member.urlRewriteConfig.rewrites.1.member.replace' "
+ "failed to satisfy constraint: Member must not be null"),
+ ({"Type": "url-rewrite", "UrlRewriteConfig.Foo": "x"}, "Rule transforms must have exactly one Rewrite"),
+ ({"Foo": "x"}, f"1 validation error detected: {_NULL_TYPE.format(1)}"),
+], ids=["rewrite-only-unknown", "rewrite-regex-and-unknown", "config-only-unknown", "transform-only-unknown"])
+def test_elbv2_rule_transform_members_with_unknown_fields(transform_listener, fields, message):
+ """AWS: captured 2026-10-21 (2310-uncertainties-2 V3:order raw-regex-and-replace-null,
+ 2310-uncertainties-4 X1:api raw-*). A member counts as sent when any of its
+ keys is, and the unknown keys are ignored."""
+ status, body = _elbv2_query({
+ "Action": "CreateRule", "ListenerArn": transform_listener, "Priority": str(next(_TX_PRIORITY)),
+ "Conditions.member.1.Field": "path-pattern", "Conditions.member.1.Values.member.1": "/raw/*",
+ "Actions.member.1.Type": "fixed-response", "Actions.member.1.FixedResponseConfig.StatusCode": "200",
+ **{f"Transforms.member.1.{k}": v for k, v in fields.items()}})
+ assert status == 400, body
+ assert re.search(r"<Code>(.*?)</Code><Message>(.*?)</Message>", body).groups() == (
+ "ValidationError", message.replace("'", "'"))
+
+
+def test_elbv2_rule_transform_message_echoes_the_type_escaped(raw_elbv2, transform_listener):
+ """AWS: captured 2026-10-21 (2310-uncertainties-4 X1:api type-xml-chars)."""
+ with pytest.raises(ClientError) as exc:
+ _transform_rule(raw_elbv2, transform_listener,
+ Transforms=[{"Type": "a&b<c>'\"", "UrlRewriteConfig": {"Rewrites": [_rewrite()]}}])
+ _refused(exc, "1 validation error detected: Value 'a&b<c>'\"' at 'transforms.1.member.type' failed to satisfy "
+ "constraint: Member must satisfy enum value set: [url-rewrite, host-header-rewrite]")
+
+
+def test_elbv2_modify_rule_with_empty_conditions_or_actions_changes_nothing(elbv2, raw_elbv2, transform_listener):
+ """AWS: captured 2026-10-21 (2310-uncertainties-4 X1:api modify-conditions-empty,
+ modify-actions-empty, modify-conditions-and-actions-empty)."""
+ rule = _transform_rule(elbv2, transform_listener, Transforms=[_url_rewrite()])
+ for params in ({"Conditions": []}, {"Actions": []}, {"Conditions": [], "Actions": []}):
+ with pytest.raises(ClientError) as exc:
+ raw_elbv2.modify_rule(RuleArn=rule["RuleArn"], **params)
+ _refused(exc, "You must provide either conditions, actions, or transforms")
+ assert _described_rule(elbv2, rule["RuleArn"])["Transforms"] == [_url_rewrite()]
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 9844f1bb..4138425e 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -8249,7 +8249,7 @@ def _cfn_elbv2_template(uid, *, health_path="/a", idle_timeout="60",
priority=10, scheme="internet-facing", name=None,
tg_port=80, listener_port=80, listener_protocol="HTTP",
listener_actions=None, listener_lb="LB",
- second_lb=False):
+ second_lb=False, rule_transforms=None):
resources = {
"LB": {
"Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
@@ -8293,6 +8293,7 @@ def _cfn_elbv2_template(uid, *, health_path="/a", idle_timeout="60",
{"Field": "path-pattern", "Values": [f"{health_path}*"]},
],
"Actions": [{"Type": "forward", "TargetGroupArn": {"Ref": "TG"}}],
+ **({"Transforms": rule_transforms} if rule_transforms is not None else {}),
},
},
}
@@ -8362,6 +8363,278 @@ def test_cfn_elbv2_update_keeps_the_arns_and_the_registered_targets(cfn, elbv2):
_delete_cfn_test_stack(cfn, stack_name)
+_CFN_URL_REWRITE = {"Type": "url-rewrite", "UrlRewriteConfig": {
+ "Rewrites": [{"Regex": "^/a/(.*)$", "Replace": "/$1"}]}}
+_CFN_HOST_REWRITE = {"Type": "host-header-rewrite", "HostHeaderRewriteConfig": {
+ "Rewrites": [{"Regex": "^www\\.example\\.com$", "Replace": "example.com"}]}}
+
+
+def _cfn_rewrite(regex="^/a$", replace="/b"):
+ return {"Regex": regex, "Replace": replace}
+
+
+def _cfn_validation_errors(cfn, stack_name):
+ return sorted((e["LogicalResourceId"], e["ValidationName"], e["ValidationPath"], e["ValidationStatusReason"])
+ for e in cfn.describe_events(StackName=stack_name)["OperationEvents"]
+ if e["EventType"] == "VALIDATION_ERROR")
+
+
+def _cfn_handler_reason(message):
+ """The ListenerRule handler's reason for a refused ELBv2 request, as a pattern."""
+ return re.compile(
+ r'Resource handler returned message: "' + re.escape(message)
+ + r' \(Service: ElasticLoadBalancingV2, Status Code: 400, Request ID: [0-9a-f-]{36}\) '
+ r'\(SDK Attempt Count: 1\)" \(RequestToken: [0-9a-f-]{36}, HandlerErrorCode: InvalidRequest\)$')
+
+
+def _cfn_rule_reasons(cfn, stack_name, status):
+ return [e["ResourceStatusReason"] for e in cfn.describe_stack_events(StackName=stack_name)["StackEvents"]
+ if e["LogicalResourceId"] == "R" and e["ResourceStatus"] == status]
+
+
+def test_cfn_elbv2_listener_rule_transforms_are_created_updated_and_removed(cfn, elbv2):
+ """AWS: captured 2026-10-20 and 2026-10-21 (elbv2-rule-transforms C47-C49;
+ 2310-uncertainties U10:cfn-create empty-list and empty-replace, U10:cfn-update
+ empty-list; 2310-uncertainties-4 X2:cfn novalue, replace-boolean, regex-boolean).
+ Transforms are "Update requires: No interruption", so each update
+ keeps the rule ARN."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-elbv2-tx-{uid}"
+ empty_replace = {"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [_cfn_rewrite(replace="")]}}
+
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_elbv2_template(uid, rule_transforms=[_CFN_URL_REWRITE]))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ rule_arn = _output(stack, "RuleRef")
+ assert elbv2.describe_rules(RuleArns=[rule_arn])["Rules"][0]["Transforms"] == [_CFN_URL_REWRITE]
+
+ booleans = {"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [{"Regex": False, "Replace": True}]}}
+ as_strings = {"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [_cfn_rewrite("false", "true")]}}
+ for transforms, expected in (([_CFN_HOST_REWRITE], [_CFN_HOST_REWRITE]), ([], []),
+ ([empty_replace], [empty_replace]), ([booleans], [as_strings]),
+ ({"Ref": "AWS::NoValue"}, []), (None, [])):
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_elbv2_template(
+ uid, rule_transforms=transforms))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "RuleRef") == rule_arn
+ assert elbv2.describe_rules(RuleArns=[rule_arn])["Rules"][0]["Transforms"] == expected
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+_T0 = "/Resources/R/Properties/Transforms/0"
+_T1 = "/Resources/R/Properties/Transforms/1"
+_BOTH_CONFIGS_MISSING = [(_T0, "Required property [HostHeaderRewriteConfig] not found"),
+ (_T0, "Required property [UrlRewriteConfig] not found")]
+_CFN_SCHEMA_CASES = [
+ ("missing-config", [{"Type": "url-rewrite"}], _BOTH_CONFIGS_MISSING),
+ ("host-missing-config", [{"Type": "host-header-rewrite"}], _BOTH_CONFIGS_MISSING),
+ ("both-configs", [{**_CFN_URL_REWRITE, "HostHeaderRewriteConfig": {"Rewrites": [_cfn_rewrite()]}}],
+ [(_T0, "#/Transforms/0: #: 2 subschemas matched instead of one")]),
+ ("identical-items", [_CFN_URL_REWRITE, _CFN_URL_REWRITE],
+ [("/Resources/R/Properties/Transforms", "#/Transforms: array items are not unique")]),
+ ("missing-type", [{"UrlRewriteConfig": {"Rewrites": [_cfn_rewrite()]}}],
+ [(_T0, "Required property [Type] not found")]),
+ ("missing-rewrites", [{"Type": "url-rewrite", "UrlRewriteConfig": {}}],
+ [(f"{_T0}/UrlRewriteConfig", "Required property [Rewrites] not found")]),
+ ("missing-regex", [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [{"Replace": "/b"}]}}],
+ [(f"{_T0}/UrlRewriteConfig/Rewrites/0", "Required property [Regex] not found")]),
+ ("missing-replace", [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [{"Regex": "^/a$"}]}}],
+ [(f"{_T0}/UrlRewriteConfig/Rewrites/0", "Required property [Replace] not found")]),
+ ("extra-transform-property", [{**_CFN_URL_REWRITE, "Foo": "x"}], [(_T0, "Unsupported property [Foo]")]),
+ ("extra-rewrite-property",
+ [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [{**_cfn_rewrite(), "Foo": "x"}]}}],
+ [(f"{_T0}/UrlRewriteConfig/Rewrites/0", "Unsupported property [Foo]")]),
+ ("not-an-array", _CFN_URL_REWRITE,
+ [("/Resources/R/Properties/Transforms", "Property [Transforms] expected type: JSONArray, found: JSONObject")]),
+ ("item-not-an-object", ["url-rewrite"],
+ [(_T0, "#/Transforms/0: #: 2 subschemas matched instead of one"),
+ (_T0, "Property [0] expected type: JSONObject, found: String")]),
+ ("rewrites-not-an-array", [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": _cfn_rewrite()}}],
+ [(f"{_T0}/UrlRewriteConfig/Rewrites", "Property [Rewrites] expected type: JSONArray, found: JSONObject")]),
+ # AWS reports indices after sorting the items by their JSON with sorted keys.
+ ("missing-config-at-index-1", [_CFN_URL_REWRITE, {"Type": "host-header-rewrite"}], _BOTH_CONFIGS_MISSING),
+ ("missing-and-both-configs",
+ [{"Type": "url-rewrite"}, {**_CFN_HOST_REWRITE, "UrlRewriteConfig": {"Rewrites": [_cfn_rewrite()]}}],
+ [(_T1, "Required property [HostHeaderRewriteConfig] not found"),
+ (_T1, "Required property [UrlRewriteConfig] not found"),
+ (_T0, "#/Transforms/0: #: 2 subschemas matched instead of one")]),
+ ("sorted-both-configs-first",
+ [{"Type": "url-rewrite", "HostHeaderRewriteConfig": {"Rewrites": [_cfn_rewrite()]},
+ "UrlRewriteConfig": {"Rewrites": [_cfn_rewrite()]}}, {"Type": "host-header-rewrite"}],
+ [(_T0, "#/Transforms/0: #: 2 subschemas matched instead of one"),
+ (_T1, "Required property [HostHeaderRewriteConfig] not found"),
+ (_T1, "Required property [UrlRewriteConfig] not found")]),
+ ("sorted-unsupported-first", [{"Type": "url-rewrite"}, {"Type": "host-header-rewrite", "Foo": "x"}],
+ _BOTH_CONFIGS_MISSING + [(_T1, "Required property [HostHeaderRewriteConfig] not found"),
+ (_T1, "Required property [UrlRewriteConfig] not found"),
+ (_T0, "Unsupported property [Foo]")]),
+ ("sorted-by-key-not-type", [{"Type": "aaa", "UrlRewriteConfig": {"Rewrites": "x"}},
+ {"HostHeaderRewriteConfig": {"Rewrites": "y"}, "Type": "zzz"}],
+ [(f"{_T0}/HostHeaderRewriteConfig/Rewrites", "Property [Rewrites] expected type: JSONArray, found: String"),
+ (f"{_T1}/UrlRewriteConfig/Rewrites", "Property [Rewrites] expected type: JSONArray, found: String")]),
+ ("identical-rewrites",
+ [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [_cfn_rewrite(), _cfn_rewrite()]}}],
+ [(f"{_T0}/UrlRewriteConfig/Rewrites", "#/Transforms/0/UrlRewriteConfig/Rewrites: array items are not unique")]),
+ ("config-extra-property",
+ [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [_cfn_rewrite()], "Foo": "x"}}],
+ [(f"{_T0}/UrlRewriteConfig", "Unsupported property [Foo]")]),
+ ("type-object", [{"Type": {"a": 1}, "UrlRewriteConfig": {"Rewrites": [_cfn_rewrite()]}}],
+ [(f"{_T0}/Type", "Property [Type] expected type: String, found: JSONObject")]),
+ ("replace-object",
+ [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [{"Regex": "^/a$", "Replace": {"a": 1}}]}}],
+ [(f"{_T0}/UrlRewriteConfig/Rewrites/0/Replace", "Property [Replace] expected type: String, found: JSONObject")]),
+ ("missing-type-and-config", [{"Foo": "x"}],
+ _BOTH_CONFIGS_MISSING + [(_T0, "Required property [Type] not found"), (_T0, "Unsupported property [Foo]")]),
+ ("transforms-string", "x",
+ [("/Resources/R/Properties/Transforms", "Property [Transforms] expected type: JSONArray, found: String")]),
+ ("item-number", [5], [(_T0, "#/Transforms/0: #: 2 subschemas matched instead of one"),
+ (_T0, "Property [0] expected type: JSONObject, found: String")]),
+ ("item-array", [[_CFN_URL_REWRITE]], [(_T0, "#/Transforms/0: #: 2 subschemas matched instead of one"),
+ (_T0, "Property [0] expected type: JSONObject, found: JSONArray")]),
+ ("config-string", [{"Type": "url-rewrite", "UrlRewriteConfig": "x"}],
+ [(f"{_T0}/UrlRewriteConfig", "Property [UrlRewriteConfig] expected type: JSONObject, found: String")]),
+ ("config-array", [{"Type": "url-rewrite", "UrlRewriteConfig": [{"Rewrites": [_cfn_rewrite()]}]}],
+ [(f"{_T0}/UrlRewriteConfig", "Property [UrlRewriteConfig] expected type: JSONObject, found: JSONArray")]),
+ ("rewrites-string", [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": "x"}}],
+ [(f"{_T0}/UrlRewriteConfig/Rewrites", "Property [Rewrites] expected type: JSONArray, found: String")]),
+ ("rewrite-string", [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": ["x"]}}],
+ [(f"{_T0}/UrlRewriteConfig/Rewrites/0", "Property [0] expected type: JSONObject, found: String")]),
+ ("type-array", [{"Type": ["url-rewrite"], "UrlRewriteConfig": {"Rewrites": [_cfn_rewrite()]}}],
+ [(f"{_T0}/Type", "Property [Type] expected type: String, found: JSONArray")]),
+ ("regex-array", [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [{"Regex": ["a"], "Replace": "/b"}]}}],
+ [(f"{_T0}/UrlRewriteConfig/Rewrites/0/Regex", "Property [Regex] expected type: String, found: JSONArray")]),
+ ("identical-missing-config", [{"Type": "url-rewrite"}, {"Type": "url-rewrite"}],
+ _BOTH_CONFIGS_MISSING + [("/Resources/R/Properties/Transforms/1", f"Required property [{c}] not found")
+ for c in ("HostHeaderRewriteConfig", "UrlRewriteConfig")]
+ + [("/Resources/R/Properties/Transforms", "#/Transforms: array items are not unique")]),
+ ("identical-with-unsupported", [{**_CFN_URL_REWRITE, "Foo": "x"}] * 2,
+ [(_T0, "Unsupported property [Foo]"), ("/Resources/R/Properties/Transforms/1", "Unsupported property [Foo]"),
+ ("/Resources/R/Properties/Transforms", "#/Transforms: array items are not unique")]),
+]
+
+
[email protected]("transforms, expected", [c[1:] for c in _CFN_SCHEMA_CASES],
+ ids=[c[0] for c in _CFN_SCHEMA_CASES])
+def test_cfn_elbv2_listener_rule_transforms_fail_schema_validation(cfn, transforms, expected):
+ """AWS: captured 2026-10-20 and 2026-10-21 (repeats elbv2:C50 missing-config,
+ wrong-config, host-missing-config; 2310-uncertainties U10:cfn-create,
+ 2310-uncertainties-3 W3:cfn-types, 2310-uncertainties-4 X2:cfn). Transforms
+ that break the resource schema fail the stack before anything is provisioned,
+ with one PROPERTY_VALIDATION event per problem."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-elbv2-txv-{uid}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_elbv2_template(uid, rule_transforms=transforms))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "ROLLBACK_COMPLETE"
+ events = [(e["ResourceStatus"], e.get("ResourceStatusReason"))
+ for e in reversed(cfn.describe_stack_events(StackName=stack_name)["StackEvents"])]
+ assert events[1:3] == [
+ ("CREATE_FAILED", f"Validation failed with {len(expected)} error(s). Call DescribeEvents to retrieve "
+ "the full list of issues with resource and property details, resolve each error, then retry the "
+ "operation."),
+ ("ROLLBACK_IN_PROGRESS", "Validation failure detected. See the operation's FAILED event for details."),
+ ]
+ assert _cfn_validation_errors(cfn, stack_name) == sorted(
+ ("R", "PROPERTY_VALIDATION", path, reason) for path, reason in expected)
+ assert cfn.describe_stack_resources(StackName=stack_name)["StackResources"] == []
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+_CFN_HANDLER_CASES = [
+ ("unknown-type", [{"Type": "path-rewrite", "UrlRewriteConfig": {"Rewrites": [_cfn_rewrite()]}}],
+ "1 validation error detected: Value 'path-rewrite' at 'transforms.1.member.type' failed to satisfy "
+ "constraint: Member must satisfy enum value set: [url-rewrite, host-header-rewrite]"),
+ ("duplicate-type", [_CFN_URL_REWRITE, {"Type": "url-rewrite", "UrlRewriteConfig": {
+ "Rewrites": [_cfn_rewrite("^/b$")]}}], "A rule can only have one transform of each type"),
+ ("two-rewrites", [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [
+ _cfn_rewrite(), _cfn_rewrite("^/c$", "/d")]}}], "Rule transforms must have exactly one Rewrite"),
+ ("no-rewrites", [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": []}}],
+ "Rule transforms must have exactly one Rewrite"),
+ ("empty-regex", [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [_cfn_rewrite(regex="")]}}],
+ "A transform rewrite Regex value must be between 1 and 1024 characters in length"),
+ ("long-regex", [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [_cfn_rewrite(regex="a" * 1025)]}}],
+ "A transform rewrite Regex value must be between 1 and 1024 characters in length"),
+ ("long-replace", [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [_cfn_rewrite(replace="a" * 1025)]}}],
+ "A transform rewrite Replace value must be between 0 and 1024 characters in length"),
+ ("invalid-regex", [{"Type": "url-rewrite", "UrlRewriteConfig": {"Rewrites": [_cfn_rewrite(regex="([")]}}],
+ "One or more provided transform rewrite Regex values are invalid"),
+ ("type-number", [{"Type": 5, "UrlRewriteConfig": {"Rewrites": [_cfn_rewrite()]}}],
+ "1 validation error detected: Value '5' at 'transforms.1.member.type' failed to satisfy "
+ "constraint: Member must satisfy enum value set: [url-rewrite, host-header-rewrite]"),
+]
+
+
[email protected]("transforms, message", [c[1:] for c in _CFN_HANDLER_CASES],
+ ids=[c[0] for c in _CFN_HANDLER_CASES])
+def test_cfn_elbv2_listener_rule_refused_transforms_fail_the_resource(cfn, transforms, message):
+ """AWS: captured 2026-10-20 and 2026-10-21 (elbv2-rule-transforms C50, repeats
+ elbv2:C50, 2310-uncertainties U10:cfn-create invalid-regex, 2310-uncertainties-3
+ W3:cfn-types type-number, empty-rewrites, unknown-type). Transforms that pass
+ the schema reach the handler, which fails the rule with the API's message."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-elbv2-txh-{uid}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_elbv2_template(uid, rule_transforms=transforms))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "ROLLBACK_COMPLETE"
+ [reason] = _cfn_rule_reasons(cfn, stack_name, "CREATE_FAILED")
+ assert _cfn_handler_reason(message).match(reason), reason
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_elbv2_listener_rule_refused_transform_updates_roll_back(cfn, elbv2):
+ """AWS: captured 2026-10-20 and 2026-10-21 (elbv2-rule-transforms C51, repeats
+ elbv2:C51 identical-items and different-regex, 2310-uncertainties U10:cfn-update).
+ Schema problems fail the update before the rule is touched; the rest fail the
+ rule with the handler's reason. Either way the rule keeps its transforms."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-elbv2-txu-{uid}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_elbv2_template(uid, rule_transforms=[_CFN_HOST_REWRITE]))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ rule_arn = _output(stack, "RuleRef")
+ other_host = {"Type": "host-header-rewrite", "HostHeaderRewriteConfig": {
+ "Rewrites": [_cfn_rewrite("^b$", "c")]}}
+ for transforms, schema, message in (
+ ([_CFN_HOST_REWRITE, _CFN_HOST_REWRITE],
+ [("/Resources/R/Properties/Transforms", "#/Transforms: array items are not unique")], None),
+ ([{"Type": "url-rewrite"}], _BOTH_CONFIGS_MISSING, None),
+ ([{"Type": "host-header-rewrite", "HostHeaderRewriteConfig": {"Rewrites": [{"Regex": "^a$"}]}}],
+ [(f"{_T0}/HostHeaderRewriteConfig/Rewrites/0", "Required property [Replace] not found")], None),
+ ([_CFN_HOST_REWRITE, other_host], None, "A rule can only have one transform of each type"),
+ ([{"Type": "host-header-rewrite", "HostHeaderRewriteConfig": {"Rewrites": [_cfn_rewrite("([")]}}],
+ None, "One or more provided transform rewrite Regex values are invalid")):
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_elbv2_template(uid, rule_transforms=transforms))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ events = [(e["ResourceStatus"], e.get("ResourceStatusReason"))
+ for e in cfn.describe_stack_events(StackName=stack_name)["StackEvents"]
+ if e["LogicalResourceId"] == stack_name]
+ if schema:
+ assert ("UPDATE_FAILED", f"Validation failed with {len(schema)} error(s). Call DescribeEvents to "
+ "retrieve the full list of issues with resource and property details, resolve each error, "
+ "then retry the operation.") in events
+ assert ("UPDATE_ROLLBACK_IN_PROGRESS",
+ "Validation failure detected. See operation's FAILED event for details.") in events
+ latest = [e for e in cfn.describe_events(StackName=stack_name)["OperationEvents"]
+ if e["EventType"] == "VALIDATION_ERROR"]
+ operation = latest[0]["OperationId"]
+ assert sorted((e["ValidationPath"], e["ValidationStatusReason"]) for e in latest
+ if e["OperationId"] == operation) == sorted(schema)
+ else:
+ assert _cfn_handler_reason(message).match(_cfn_rule_reasons(cfn, stack_name, "UPDATE_FAILED")[0])
+ assert ("UPDATE_ROLLBACK_IN_PROGRESS", "The following resource(s) failed to update: [R]. ") in events
+ assert _output(_wait_stack(cfn, stack_name), "RuleRef") == rule_arn
+ assert elbv2.describe_rules(RuleArns=[rule_arn])["Rules"][0]["Transforms"] == [_CFN_HOST_REWRITE]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
def test_cfn_elbv2_listener_update_changes_port_protocol_and_actions(cfn, elbv2):
"""Port, Protocol and DefaultActions are all "Update requires: No
interruption" on the Listener resource reference, so a change to any of