Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(waf): support WAFv2 RegexPatternSet operations (#2212)
Kiran Malsettyeabae86126b2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 103ecc3b..56152223 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added+- **WAF v2 — regex pattern sets** — `CreateRegexPatternSet`, `GetRegexPatternSet`, `UpdateRegexPatternSet`, `DeleteRegexPatternSet` and `ListRegexPatternSets` now manage regional and CloudFront-scoped regex pattern sets, with their ARN (`regexpatternset`), tags and `LockToken` checks on update and delete (`WAFOptimisticLockException` for a stale token), as AWS does. Web ACL and rule group rules are stored as sent, so a `RegexPatternSetReferenceStatement` pointing at a pattern set ARN round-trips; the statement is not evaluated, as MiniStack does not inspect requests.### Fixed- **IoT — device certificates take the mode of their CA** — a device certificate registered under a CA in `SNI_ONLY` mode, with or without `caCertificatePem`, or created by just-in-time registration reported `certificateMode` `DEFAULT`; it now takes its CA's mode, and RegisterCertificateWithoutCA stays `SNI_ONLY`. Contributed by @iot-rocket.- **IoT — deletes of unknown resources and `DeleteThing` `expectedVersion`** — `DeleteThing`, `DeleteThingType`, `DeleteThingGroup`, `RemoveThingFromThingGroup` with an unknown group and `DetachPolicy` with an unknown policy answered `ResourceNotFoundException`, and `DeleteThing` ignored `expectedVersion`; they now answer 200 as AWS does, and `DeleteThing` refuses a wrong `expectedVersion` with `VersionConflictException` before the attached-principal check. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex 9f622d2e..4fdc2596 100644--- a/README.md+++ b/README.md@@ -436,7 +436,7 @@ subnet = ec2.create_subnet(| **Transcribe** | StartTranscriptionJob, GetTranscriptionJob, ListTranscriptionJobs, DeleteTranscriptionJob | Batch transcription jobs only; streaming is a separate endpoint (`transcribestreaming`). All four operations verified against botocore `transcribe-2017-10-26`. A job starts `IN_PROGRESS` with `StartTime` set, as on AWS, and reaches `COMPLETED` over two seconds; `QUEUED`, which AWS reaches only for a request that opted into job queueing (`JobExecutionSettings.AllowDeferredExecution`) while the account is at its concurrent job limit, is not modelled; the media object is read from MiniStack S3 via an `s3://`, path-style or virtual-hosted HTTPS URI, and an unreadable URI fails the job with a `FailureReason` rather than erroring at `Start`, as on AWS; the transcript is written back to S3 in the real result format (`results.transcripts`, word-level `results.items`, `results.audio_segments`, plus `results.segments` and `results.speaker_labels` when the matching `Settings` are set) at `OutputBucketName`/`OutputKey`, or to an auto-created `ministack-transcribe-output` bucket. `IdentifyLanguage` and `IdentifyMultipleLanguages` resolve a language on completion, `ContentRedaction` controls whether a `redacted-` copy replaces or accompanies the transcript, and `Subtitles` writes WebVTT and SubRip files, redacted alongside the transcript when redaction is on. Reaching a terminal state publishes a `Transcribe Job State Change` event, so EventBridge rules downstream of a job fire. There is no speech recognition, so the transcript is deterministic canned text keyed on a digest of the media URI || **Translate** | StartTextTranslationJob, DescribeTextTranslationJob, ListTextTranslationJobs, StopTextTranslationJob | Batch text translation jobs only; the synchronous `TranslateText` / `TranslateDocument` pair and the custom terminology / parallel data families are not implemented. All four operations verified against botocore `translate-2017-07-01`. Jobs walk `SUBMITTED` → `IN_PROGRESS` → `COMPLETED` over `TRANSLATE_JOB_RUN_SECONDS` (default 2, `0` completes immediately); every document under `InputDataConfig.S3Uri` is read from MiniStack S3 and written back to the rewritten output location AWS uses — `OutputDataConfig.S3Uri` is reported as `s3://<bucket>/<prefix><account-id>-TranslateText-<JobId>/` — as `<target-code>.<input name>`, with a `details/<code>.auxiliary-translation-details.json` summary per target language. `text/plain` is translated line by line, `text/html` keeps its markup and translates only text nodes, `application/x-xliff+xml` gets a populated `<target>` in every `<trans-unit>` plus `target-language` on every `<file>`, and the three Office ZIP types are copied through. A document that can't be read as its content type is counted in `JobDetails` and the job ends `COMPLETED_WITH_ERROR`; an empty or unreadable input location fails the job with a `Message` rather than erroring at `Start`. `ClientToken` is idempotent, `StopTextTranslationJob` reaches a running worker, and reaching a terminal state publishes a `Translate TextTranslationJob State Change` event, so EventBridge rules downstream of a job fire. There is no machine translation, so the output is deterministic canned text derived from the source || **MSK** | CreateCluster, ListClusters, DescribeCluster, DeleteCluster, GetBootstrapBrokers, ListNodes, CreateConfiguration, ListConfigurations, DescribeConfiguration, ListConfigurationRevisions, DescribeConfigurationRevision, BatchAssociateScramSecret, BatchDisassociateScramSecret, ListScramSecrets, TagResource, UntagResource, ListTagsForResource | Kafka control plane; `GetBootstrapBrokers` honors `MINISTACK_MSK_BOOTSTRAP` so clients route to a real broker you bring (Redpanda, Kafka, KRaft) — the Kafka wire protocol itself is not emulated |-| **WAF v2** | CreateWebACL, GetWebACL, UpdateWebACL, DeleteWebACL, ListWebACLs, AssociateWebACL, DisassociateWebACL, GetWebACLForResource, ListResourcesForWebACL, CreateIPSet, GetIPSet, UpdateIPSet, DeleteIPSet, ListIPSets, CreateRuleGroup, GetRuleGroup, UpdateRuleGroup, DeleteRuleGroup, ListRuleGroups, TagResource, UntagResource, ListTagsForResource, CheckCapacity, DescribeManagedRuleGroup | LockToken enforced on Update/Delete; resource associations tracked |+| **WAF v2** | CreateWebACL, GetWebACL, UpdateWebACL, DeleteWebACL, ListWebACLs, AssociateWebACL, DisassociateWebACL, GetWebACLForResource, ListResourcesForWebACL, CreateIPSet, GetIPSet, UpdateIPSet, DeleteIPSet, ListIPSets, CreateRegexPatternSet, GetRegexPatternSet, UpdateRegexPatternSet, DeleteRegexPatternSet, ListRegexPatternSets, CreateRuleGroup, GetRuleGroup, UpdateRuleGroup, DeleteRuleGroup, ListRuleGroups, TagResource, UntagResource, ListTagsForResource, CheckCapacity, DescribeManagedRuleGroup | LockToken enforced on Update/Delete; resource associations tracked || **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 |diff --git a/ministack/services/waf.py b/ministack/services/waf.pyindex 3d500c54..53e742a5 100644--- a/ministack/services/waf.py+++ b/ministack/services/waf.py@@ -6,6 +6,8 @@ JSON-based API via X-Amz-Target: AWSWAF_20190729.Supports: CreateWebACL, GetWebACL, UpdateWebACL, DeleteWebACL, ListWebACLs,AssociateWebACL, DisassociateWebACL, GetWebACLForResource, ListResourcesForWebACL,CreateIPSet, GetIPSet, UpdateIPSet, DeleteIPSet, ListIPSets,+ CreateRegexPatternSet, GetRegexPatternSet, UpdateRegexPatternSet,+ DeleteRegexPatternSet, ListRegexPatternSets,CreateRuleGroup, GetRuleGroup, UpdateRuleGroup, DeleteRuleGroup, ListRuleGroups,TagResource, UntagResource, ListTagsForResource,CheckCapacity, DescribeManagedRuleGroup.@@ -35,6 +37,7 @@ CLOUDFRONT_HOME_REGION = "us-east-1"_web_acls = AccountRegionScopedDict() # id -> webacl_ip_sets = AccountRegionScopedDict() # id -> ipset+_regex_pattern_sets = AccountRegionScopedDict() # id -> regexpatternset_rule_groups = AccountRegionScopedDict() # id -> rulegroup# AssociateWebACL is for regional application resources; CloudFront uses the# distribution configuration path. Keep this request-region scoped even though@@ -45,6 +48,7 @@ _waf_tags = AccountScopedDict() # resource_arn -> [tags]_WAF_RESOURCE_SCOPES = {"webacl": {"regional", "cloudfront", "global"},"ipset": {"regional", "global"},+ "regexpatternset": {"regional", "global"},"rulegroup": {"regional", "global"},}@@ -53,6 +57,7 @@ def get_state():return {"_web_acls": copy.deepcopy(_web_acls),"_ip_sets": copy.deepcopy(_ip_sets),+ "_regex_pattern_sets": copy.deepcopy(_regex_pattern_sets),"_rule_groups": copy.deepcopy(_rule_groups),"_associations": copy.deepcopy(_associations),"_waf_tags": copy.deepcopy(_waf_tags),@@ -69,6 +74,9 @@ def _restore_state(data):arn_rewrites = {}_restore_resource_store(_web_acls, data.get("_web_acls", {}), "webacl", arn_rewrites)_restore_resource_store(_ip_sets, data.get("_ip_sets", {}), "ipset", arn_rewrites)+ _restore_resource_store(+ _regex_pattern_sets, data.get("_regex_pattern_sets", {}), "regexpatternset", arn_rewrites+ )_restore_resource_store(_rule_groups, data.get("_rule_groups", {}), "rulegroup", arn_rewrites)_rewrite_nested_resource_arns(arn_rewrites)_restore_associations(data.get("_associations", {}), arn_rewrites)@@ -258,6 +266,7 @@ def _resource_store(resource_type):return {"webacl": _web_acls,"ipset": _ip_sets,+ "regexpatternset": _regex_pattern_sets,"rulegroup": _rule_groups,}[resource_type]@@ -320,6 +329,10 @@ def _ipset_arn(name, uid, scope="REGIONAL"):return _resource_arn("ipset", name, uid, scope)+def _regex_pattern_set_arn(name, uid, scope="REGIONAL"):+ return _resource_arn("regexpatternset", name, uid, scope)++def _rg_arn(name, uid, scope="REGIONAL"):return _resource_arn("rulegroup", name, uid, scope)@@ -356,7 +369,7 @@ def _parse_local_waf_arn(arn, allowed_types):return resource_type, (spec.account_id, region, uid), None-def _resolve_local_waf_resource_arn(arn, allowed_types=("webacl", "ipset", "rulegroup")):+def _resolve_local_waf_resource_arn(arn, allowed_types=("webacl", "ipset", "regexpatternset", "rulegroup")):resource_type, scoped_key, err = _parse_local_waf_arn(arn, allowed_types)if err:return None, err@@ -406,6 +419,11 @@ async def handle_request(method, path, headers, body, query_params):"UpdateIPSet": _update_ip_set,"DeleteIPSet": _delete_ip_set,"ListIPSets": _list_ip_sets,+ "CreateRegexPatternSet": _create_regex_pattern_set,+ "GetRegexPatternSet": _get_regex_pattern_set,+ "UpdateRegexPatternSet": _update_regex_pattern_set,+ "DeleteRegexPatternSet": _delete_regex_pattern_set,+ "ListRegexPatternSets": _list_regex_pattern_sets,"CreateRuleGroup": _create_rule_group,"GetRuleGroup": _get_rule_group,"UpdateRuleGroup": _update_rule_group,@@ -598,6 +616,84 @@ def _list_ip_sets(data):return json_response({"IPSets": sets, "NextMarker": None})+# ---------------------------------------------------------------------------+# RegexPatternSet+# ---------------------------------------------------------------------------++def _regex_pattern_set_body(rps):+ return {+ "ARN": rps["ARN"], "Id": rps["Id"], "Name": rps["Name"],+ "Description": rps.get("Description", ""),+ "RegularExpressionList": rps.get("RegularExpressionList", []),+ }+++def _create_regex_pattern_set(data):+ name = data.get("Name", "")+ scope = _normalize_scope(data.get("Scope", "REGIONAL"))+ uid = new_uuid()+ lock_token = new_uuid()+ arn = _regex_pattern_set_arn(name, uid, scope)+ _regex_pattern_sets.set_scoped(get_account_id(), _scope_home_region(scope), uid, {+ "ARN": arn, "Id": uid, "Name": name,+ "Description": data.get("Description", ""),+ "RegularExpressionList": data.get("RegularExpressionList", []),+ "LockToken": lock_token,+ "Scope": scope,+ })+ _waf_tags[arn] = data.get("Tags", [])+ return json_response({"Summary": {"ARN": arn, "Id": uid, "Name": name,+ "Description": data.get("Description", ""),+ "LockToken": lock_token}})+++def _get_regex_pattern_set(data):+ uid = data.get("Id", "")+ rps = _resource_from_scope(_regex_pattern_sets, uid, data.get("Scope", "REGIONAL"))+ if not rps:+ return _waf_err("WAFNonexistentItemException", f"RegexPatternSet {uid} not found")+ return json_response({"RegexPatternSet": _regex_pattern_set_body(rps), "LockToken": rps["LockToken"]})+++def _update_regex_pattern_set(data):+ uid = data.get("Id", "")+ rps = _resource_from_scope(_regex_pattern_sets, uid, data.get("Scope", "REGIONAL"))+ if not rps:+ return _waf_err("WAFNonexistentItemException", f"RegexPatternSet {uid} not found")+ if data.get("LockToken", "") != rps["LockToken"]:+ return _waf_err("WAFOptimisticLockException",+ "The resource you are trying to update has been modified by another request.")+ rps["Description"] = data.get("Description", rps.get("Description", ""))+ rps["RegularExpressionList"] = data.get("RegularExpressionList", rps["RegularExpressionList"])+ rps["LockToken"] = new_uuid()+ return json_response({"NextLockToken": rps["LockToken"]})+++def _delete_regex_pattern_set(data):+ uid = data.get("Id", "")+ scope = data.get("Scope", "REGIONAL")+ rps = _resource_from_scope(_regex_pattern_sets, uid, scope)+ if not rps:+ return _waf_err("WAFNonexistentItemException", f"RegexPatternSet {uid} not found")+ if data.get("LockToken", "") != rps["LockToken"]:+ return _waf_err("WAFOptimisticLockException",+ "The resource you are trying to delete has been modified by another request.")+ arn = rps["ARN"]+ _regex_pattern_sets.pop_scoped(get_account_id(), _scope_home_region(scope), uid, None)+ _waf_tags.pop(arn, None)+ return json_response({})+++def _list_regex_pattern_sets(data):+ scope = _normalize_scope(data.get("Scope", "REGIONAL"))+ sets = [+ {"ARN": r["ARN"], "Id": r["Id"], "Name": r["Name"],+ "Description": r.get("Description", ""), "LockToken": r["LockToken"]}+ for r in _values_for_scope(_regex_pattern_sets, scope) if r.get("Scope", "REGIONAL") == scope+ ]+ return json_response({"RegexPatternSets": sets, "NextMarker": None})++# ---------------------------------------------------------------------------# RuleGroup# ---------------------------------------------------------------------------@@ -719,6 +815,7 @@ def _describe_managed_rule_group(data):def reset():_web_acls.clear()_ip_sets.clear()+ _regex_pattern_sets.clear()_rule_groups.clear()_associations.clear()_waf_tags.clear()diff --git a/tests/test_waf.py b/tests/test_waf.pyindex 470c5f78..60a5c2f1 100644--- a/tests/test_waf.py+++ b/tests/test_waf.py@@ -335,6 +335,123 @@ def test_waf_ip_set_crud(wafv2):ids2 = [s["Id"] for s in lst2["IPSets"]]assert uid not in ids2+def test_waf_regex_pattern_set_crud(wafv2):+ resp = wafv2.create_regex_pattern_set(+ Name="test-regex",+ Scope="REGIONAL",+ Description="first",+ RegularExpressionList=[{"RegexString": "^/admin"}],+ )+ summary = resp["Summary"]+ uid = summary["Id"]+ assert summary["Name"] == "test-regex"+ assert summary["Description"] == "first"+ assert ":regional/regexpatternset/test-regex/" in summary["ARN"]++ get_resp = wafv2.get_regex_pattern_set(Name="test-regex", Scope="REGIONAL", Id=uid)+ assert get_resp["RegexPatternSet"]["RegularExpressionList"] == [{"RegexString": "^/admin"}]+ assert get_resp["RegexPatternSet"]["ARN"] == summary["ARN"]+ assert "LockToken" not in get_resp["RegexPatternSet"]++ upd = wafv2.update_regex_pattern_set(+ Name="test-regex",+ Scope="REGIONAL",+ Id=uid,+ LockToken=get_resp["LockToken"],+ RegularExpressionList=[{"RegexString": "^/api"}, {"RegexString": "^/v2"}],+ )+ assert "NextLockToken" in upd+ updated = wafv2.get_regex_pattern_set(Name="test-regex", Scope="REGIONAL", Id=uid)+ assert len(updated["RegexPatternSet"]["RegularExpressionList"]) == 2+ assert updated["RegexPatternSet"]["Description"] == "first"++ lst = wafv2.list_regex_pattern_sets(Scope="REGIONAL")+ assert uid in [s["Id"] for s in lst["RegexPatternSets"]]++ wafv2.delete_regex_pattern_set(Name="test-regex", Scope="REGIONAL", Id=uid, LockToken=upd["NextLockToken"])+ lst2 = wafv2.list_regex_pattern_sets(Scope="REGIONAL")+ assert uid not in [s["Id"] for s in lst2["RegexPatternSets"]]+++def test_waf_regex_pattern_set_stale_lock_token_rejected(wafv2):+ from botocore.exceptions import ClientError++ resp = wafv2.create_regex_pattern_set(+ Name="lock-regex",+ Scope="REGIONAL",+ RegularExpressionList=[{"RegexString": "a"}],+ )+ uid = resp["Summary"]["Id"]+ lock = resp["Summary"]["LockToken"]+ wafv2.update_regex_pattern_set(+ Name="lock-regex", Scope="REGIONAL", Id=uid, LockToken=lock,+ RegularExpressionList=[{"RegexString": "b"}],+ )++ with pytest.raises(ClientError) as exc:+ wafv2.update_regex_pattern_set(+ Name="lock-regex", Scope="REGIONAL", Id=uid, LockToken=lock,+ RegularExpressionList=[{"RegexString": "c"}],+ )+ assert exc.value.response["Error"]["Code"] == "WAFOptimisticLockException"++ with pytest.raises(ClientError) as exc:+ wafv2.delete_regex_pattern_set(Name="lock-regex", Scope="REGIONAL", Id=uid, LockToken=lock)+ assert exc.value.response["Error"]["Code"] == "WAFOptimisticLockException"+++def test_waf_regex_pattern_set_tags_and_not_found(wafv2):+ from botocore.exceptions import ClientError++ resp = wafv2.create_regex_pattern_set(+ Name="tag-regex",+ Scope="REGIONAL",+ RegularExpressionList=[],+ Tags=[{"Key": "env", "Value": "test"}],+ )+ arn = resp["Summary"]["ARN"]+ tags = wafv2.list_tags_for_resource(ResourceARN=arn)["TagInfoForResource"]["TagList"]+ assert any(t["Key"] == "env" for t in tags)++ with pytest.raises(ClientError) as exc:+ wafv2.get_regex_pattern_set(Name="missing", Scope="REGIONAL", Id="00000000-0000-0000-0000-000000000000")+ assert exc.value.response["Error"]["Code"] == "WAFNonexistentItemException"+++def test_waf_web_acl_rule_can_reference_regex_pattern_set(wafv2):+ regex = wafv2.create_regex_pattern_set(+ Name="ref-regex",+ Scope="CLOUDFRONT",+ RegularExpressionList=[{"RegexString": "^/[^/]+/(img|css|scripts)/"}],+ )+ arn = regex["Summary"]["ARN"]+ assert ":global/regexpatternset/ref-regex/" in arn++ rule = {+ "Name": "static-resources",+ "Priority": 0,+ "Statement": {+ "RegexPatternSetReferenceStatement": {+ "ARN": arn,+ "FieldToMatch": {"UriPath": {}},+ "TextTransformations": [{"Priority": 0, "Type": "NONE"}],+ }+ },+ "Action": {"Allow": {}},+ "VisibilityConfig": {"SampledRequestsEnabled": True, "CloudWatchMetricsEnabled": False, "MetricName": "static"},+ }+ acl = wafv2.create_web_acl(+ Name="ref-acl",+ Scope="CLOUDFRONT",+ DefaultAction={"Block": {}},+ Rules=[rule],+ VisibilityConfig={"SampledRequestsEnabled": True, "CloudWatchMetricsEnabled": False, "MetricName": "ref"},+ )+ got = wafv2.get_web_acl(Name="ref-acl", Scope="CLOUDFRONT", Id=acl["Summary"]["Id"])+ stmt = got["WebACL"]["Rules"][0]["Statement"]["RegexPatternSetReferenceStatement"]+ assert stmt["ARN"] == arn++def test_waf_rule_group_crud(wafv2):resp = wafv2.create_rule_group(Name="test-rg",