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: ELBv2/ALB - control plane + ALB+Lambda data plan, 673 tests (v1.1.4) (#30)
Peter Etherington2eaba135ca8e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7604db81..316ddcb5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,32 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [1.1.4] — 2026-03-30++### Added+- **Amazon ELBv2 / ALB** (`ministack/services/alb.py`) — full control plane + data plane+ - **Load Balancers**: `CreateLoadBalancer`, `DescribeLoadBalancers`, `DeleteLoadBalancer`, `DescribeLoadBalancerAttributes`, `ModifyLoadBalancerAttributes`+ - **Target Groups**: `CreateTargetGroup`, `DescribeTargetGroups`, `ModifyTargetGroup`, `DeleteTargetGroup`, `DescribeTargetGroupAttributes`, `ModifyTargetGroupAttributes`+ - **Listeners**: `CreateListener`, `DescribeListeners`, `ModifyListener`, `DeleteListener`+ - **Rules**: `CreateRule`, `DescribeRules`, `ModifyRule`, `DeleteRule`, `SetRulePriorities`+ - **Targets**: `RegisterTargets`, `DeregisterTargets`, `DescribeTargetHealth`+ - **Tags**: `AddTags`, `RemoveTags`, `DescribeTags`+ - **Data plane — ALB→Lambda live traffic routing**+ - Incoming HTTP requests matched against configured listener rules (priority order)+ - Rule conditions supported: `path-pattern`, `host-header`, `http-method`, `query-string`, `http-header` (fnmatch glob matching)+ - Actions supported: `forward` (to target group), `fixed-response`, `redirect` (301/302 with `#{host}`/`#{path}`/`#{port}` substitution)+ - `TargetType=lambda` target groups: builds ALB event payload (httpMethod, path, queryStringParameters, multiValueQueryStringParameters, headers, multiValueHeaders, body, isBase64Encoded, requestContext.elb) and invokes Lambda via the in-process Lambda runtime; translates Lambda response (statusCode, headers, multiValueHeaders, body, isBase64Encoded) back to HTTP+ - Two addressing modes — no DNS or `/etc/hosts` changes required for local testing:+ - **Host-header**: `Host: {lb-name}.alb.localhost[:{port}]` or the ALB's exact `DNSName`+ - **Path prefix**: `/_alb/{lb-name}/path` (rewrites path before rule evaluation)+ - Query/XML protocol via `Action=` parameter; credential scope `elasticloadbalancing`+ - 10 control-plane integration tests + 7 data-plane integration tests++### Tests+- 688 integration tests — all passing++---+## [1.1.3] — 2026-03-30### Addeddiff --git a/Makefile b/Makefileindex c2aa1d10..cb7a010c 100644--- a/Makefile+++ b/Makefile@@ -4,6 +4,12 @@ IMAGE_NAME := ministackCONTAINER_NAME := ministackPORT := 4566+# Override any shell AWS credentials so make test is self-contained+export AWS_ACCESS_KEY_ID := test+export AWS_SECRET_ACCESS_KEY := test+export AWS_DEFAULT_REGION := us-east-1+unexport AWS_PROFILE+build:docker build -t $(IMAGE_NAME) .@@ -32,8 +38,16 @@ logs:health:@curl -s http://localhost:$(PORT)/_localstack/health | python3 -m json.tool-test: run- @sleep 2+test: stop run+ @echo "Waiting for ministack to be ready..."+ @READY=0; \+ for i in $$(seq 1 30); do \+ if curl -sf http://localhost:$(PORT)/_localstack/health > /dev/null 2>&1; then \+ echo "Ready after $$i second(s)."; READY=1; break; \+ fi; \+ sleep 1; \+ done; \+ if [ "$$READY" = "0" ]; then echo "ERROR: ministack did not start within 30s" >&2; exit 1; fi@echo "=== S3 ==="aws --endpoint-url=http://localhost:$(PORT) s3 mb s3://test-bucketecho "hello" | aws --endpoint-url=http://localhost:$(PORT) s3 cp - s3://test-bucket/hello.txt@@ -72,6 +86,35 @@ test: run@echo "=== Lambda ==="aws --endpoint-url=http://localhost:$(PORT) lambda list-functions@echo ""+ @echo "=== ALB/ELBv2 ==="+ @python3 -c "\+import zipfile; \+z = zipfile.ZipFile('/tmp/ms-alb-test.zip', 'w'); \+z.writestr('index.py', 'import json\ndef handler(event, context):\n return {\"statusCode\": 200, \"headers\": {\"Content-Type\": \"application/json\"}, \"body\": json.dumps({\"ok\": True, \"path\": event[\"path\"]})}\n'); \+z.close(); \+print('Lambda zip created')"+ aws --endpoint-url=http://localhost:$(PORT) lambda create-function \+ --function-name alb-test-fn --runtime python3.9 \+ --handler index.handler \+ --role arn:aws:iam::000000000000:role/role \+ --zip-file fileb:///tmp/ms-alb-test.zip+ @LB_ARN=$$(aws --endpoint-url=http://localhost:$(PORT) elbv2 create-load-balancer \+ --name test-alb --query 'LoadBalancers[0].LoadBalancerArn' --output text) && \+ TG_ARN=$$(aws --endpoint-url=http://localhost:$(PORT) elbv2 create-target-group \+ --name test-tg --target-type lambda --protocol HTTP --port 80 \+ --vpc-id vpc-00000001 --query 'TargetGroups[0].TargetGroupArn' --output text) && \+ FN_ARN=$$(aws --endpoint-url=http://localhost:$(PORT) lambda get-function \+ --function-name alb-test-fn --query 'Configuration.FunctionArn' --output text) && \+ aws --endpoint-url=http://localhost:$(PORT) elbv2 register-targets \+ --target-group-arn $$TG_ARN --targets Id=$$FN_ARN && \+ aws --endpoint-url=http://localhost:$(PORT) elbv2 create-listener \+ --load-balancer-arn $$LB_ARN --protocol HTTP --port 80 \+ --default-actions Type=forward,TargetGroupArn=$$TG_ARN && \+ RESULT=$$(curl -sf http://localhost:$(PORT)/_alb/test-alb/ping) && \+ echo "ALB response: $$RESULT" && \+ echo "$$RESULT" | python3 -c "import sys,json; d=json.load(sys.stdin); assert d['ok'] and d['path']=='/ping', f'Unexpected response: {d}'" && \+ echo "ALB -> Lambda routing: OK"+ @echo ""@echo "=== All tests passed ==="clean: stopdiff --git a/README.md b/README.mdindex d549d982..a35b2d2d 100644--- a/README.md+++ b/README.md@@ -223,6 +223,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, TagResource, UntagResource, ListTagsForResource | Full ASL interpreter; Retry/Catch; waitForTaskToken; Activities (worker pattern); Pass/Task/Choice/Wait/Succeed/Fail/Map/Parallel || **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, TagResource, UntagResource, GetTags | HTTP API (v2) protocol; Lambda proxy (AWS_PROXY) and HTTP proxy (HTTP_PROXY) integrations; data plane via `{apiId}.execute-api.localhost`; `{param}` and `{proxy+}` path matching; JWT/Lambda authorizer CRUD || **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, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost`; resource tree with `{param}` and `{proxy+}` path matching; JSON Patch for all PATCH operations; state persistence |+| **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, 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` actions; data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix |### Infrastructure Services (with real Docker execution)@@ -562,6 +563,7 @@ config:| **Cognito** | ✅ | ✅ | ✅ || **EC2** | ✅ | ✅ | ✅ || **EMR** | ✅ | Paid | ✅ |+| **ELBv2 / ALB** | ✅ | ✅ | ✅ || **EBS** | ✅ | Paid | ✅ || **EFS** | ✅ | Paid | ✅ || CloudFormation | ❌ | partial | ✅ |diff --git a/ministack/app.py b/ministack/app.pyindex 202fe22f..67fd6af8 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -25,6 +25,7 @@ from ministack.core.persistence import save_all, load_state, PERSIST_STATEfrom ministack.services import s3, sqs, sns, dynamodb, lambda_svc, secretsmanager, cloudwatch_logsfrom ministack.services import ssm, eventbridge, kinesis, cloudwatch, ses, stepfunctionsfrom ministack.services import ecs, rds, elasticache, glue, athena+from ministack.services import albfrom ministack.services import ec2from ministack.services import apigatewayfrom ministack.services import firehose@@ -71,6 +72,7 @@ SERVICE_HANDLERS = {"cognito-identity": cognito.handle_request,"ec2": ec2.handle_request,"elasticmapreduce": emr.handle_request,+ "elasticloadbalancing": alb.handle_request,"elasticfilesystem": efs.handle_request,}@@ -86,6 +88,8 @@ SERVICE_NAME_ALIASES = {"route53": "route53","cognito-idp": "cognito-idp","cognito-identity": "cognito-identity",+ "elbv2": "elasticloadbalancing",+ "elb": "elasticloadbalancing",}@@ -122,7 +126,7 @@ BANNER = r"""Services: S3, SQS, SNS, DynamoDB, Lambda, IAM, STS, SecretsManager, CloudWatch Logs,SSM, EventBridge, Kinesis, CloudWatch, SES, Step Functions,ECS, RDS, ElastiCache, Glue, Athena, API Gateway, Firehose, Route53,- Cognito, EC2, EMR, EFS+ Cognito, EC2, EMR, EBS, EFS, ALB/ELBv2"""@@ -214,6 +218,41 @@ async def app(scope, receive, send):await _send_response(send, status, resp_headers, resp_body)return+ # ALB data-plane — two addressing modes:+ # 1. Host header matches a configured ALB DNS name or {lb-name}.alb.localhost+ # 2. Path prefix /_alb/{lb-name}/... (no DNS config needed for local testing)+ _alb_lb = alb.find_lb_for_host(host)+ if _alb_lb is None and path.startswith("/_alb/"):+ _alb_path_parts = path[6:].split("/", 1)+ _alb_lb = alb._find_lb_by_name(_alb_path_parts[0])+ if _alb_lb:+ path = "/" + _alb_path_parts[1] if len(_alb_path_parts) > 1 else "/"++ if _alb_lb:+ _alb_port = 80+ if ":" in host:+ try:+ _alb_port = int(host.rsplit(":", 1)[-1])+ except ValueError:+ pass+ try:+ status, resp_headers, resp_body = await alb.dispatch_request(+ _alb_lb, method, path, headers, body, query_params, _alb_port+ )+ except Exception as e:+ logger.exception(f"Error in ALB data-plane dispatch: {e}")+ status, resp_headers, resp_body = (+ 500, {"Content-Type": "application/json"},+ json.dumps({"message": str(e)}).encode(),+ )+ resp_headers.update({+ "Access-Control-Allow-Origin": "*",+ "x-amzn-requestid": request_id,+ "x-amz-request-id": request_id,+ })+ await _send_response(send, status, resp_headers, resp_body)+ return+# Virtual-hosted S3: {bucket}.localhost[:{port}] — rewrite to path-style and forward to S3_s3_vhost = _S3_VHOST_RE.match(host)if _s3_vhost and not _execute_match:@@ -380,6 +419,7 @@ def _reset_all_state():(cognito, cognito.reset),(ec2, ec2.reset),(emr, emr.reset),+ (alb, alb.reset),(efs, efs.reset),]:try:diff --git a/ministack/core/router.py b/ministack/core/router.pyindex b41297ff..5cf3b1c9 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -132,6 +132,9 @@ SERVICE_PATTERNS = {r"Action=.*Image", r"Action=.*Tag", r"Action=.*InternetGateway",r"Action=.*AvailabilityZone"],},+ "elasticloadbalancing": {+ "host_patterns": [r"elasticloadbalancing\."],+ },}@@ -175,6 +178,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"cognito-idp": "cognito-idp","cognito-identity": "cognito-identity","elasticmapreduce": "elasticmapreduce",+ "elasticloadbalancing": "elasticloadbalancing","elasticfilesystem": "elasticfilesystem",}if svc_name in scope_map:@@ -311,6 +315,33 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"AttachNetworkInterface": "ec2", "DetachNetworkInterface": "ec2","CreateVpcEndpoint": "ec2", "DeleteVpcEndpoints": "ec2","DescribeVpcEndpoints": "ec2",+ # ELBv2 / ALB actions+ "CreateLoadBalancer": "elasticloadbalancing",+ "DescribeLoadBalancers": "elasticloadbalancing",+ "DeleteLoadBalancer": "elasticloadbalancing",+ "DescribeLoadBalancerAttributes": "elasticloadbalancing",+ "ModifyLoadBalancerAttributes": "elasticloadbalancing",+ "CreateTargetGroup": "elasticloadbalancing",+ "DescribeTargetGroups": "elasticloadbalancing",+ "ModifyTargetGroup": "elasticloadbalancing",+ "DeleteTargetGroup": "elasticloadbalancing",+ "DescribeTargetGroupAttributes": "elasticloadbalancing",+ "ModifyTargetGroupAttributes": "elasticloadbalancing",+ "CreateListener": "elasticloadbalancing",+ "DescribeListeners": "elasticloadbalancing",+ "ModifyListener": "elasticloadbalancing",+ "DeleteListener": "elasticloadbalancing",+ "CreateRule": "elasticloadbalancing",+ "DescribeRules": "elasticloadbalancing",+ "ModifyRule": "elasticloadbalancing",+ "DeleteRule": "elasticloadbalancing",+ "SetRulePriorities": "elasticloadbalancing",+ "RegisterTargets": "elasticloadbalancing",+ "DeregisterTargets": "elasticloadbalancing",+ "DescribeTargetHealth": "elasticloadbalancing",+ "AddTags": "elasticloadbalancing",+ "RemoveTags": "elasticloadbalancing",+ "DescribeTags": "elasticloadbalancing",# EBS Volumes"CreateVolume": "ec2", "DeleteVolume": "ec2", "DescribeVolumes": "ec2","DescribeVolumeStatus": "ec2", "AttachVolume": "ec2", "DetachVolume": "ec2",diff --git a/ministack/services/alb.py b/ministack/services/alb.pynew file mode 100644index 00000000..2d4e108a--- /dev/null+++ b/ministack/services/alb.py@@ -0,0 +1,1055 @@+"""+ALB / ELBv2 (Elastic Load Balancing v2) Service Emulator.+Query API (Action=...) with XML responses. In-memory only.++Supports:+ Load Balancers: CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer,+ ModifyLoadBalancerAttributes, DescribeLoadBalancerAttributes+ Target Groups: CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup,+ DeleteTargetGroup, DescribeTargetGroupAttributes,+ ModifyTargetGroupAttributes+ Listeners: CreateListener, DescribeListeners, ModifyListener, DeleteListener+ Rules: CreateRule, DescribeRules, ModifyRule, DeleteRule,+ SetRulePriorities+ Target Registration: RegisterTargets, DeregisterTargets, DescribeTargetHealth+ Tags: AddTags, RemoveTags, DescribeTags+"""++import base64+import fnmatch+import json+import os+import random+import string+import time+import logging+from urllib.parse import parse_qs++from ministack.core.responses import new_uuid++logger = logging.getLogger("alb")++ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")+REGION = os.environ.get("MINISTACK_REGION", "us-east-1")+NS = "http://elasticloadbalancing.amazonaws.com/doc/2015-12-01/"++# ---------------------------------------------------------------------------+# State+# ---------------------------------------------------------------------------+_lbs: dict = {} # lb_arn -> LB record+_tgs: dict = {} # tg_arn -> TG record+_listeners: dict = {} # l_arn -> Listener record+_rules: dict = {} # r_arn -> Rule record+_targets: dict = {} # tg_arn -> [target dict]+_tags: dict = {} # res_arn -> [{Key, Value}]+_lb_attrs: dict = {} # lb_arn -> [{Key, Value}]+_tg_attrs: dict = {} # tg_arn -> [{Key, Value}]++# ---------------------------------------------------------------------------+# Small helpers+# ---------------------------------------------------------------------------++def _p(params, key, default=""):+ val = params.get(key, [default])+ return (val[0] if val else default) if isinstance(val, list) else val+++def _parse_member_list(params, prefix):+ items, i = [], 1+ while True:+ v = _p(params, f"{prefix}.member.{i}")+ if not v:+ break+ items.append(v)+ i += 1+ return items+++def _parse_tags(params):+ tags, i = [], 1+ while True:+ k = _p(params, f"Tags.member.{i}.Key")+ if not k:+ break+ tags.append({"Key": k, "Value": _p(params, f"Tags.member.{i}.Value")})+ i += 1+ return tags+++def _parse_actions(params, prefix="DefaultActions"):+ actions, i = [], 1+ while True:+ t = _p(params, f"{prefix}.member.{i}.Type")+ if not t:+ break+ action = {"Type": t, "Order": int(_p(params, f"{prefix}.member.{i}.Order", str(i)))}+ tg = _p(params, f"{prefix}.member.{i}.TargetGroupArn")+ if tg:+ action["TargetGroupArn"] = tg+ rc_code = _p(params, f"{prefix}.member.{i}.RedirectConfig.StatusCode")+ if rc_code:+ action["RedirectConfig"] = {+ "Protocol": _p(params, f"{prefix}.member.{i}.RedirectConfig.Protocol", "#{protocol}"),+ "Port": _p(params, f"{prefix}.member.{i}.RedirectConfig.Port", "#{port}"),+ "Host": _p(params, f"{prefix}.member.{i}.RedirectConfig.Host", "#{host}"),+ "Path": _p(params, f"{prefix}.member.{i}.RedirectConfig.Path", "/#{path}"),+ "StatusCode": rc_code,+ }+ fr_code = _p(params, f"{prefix}.member.{i}.FixedResponseConfig.StatusCode")+ if fr_code:+ action["FixedResponseConfig"] = {+ "StatusCode": fr_code,+ "ContentType": _p(params, f"{prefix}.member.{i}.FixedResponseConfig.ContentType", "text/plain"),+ "MessageBody": _p(params, f"{prefix}.member.{i}.FixedResponseConfig.MessageBody", ""),+ }+ actions.append(action)+ i += 1+ return actions+++def _parse_conditions(params, prefix="Conditions"):+ conditions, i = [], 1+ while True:+ field = _p(params, f"{prefix}.member.{i}.Field")+ if not field:+ break+ values, j = [], 1+ while True:+ v = _p(params, f"{prefix}.member.{i}.Values.member.{j}")+ if not v:+ break+ values.append(v)+ j += 1+ conditions.append({"Field": field, "Values": values})+ i += 1+ return conditions+++def _parse_targets_param(params, prefix="Targets"):+ targets, i = [], 1+ while True:+ tid = _p(params, f"{prefix}.member.{i}.Id")+ if not tid:+ break+ t = {"Id": tid}+ port = _p(params, f"{prefix}.member.{i}.Port")+ if port:+ t["Port"] = int(port)+ targets.append(t)+ i += 1+ return targets+++def _now_iso():+ return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())+++def _short_id():+ return "".join(random.choices(string.ascii_lowercase + string.digits, k=16))++# ---------------------------------------------------------------------------+# XML builders+# ---------------------------------------------------------------------------++def _xml(status, action, inner):+ body = (+ f'<?xml version="1.0" encoding="UTF-8"?>'+ f'<{action}Response xmlns="{NS}">'+ f'<{action}Result>{inner}</{action}Result>'+ f'<ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>'+ f'</{action}Response>'+ ).encode("utf-8")+ return status, {"Content-Type": "text/xml"}, body+++def _empty(action):+ body = (+ f'<?xml version="1.0" encoding="UTF-8"?>'+ f'<{action}Response xmlns="{NS}">'+ f'<{action}Result/>'+ f'<ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>'+ f'</{action}Response>'+ ).encode("utf-8")+ return 200, {"Content-Type": "text/xml"}, body+++def _error(code, message, status=400):+ body = (+ f'<?xml version="1.0" encoding="UTF-8"?>'+ f'<ErrorResponse xmlns="{NS}">'+ f'<Error><Code>{code}</Code><Message>{message}</Message></Error>'+ f'<RequestId>{new_uuid()}</RequestId>'+ f'</ErrorResponse>'+ ).encode("utf-8")+ return status, {"Content-Type": "text/xml"}, body+++def _attrs_xml(attrs):+ return "".join(+ f"<member><Key>{a['Key']}</Key><Value>{a['Value']}</Value></member>"+ for a in attrs+ )++# ---------------------------------------------------------------------------+# XML serialisers for each resource type+# ---------------------------------------------------------------------------++def _lb_xml(lb):+ azs = "".join(+ f"<member><ZoneName>{REGION}a</ZoneName><SubnetId>{s}</SubnetId>"+ f"<LoadBalancerAddresses/></member>"+ for s in lb.get("Subnets", [])+ )+ sgs = "".join(f"<member>{sg}</member>" for sg in lb.get("SecurityGroups", []))+ return (+ f"<member>"+ f"<LoadBalancerArn>{lb['LoadBalancerArn']}</LoadBalancerArn>"+ f"<LoadBalancerName>{lb['LoadBalancerName']}</LoadBalancerName>"+ f"<DNSName>{lb['DNSName']}</DNSName>"+ f"<CanonicalHostedZoneId>Z35SXDOTRQ7X7K</CanonicalHostedZoneId>"+ f"<CreatedTime>{lb['CreatedTime']}</CreatedTime>"+ f"<Scheme>{lb['Scheme']}</Scheme>"+ f"<VpcId>{lb.get('VpcId','')}</VpcId>"+ f"<State><Code>{lb['State']}</Code></State>"+ f"<Type>{lb['Type']}</Type>"+ f"<AvailabilityZones>{azs}</AvailabilityZones>"+ f"<SecurityGroups>{sgs}</SecurityGroups>"+ f"<IpAddressType>{lb.get('IpAddressType','ipv4')}</IpAddressType>"+ f"</member>"+ )+++def _tg_xml(tg):+ lb_arns = "".join(f"<member>{a}</member>" for a in tg.get("LoadBalancerArns", []))+ return (+ f"<member>"+ f"<TargetGroupArn>{tg['TargetGroupArn']}</TargetGroupArn>"+ f"<TargetGroupName>{tg['TargetGroupName']}</TargetGroupName>"+ f"<Protocol>{tg.get('Protocol','HTTP')}</Protocol>"+ f"<Port>{tg.get('Port',80)}</Port>"+ f"<VpcId>{tg.get('VpcId','')}</VpcId>"+ f"<HealthCheckProtocol>{tg.get('HealthCheckProtocol','HTTP')}</HealthCheckProtocol>"+ f"<HealthCheckPort>{tg.get('HealthCheckPort','traffic-port')}</HealthCheckPort>"+ f"<HealthCheckEnabled>{str(tg.get('HealthCheckEnabled',True)).lower()}</HealthCheckEnabled>"+ f"<HealthCheckPath>{tg.get('HealthCheckPath','/')}</HealthCheckPath>"+ f"<HealthCheckIntervalSeconds>{tg.get('HealthCheckIntervalSeconds',30)}</HealthCheckIntervalSeconds>"+ f"<HealthCheckTimeoutSeconds>{tg.get('HealthCheckTimeoutSeconds',5)}</HealthCheckTimeoutSeconds>"+ f"<HealthyThresholdCount>{tg.get('HealthyThresholdCount',5)}</HealthyThresholdCount>"+ f"<UnhealthyThresholdCount>{tg.get('UnhealthyThresholdCount',2)}</UnhealthyThresholdCount>"+ f"<Matcher><HttpCode>{tg.get('Matcher',{}).get('HttpCode','200')}</HttpCode></Matcher>"+ f"<LoadBalancerArns>{lb_arns}</LoadBalancerArns>"+ f"<TargetType>{tg.get('TargetType','instance')}</TargetType>"+ f"</member>"+ )+++def _action_xml(a):+ inner = f"<Type>{a['Type']}</Type><Order>{a.get('Order',1)}</Order>"+ if "TargetGroupArn" in a:+ inner += f"<TargetGroupArn>{a['TargetGroupArn']}</TargetGroupArn>"+ if "RedirectConfig" in a:+ rc = a["RedirectConfig"]+ inner += (+ f"<RedirectConfig>"+ f"<Protocol>{rc.get('Protocol','#{protocol}')}</Protocol>"+ f"<Port>{rc.get('Port','#{port}')}</Port>"+ f"<Host>{rc.get('Host','#{host}')}</Host>"+ f"<Path>{rc.get('Path','/#{path}')}</Path>"+ f"<StatusCode>{rc.get('StatusCode','HTTP_301')}</StatusCode>"+ f"</RedirectConfig>"+ )+ if "FixedResponseConfig" in a:+ frc = a["FixedResponseConfig"]+ inner += (+ f"<FixedResponseConfig>"+ f"<StatusCode>{frc.get('StatusCode','200')}</StatusCode>"+ f"<ContentType>{frc.get('ContentType','text/plain')}</ContentType>"+ f"<MessageBody>{frc.get('MessageBody','')}</MessageBody>"+ f"</FixedResponseConfig>"+ )+ return f"<member>{inner}</member>"+++def _listener_xml(l):+ acts = "".join(_action_xml(a) for a in l.get("DefaultActions", []))+ return (+ f"<member>"+ f"<ListenerArn>{l['ListenerArn']}</ListenerArn>"+ f"<LoadBalancerArn>{l['LoadBalancerArn']}</LoadBalancerArn>"+ f"<Port>{l.get('Port',80)}</Port>"+ f"<Protocol>{l.get('Protocol','HTTP')}</Protocol>"+ f"<DefaultActions>{acts}</DefaultActions>"+ f"</member>"+ )+++def _rule_xml(r):+ conds = "".join(+ f"<member><Field>{c['Field']}</Field>"+ f"<Values>{''.join(f'<member>{v}</member>' for v in c.get('Values',[]))}</Values>"+ f"</member>"+ for c in r.get("Conditions", [])+ )+ acts = "".join(_action_xml(a) for a in r.get("Actions", []))+ return (+ f"<member>"+ f"<RuleArn>{r['RuleArn']}</RuleArn>"+ f"<Priority>{r['Priority']}</Priority>"+ f"<Conditions>{conds}</Conditions>"+ f"<Actions>{acts}</Actions>"+ f"<IsDefault>{str(r.get('IsDefault',False)).lower()}</IsDefault>"+ f"</member>"+ )++# ---------------------------------------------------------------------------+# Load Balancer handlers+# ---------------------------------------------------------------------------++def _create_lb(params):+ name = _p(params, "Name")+ if not name:+ return _error("ValidationError", "Name is required")+ for lb in _lbs.values():+ if lb["LoadBalancerName"] == name:+ return _error("DuplicateLoadBalancerName",+ f"A load balancer with name '{name}' already exists.")+ lid = _short_id()+ arn = f"arn:aws:elasticloadbalancing:{REGION}:{ACCOUNT_ID}:loadbalancer/app/{name}/{lid}"+ lb = {+ "LoadBalancerArn": arn,+ "LoadBalancerName": name,+ "DNSName": f"{name}-{lid[:8]}.{REGION}.elb.amazonaws.com",+ "Scheme": _p(params, "Scheme", "internet-facing"),+ "VpcId": _p(params, "VpcId", "vpc-00000001"),+ "State": "active",+ "Type": _p(params, "Type", "application"),+ "Subnets": _parse_member_list(params, "Subnets"),+ "SecurityGroups": _parse_member_list(params, "SecurityGroups"),+ "IpAddressType": _p(params, "IpAddressType", "ipv4"),+ "CreatedTime": _now_iso(),+ }+ _lbs[arn] = lb+ _tags[arn] = _parse_tags(params)+ _lb_attrs[arn] = [+ {"Key": "access_logs.s3.enabled", "Value": "false"},+ {"Key": "deletion_protection.enabled", "Value": "false"},+ {"Key": "idle_timeout.timeout_seconds", "Value": "60"},+ ]+ return _xml(200, "CreateLoadBalancer", f"<LoadBalancers>{_lb_xml(lb)}</LoadBalancers>")+++def _describe_lbs(params):+ arn_filter = _parse_member_list(params, "LoadBalancerArns")+ name_filter = _parse_member_list(params, "Names")+ results = list(_lbs.values())+ if arn_filter:+ results = [lb for lb in results if lb["LoadBalancerArn"] in arn_filter]+ if name_filter:+ results = [lb for lb in results if lb["LoadBalancerName"] in name_filter]+ return _xml(200, "DescribeLoadBalancers",+ f"<LoadBalancers>{''.join(_lb_xml(lb) for lb in results)}</LoadBalancers>")+++def _delete_lb(params):+ arn = _p(params, "LoadBalancerArn")+ _lbs.pop(arn, None)+ _lb_attrs.pop(arn, None)+ _tags.pop(arn, None)+ return _empty("DeleteLoadBalancer")+++def _describe_lb_attrs(params):+ arn = _p(params, "LoadBalancerArn")+ if arn not in _lbs:+ return _error("LoadBalancerNotFound", f"Load balancer '{arn}' not found.")+ return _xml(200, "DescribeLoadBalancerAttributes",+ f"<Attributes>{_attrs_xml(_lb_attrs.get(arn,[]))}</Attributes>")+++def _modify_lb_attrs(params):+ arn = _p(params, "LoadBalancerArn")+ if arn not in _lbs:+ return _error("LoadBalancerNotFound", f"Load balancer '{arn}' not found.")+ attrs = _lb_attrs.setdefault(arn, [])+ idx = {a["Key"]: i for i, a in enumerate(attrs)}+ i = 1+ while True:+ key = _p(params, f"Attributes.member.{i}.Key")+ if not key:+ break+ val = _p(params, f"Attributes.member.{i}.Value")+ if key in idx:+ attrs[idx[key]]["Value"] = val+ else:+ attrs.append({"Key": key, "Value": val})+ idx[key] = len(attrs) - 1+ i += 1+ return _xml(200, "ModifyLoadBalancerAttributes",+ f"<Attributes>{_attrs_xml(attrs)}</Attributes>")++++# ---------------------------------------------------------------------------+# Target Group handlers+# ---------------------------------------------------------------------------++def _create_tg(params):+ name = _p(params, "Name")+ if not name:+ return _error("ValidationError", "Name is required")+ for tg in _tgs.values():+ if tg["TargetGroupName"] == name:+ return _error("DuplicateTargetGroupName",+ f"A target group with name '{name}' already exists.")+ tid = _short_id()+ arn = f"arn:aws:elasticloadbalancing:{REGION}:{ACCOUNT_ID}:targetgroup/{name}/{tid}"+ tg = {+ "TargetGroupArn": arn,+ "TargetGroupName": name,+ "Protocol": _p(params, "Protocol", "HTTP"),+ "Port": int(_p(params, "Port", "80") or 80),+ "VpcId": _p(params, "VpcId", ""),+ "HealthCheckProtocol": _p(params, "HealthCheckProtocol", "HTTP"),+ "HealthCheckPort": _p(params, "HealthCheckPort", "traffic-port"),+ "HealthCheckEnabled": _p(params, "HealthCheckEnabled", "true").lower() == "true",+ "HealthCheckPath": _p(params, "HealthCheckPath", "/"),+ "HealthCheckIntervalSeconds": int(_p(params, "HealthCheckIntervalSeconds", "30") or 30),+ "HealthCheckTimeoutSeconds": int(_p(params, "HealthCheckTimeoutSeconds", "5") or 5),+ "HealthyThresholdCount": int(_p(params, "HealthyThresholdCount", "5") or 5),+ "UnhealthyThresholdCount": int(_p(params, "UnhealthyThresholdCount", "2") or 2),+ "Matcher": {"HttpCode": _p(params, "Matcher.HttpCode", "200")},+ "LoadBalancerArns": [],+ "TargetType": _p(params, "TargetType", "instance"),+ }+ _tgs[arn] = tg+ _targets[arn] = []+ _tags[arn] = _parse_tags(params)+ _tg_attrs[arn] = [+ {"Key": "deregistration_delay.timeout_seconds", "Value": "300"},+ {"Key": "stickiness.enabled", "Value": "false"},+ {"Key": "stickiness.type", "Value": "lb_cookie"},+ ]+ return _xml(200, "CreateTargetGroup", f"<TargetGroups>{_tg_xml(tg)}</TargetGroups>")+++def _describe_tgs(params):+ arn_filter = _parse_member_list(params, "TargetGroupArns")+ name_filter = _parse_member_list(params, "Names")+ lb_arn = _p(params, "LoadBalancerArn")+ results = list(_tgs.values())+ if arn_filter:+ results = [tg for tg in results if tg["TargetGroupArn"] in arn_filter]+ if name_filter:+ results = [tg for tg in results if tg["TargetGroupName"] in name_filter]+ if lb_arn:+ results = [tg for tg in results if lb_arn in tg.get("LoadBalancerArns", [])]+ return _xml(200, "DescribeTargetGroups",+ f"<TargetGroups>{''.join(_tg_xml(tg) for tg in results)}</TargetGroups>")+++def _modify_tg(params):+ arn = _p(params, "TargetGroupArn")+ tg = _tgs.get(arn)+ if not tg:+ return _error("TargetGroupNotFound", f"Target group '{arn}' not found.")+ for field, param in [("HealthCheckProtocol", "HealthCheckProtocol"),+ ("HealthCheckPort", "HealthCheckPort"),+ ("HealthCheckPath", "HealthCheckPath")]:+ v = _p(params, param)+ if v:+ tg[field] = v+ for field, param, cast in [+ ("HealthCheckEnabled", "HealthCheckEnabled", lambda v: v.lower() == "true"),+ ("HealthCheckIntervalSeconds", "HealthCheckIntervalSeconds", int),+ ("HealthCheckTimeoutSeconds", "HealthCheckTimeoutSeconds", int),+ ("HealthyThresholdCount", "HealthyThresholdCount", int),+ ("UnhealthyThresholdCount", "UnhealthyThresholdCount", int),+ ]:+ v = _p(params, param)+ if v:+ tg[field] = cast(v)+ http_code = _p(params, "Matcher.HttpCode")+ if http_code:+ tg["Matcher"]["HttpCode"] = http_code+ return _xml(200, "ModifyTargetGroup", f"<TargetGroups>{_tg_xml(tg)}</TargetGroups>")+++def _delete_tg(params):+ arn = _p(params, "TargetGroupArn")+ _tgs.pop(arn, None)+ _targets.pop(arn, None)+ _tg_attrs.pop(arn, None)+ _tags.pop(arn, None)+ return _empty("DeleteTargetGroup")+++def _describe_tg_attrs(params):+ arn = _p(params, "TargetGroupArn")+ if arn not in _tgs:+ return _error("TargetGroupNotFound", f"Target group '{arn}' not found.")+ return _xml(200, "DescribeTargetGroupAttributes",+ f"<Attributes>{_attrs_xml(_tg_attrs.get(arn,[]))}</Attributes>")+++def _modify_tg_attrs(params):+ arn = _p(params, "TargetGroupArn")+ if arn not in _tgs:+ return _error("TargetGroupNotFound", f"Target group '{arn}' not found.")+ attrs = _tg_attrs.setdefault(arn, [])+ idx = {a["Key"]: i for i, a in enumerate(attrs)}+ i = 1+ while True:+ key = _p(params, f"Attributes.member.{i}.Key")+ if not key:+ break+ val = _p(params, f"Attributes.member.{i}.Value")+ if key in idx:+ attrs[idx[key]]["Value"] = val+ else:+ attrs.append({"Key": key, "Value": val})+ idx[key] = len(attrs) - 1+ i += 1+ return _xml(200, "ModifyTargetGroupAttributes",+ f"<Attributes>{_attrs_xml(attrs)}</Attributes>")+++# ---------------------------------------------------------------------------+# Listener handlers+# ---------------------------------------------------------------------------++def _create_listener(params):+ lb_arn = _p(params, "LoadBalancerArn")+ if lb_arn not in _lbs:+ return _error("LoadBalancerNotFound", f"Load balancer '{lb_arn}' not found.")+ lid = _short_id()+ lb = _lbs[lb_arn]+ lb_name = lb["LoadBalancerName"]+ lb_id = lb_arn.split("/")[-1]+ l_arn = (f"arn:aws:elasticloadbalancing:{REGION}:{ACCOUNT_ID}"+ f":listener/app/{lb_name}/{lb_id}/{lid}")+ actions = _parse_actions(params, "DefaultActions")+ for action in actions:+ tg_arn = action.get("TargetGroupArn")+ if tg_arn and tg_arn in _tgs and lb_arn not in _tgs[tg_arn]["LoadBalancerArns"]:+ _tgs[tg_arn]["LoadBalancerArns"].append(lb_arn)+ listener = {+ "ListenerArn": l_arn,+ "LoadBalancerArn": lb_arn,+ "Port": int(_p(params, "Port", "80") or 80),+ "Protocol": _p(params, "Protocol", "HTTP"),+ "DefaultActions": actions,+ }+ _listeners[l_arn] = listener+ _tags[l_arn] = _parse_tags(params)+ # auto-create default rule+ rule_id = _short_id()+ rule_arn = (f"arn:aws:elasticloadbalancing:{REGION}:{ACCOUNT_ID}"+ f":listener-rule/app/{lb_name}/{lb_id}/{lid}/{rule_id}")+ _rules[rule_arn] = {+ "RuleArn": rule_arn, "ListenerArn": l_arn,+ "Priority": "default", "Conditions": [],+ "Actions": actions, "IsDefault": True,+ }+ return _xml(200, "CreateListener", f"<Listeners>{_listener_xml(listener)}</Listeners>")+++def _describe_listeners(params):+ lb_arn = _p(params, "LoadBalancerArn")+ arn_filter = _parse_member_list(params, "ListenerArns")+ results = list(_listeners.values())+ if lb_arn:+ results = [l for l in results if l["LoadBalancerArn"] == lb_arn]+ if arn_filter:+ results = [l for l in results if l["ListenerArn"] in arn_filter]+ return _xml(200, "DescribeListeners",+ f"<Listeners>{''.join(_listener_xml(l) for l in results)}</Listeners>")+++def _modify_listener(params):+ arn = _p(params, "ListenerArn")+ listener = _listeners.get(arn)+ if not listener:+ return _error("ListenerNotFound", f"Listener '{arn}' not found.")+ port = _p(params, "Port")+ if port:+ listener["Port"] = int(port)+ protocol = _p(params, "Protocol")+ if protocol:+ listener["Protocol"] = protocol+ actions = _parse_actions(params, "DefaultActions")+ if actions:+ listener["DefaultActions"] = actions+ return _xml(200, "ModifyListener", f"<Listeners>{_listener_xml(listener)}</Listeners>")+++def _delete_listener(params):+ arn = _p(params, "ListenerArn")+ _listeners.pop(arn, None)+ _tags.pop(arn, None)+ for rarn in [k for k, v in list(_rules.items()) if v.get("ListenerArn") == arn]:+ _rules.pop(rarn, None)+ return _empty("DeleteListener")+++# ---------------------------------------------------------------------------+# Rule handlers+# ---------------------------------------------------------------------------++def _create_rule(params):+ l_arn = _p(params, "ListenerArn")+ if l_arn not in _listeners:+ return _error("ListenerNotFound", f"Listener '{l_arn}' not found.")+ listener = _listeners[l_arn]+ lb_arn = listener["LoadBalancerArn"]+ lb_name = _lbs[lb_arn]["LoadBalancerName"]+ lb_id = lb_arn.split("/")[-1]+ l_id = l_arn.split("/")[-1]+ rule_id = _short_id()+ rule_arn = (f"arn:aws:elasticloadbalancing:{REGION}:{ACCOUNT_ID}"+ f":listener-rule/app/{lb_name}/{lb_id}/{l_id}/{rule_id}")+ rule = {+ "RuleArn": rule_arn, "ListenerArn": l_arn,+ "Priority": _p(params, "Priority", "1"),+ "Conditions": _parse_conditions(params),+ "Actions": _parse_actions(params, "Actions"),+ "IsDefault": False,+ }+ _rules[rule_arn] = rule+ _tags[rule_arn] = _parse_tags(params)+ return _xml(200, "CreateRule", f"<Rules>{_rule_xml(rule)}</Rules>")+++def _describe_rules(params):+ l_arn = _p(params, "ListenerArn")+ arn_filter = _parse_member_list(params, "RuleArns")+ results = list(_rules.values())+ if l_arn:+ results = [r for r in results if r.get("ListenerArn") == l_arn]+ if arn_filter:+ results = [r for r in results if r["RuleArn"] in arn_filter]+ return _xml(200, "DescribeRules", f"<Rules>{''.join(_rule_xml(r) for r in results)}</Rules>")+++def _modify_rule(params):+ arn = _p(params, "RuleArn")+ rule = _rules.get(arn)+ if not rule:+ return _error("RuleNotFound", f"Rule '{arn}' not found.")+ conds = _parse_conditions(params)+ if conds:+ rule["Conditions"] = conds+ acts = _parse_actions(params, "Actions")+ if acts:+ rule["Actions"] = acts+ return _xml(200, "ModifyRule", f"<Rules>{_rule_xml(rule)}</Rules>")+++def _delete_rule(params):+ arn = _p(params, "RuleArn")+ if _rules.get(arn, {}).get("IsDefault"):+ return _error("OperationNotPermitted", "Cannot delete a default rule.")+ _rules.pop(arn, None)+ _tags.pop(arn, None)+ return _empty("DeleteRule")+++def _set_rule_priorities(params):+ updated, i = [], 1+ while True:+ arn = _p(params, f"RulePriorities.member.{i}.RuleArn")+ if not arn:+ break+ priority = _p(params, f"RulePriorities.member.{i}.Priority")+ if arn in _rules:+ _rules[arn]["Priority"] = priority+ updated.append(_rules[arn])+ i += 1+ return _xml(200, "SetRulePriorities",+ f"<Rules>{''.join(_rule_xml(r) for r in updated)}</Rules>")+++# ---------------------------------------------------------------------------+# Target registration handlers+# ---------------------------------------------------------------------------++def _register_targets(params):+ tg_arn = _p(params, "TargetGroupArn")+ if tg_arn not in _tgs:+ return _error("TargetGroupNotFound", f"Target group '{tg_arn}' not found.")+ new_tgts = _parse_targets_param(params)+ existing = _targets.setdefault(tg_arn, [])+ existing_ids = {t["Id"] for t in existing}+ for t in new_tgts:+ if t["Id"] not in existing_ids:+ existing.append(t)+ existing_ids.add(t["Id"])+ return _empty("RegisterTargets")+++def _deregister_targets(params):+ tg_arn = _p(params, "TargetGroupArn")+ if tg_arn not in _tgs:+ return _error("TargetGroupNotFound", f"Target group '{tg_arn}' not found.")+ to_remove = {t["Id"] for t in _parse_targets_param(params)}+ _targets[tg_arn] = [t for t in _targets.get(tg_arn, []) if t["Id"] not in to_remove]+ return _empty("DeregisterTargets")+++def _describe_target_health(params):+ tg_arn = _p(params, "TargetGroupArn")+ if tg_arn not in _tgs:+ return _error("TargetGroupNotFound", f"Target group '{tg_arn}' not found.")+ registered = _targets.get(tg_arn, [])+ target_filter = {t["Id"] for t in _parse_targets_param(params)}+ if target_filter:+ registered = [t for t in registered if t["Id"] in target_filter]+ default_port = _tgs[tg_arn].get("Port", 80)+ descs = "".join(+ f"<member>"+ f"<Target><Id>{t['Id']}</Id><Port>{t.get('Port', default_port)}</Port></Target>"+ f"<HealthStatus>healthy</HealthStatus>"+ f"<TargetHealth><State>healthy</State></TargetHealth>"+ f"</member>"+ for t in registered+ )+ return _xml(200, "DescribeTargetHealth",+ f"<TargetHealthDescriptions>{descs}</TargetHealthDescriptions>")+++# ---------------------------------------------------------------------------+# Tag handlers+# ---------------------------------------------------------------------------++def _add_tags(params):+ arns = _parse_member_list(params, "ResourceArns")+ new_tags = _parse_tags(params)+ for arn in arns:+ existing = _tags.setdefault(arn, [])+ idx = {t["Key"]: i for i, t in enumerate(existing)}+ for tag in new_tags:+ if tag["Key"] in idx:+ existing[idx[tag["Key"]]]["Value"] = tag["Value"]+ else:+ existing.append(tag)+ idx[tag["Key"]] = len(existing) - 1+ return _empty("AddTags")+++def _remove_tags(params):+ arns = _parse_member_list(params, "ResourceArns")+ key_set = set(_parse_member_list(params, "TagKeys"))+ for arn in arns:+ if arn in _tags:+ _tags[arn] = [t for t in _tags[arn] if t["Key"] not in key_set]+ return _empty("RemoveTags")+++def _describe_tags(params):+ arns = _parse_member_list(params, "ResourceArns")+ descs = ""+ for arn in arns:+ tags_xml = "".join(+ f"<member><Key>{t['Key']}</Key><Value>{t['Value']}</Value></member>"+ for t in _tags.get(arn, [])+ )+ descs += f"<member><ResourceArn>{arn}</ResourceArn><Tags>{tags_xml}</Tags></member>"+ return _xml(200, "DescribeTags", f"<TagDescriptions>{descs}</TagDescriptions>")+++# ---------------------------------------------------------------------------+# Action map, request routing, and reset+# ---------------------------------------------------------------------------++_ACTION_MAP = {+ "CreateLoadBalancer": _create_lb,+ "DescribeLoadBalancers": _describe_lbs,+ "DeleteLoadBalancer": _delete_lb,+ "DescribeLoadBalancerAttributes": _describe_lb_attrs,+ "ModifyLoadBalancerAttributes": _modify_lb_attrs,+ "CreateTargetGroup": _create_tg,+ "DescribeTargetGroups": _describe_tgs,+ "ModifyTargetGroup": _modify_tg,+ "DeleteTargetGroup": _delete_tg,+ "DescribeTargetGroupAttributes": _describe_tg_attrs,+ "ModifyTargetGroupAttributes": _modify_tg_attrs,+ "CreateListener": _create_listener,+ "DescribeListeners": _describe_listeners,+ "ModifyListener": _modify_listener,+ "DeleteListener": _delete_listener,+ "CreateRule": _create_rule,+ "DescribeRules": _describe_rules,+ "ModifyRule": _modify_rule,+ "DeleteRule": _delete_rule,+ "SetRulePriorities": _set_rule_priorities,+ "RegisterTargets": _register_targets,+ "DeregisterTargets": _deregister_targets,+ "DescribeTargetHealth": _describe_target_health,+ "AddTags": _add_tags,+ "RemoveTags": _remove_tags,+ "DescribeTags": _describe_tags,+}+++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+ action = _p(params, "Action")+ handler = _ACTION_MAP.get(action)+ if not handler:+ return _error("InvalidAction", f"Unknown ELBv2 action: {action}", 400)+ return handler(params)+++# ---------------------------------------------------------------------------+# Data-plane: host/name lookup+# ---------------------------------------------------------------------------++def find_lb_for_host(host):+ hostname = host.split(":")[0].lower()+ for lb in _lbs.values():+ if lb["DNSName"].lower() == hostname:+ return lb+ if hostname == f"{lb['LoadBalancerName'].lower()}.alb.localhost":+ return lb+ return None+++def _find_lb_by_name(name):+ name_lc = name.lower()+ for lb in _lbs.values():+ if lb["LoadBalancerName"].lower() == name_lc:+ return lb+ return None+++# ---------------------------------------------------------------------------+# Data-plane: rule matching+# ---------------------------------------------------------------------------++def _match_condition(cond, method, path, headers, query_params):+ field = cond.get("Field", "")+ values = cond.get("Values", [])++ if field == "path-pattern":+ return any(fnmatch.fnmatch(path, v) for v in values)++ if field == "host-header":+ hostname = headers.get("host", "").split(":")[0]+ return any(fnmatch.fnmatch(hostname, v) for v in values)++ if field == "http-method":+ return method.upper() in [v.upper() for v in values]++ if field == "query-string":+ # Values stored as "key=value" strings+ for v in values:+ if "=" in v:+ k, expected = v.split("=", 1)+ actual = query_params.get(k, [""])[0] if isinstance(query_params.get(k), list) else query_params.get(k, "")+ if actual != expected:+ return False+ else:+ if v not in query_params:+ return False+ return True++ if field == "http-header":+ cfg = cond.get("HttpHeaderConfig", {})+ hname = cfg.get("HttpHeaderName", "").lower()+ hvals = cfg.get("Values", values)+ actual = headers.get(hname, "")+ return any(fnmatch.fnmatch(actual, v) for v in hvals)++ # source-ip is not implemented (no real network in emulator) — always matches.+ # Unknown condition types also always match to avoid silently dropping traffic.+ return True+++def _rule_sort_key(rule):+ p = rule.get("Priority", "default")+ if p == "default":+ return (1, 0)+ try:+ return (0, int(p))+ except (ValueError, TypeError):+ return (0, 9999)+++# ---------------------------------------------------------------------------+# Data-plane: action execution+# ---------------------------------------------------------------------------++async def _execute_action(action, method, path, headers, body, query_params):+ atype = action.get("Type", "").lower()++ if atype == "fixed-response":+ frc = action.get("FixedResponseConfig", {})+ code = int(frc.get("StatusCode", "200"))+ ct = frc.get("ContentType", "text/plain")+ msg = frc.get("MessageBody", "")+ return code, {"Content-Type": ct}, msg.encode("utf-8")++ if atype == "redirect":+ rc = action.get("RedirectConfig", {})+ code = int(rc.get("StatusCode", "HTTP_301").replace("HTTP_", ""))+ src_host = headers.get("host", "localhost").split(":")[0]+ proto = rc.get("Protocol", "#{protocol}").replace("#{protocol}", "http")+ rhost = rc.get("Host", "#{host}").replace("#{host}", src_host)+ rport = rc.get("Port", "#{port}").replace("#{port}", "")+ rpath = rc.get("Path", "/#{path}").replace("#{path}", path.lstrip("/"))+ location = f"{proto}://{rhost}"+ if rport and rport not in ("80", "443", ""):+ location += f":{rport}"+ location += rpath+ return code, {"Location": location, "Content-Type": "text/plain"}, b""++ if atype == "forward":+ tg_arn = action.get("TargetGroupArn", "")+ return await _forward_to_tg(tg_arn, method, path, headers, body, query_params)++ return (502, {"Content-Type": "application/json"},+ json.dumps({"message": f"Unsupported action type: {atype}"}).encode())+++async def _forward_to_tg(tg_arn, method, path, headers, body, query_params):+ tg = _tgs.get(tg_arn)+ if not tg:+ return (502, {"Content-Type": "application/json"},+ json.dumps({"message": f"Target group '{tg_arn}' not found"}).encode())++ registered = _targets.get(tg_arn, [])+ if not registered:+ return (503, {"Content-Type": "application/json"},+ json.dumps({"message": "No registered targets in target group"}).encode())++ target_type = tg.get("TargetType", "instance")++ if target_type == "lambda":+ func_id = registered[0]["Id"]+ func_name = func_id.split(":function:")[-1].split(":")[0] if ":function:" in func_id else func_id+ return await _invoke_lambda_target(func_name, tg_arn, method, path,+ headers, body, query_params)++ return (502, {"Content-Type": "application/json"},+ json.dumps({"message": f"Target type '{target_type}' not supported."}).encode())+++async def _invoke_lambda_target(func_name, tg_arn, method, path, headers, body, query_params):+ try:+ from ministack.services import lambda_svc+ except ImportError:+ return (502, {"Content-Type": "application/json"},+ json.dumps({"message": "Lambda service unavailable"}).encode())++ if func_name not in lambda_svc._functions:+ return (502, {"Content-Type": "application/json"},+ json.dumps({"message": f"Lambda function '{func_name}' not found"}).encode())++ body_str = None+ is_b64 = False+ if body:+ try:+ body_str = body.decode("utf-8")+ except UnicodeDecodeError:+ body_str = base64.b64encode(body).decode("ascii")+ is_b64 = True++ qs_single = {k: (v[0] if isinstance(v, list) else v) for k, v in query_params.items()}+ qs_multi = {k: (v if isinstance(v, list) else [v]) for k, v in query_params.items()}++ event = {+ "requestContext": {"elb": {"targetGroupArn": tg_arn}},+ "httpMethod": method.upper(),+ "path": path,+ "queryStringParameters": qs_single,+ "multiValueQueryStringParameters": qs_multi,+ "headers": {k.lower(): v for k, v in headers.items()},+ "multiValueHeaders": {k.lower(): [v] for k, v in headers.items()},+ "body": body_str,+ "isBase64Encoded": is_b64,+ }++ _, resp_headers, resp_body = await lambda_svc._invoke(func_name, event, {})++ if resp_headers.get("X-Amz-Function-Error"):+ raw = resp_body.decode("utf-8", errors="replace") if isinstance(resp_body, bytes) else str(resp_body)+ return (502, {"Content-Type": "application/json"},+ json.dumps({"message": f"Lambda error: {raw}"}).encode())++ try:+ result = json.loads(resp_body) if isinstance(resp_body, bytes) else resp_body+ if not isinstance(result, dict):+ return (200, {"Content-Type": "text/plain"},+ str(result).encode("utf-8"))++ resp_code = int(result.get("statusCode", 200))+ out_headers = dict(result.get("headers") or {})+ for k, vals in (result.get("multiValueHeaders") or {}).items():+ out_headers[k] = vals[-1]++ out_body = result.get("body", "")+ if result.get("isBase64Encoded"):+ out_body = base64.b64decode(out_body)+ elif isinstance(out_body, str):+ out_body = out_body.encode("utf-8")+ elif not isinstance(out_body, bytes):+ out_body = json.dumps(out_body).encode("utf-8")++ return resp_code, out_headers, out_body++ except Exception:+ raw = resp_body if isinstance(resp_body, bytes) else str(resp_body).encode()+ return 200, {"Content-Type": "text/plain"}, raw+++# ---------------------------------------------------------------------------+# Data-plane: main dispatcher+# ---------------------------------------------------------------------------++async def dispatch_request(lb, method, path, headers, body, query_params, port=80):+ lb_arn = lb["LoadBalancerArn"]++ candidates = [l for l in _listeners.values() if l["LoadBalancerArn"] == lb_arn]+ matching = [l for l in candidates if l.get("Port", 80) == port] or candidates++ if not matching:+ return (503, {"Content-Type": "application/json"},+ json.dumps({"message": f"No listeners configured for '{lb['LoadBalancerName']}'"}).encode())++ listener = matching[0]+ l_arn = listener["ListenerArn"]++ listener_rules = sorted(+ (r for r in _rules.values() if r.get("ListenerArn") == l_arn),+ key=_rule_sort_key,+ )++ for rule in listener_rules:+ conditions = rule.get("Conditions", [])+ is_default = rule.get("IsDefault", False)+ matched = is_default or all(+ _match_condition(c, method, path, headers, query_params)+ for c in conditions+ )+ if matched:+ actions = rule.get("Actions") or listener.get("DefaultActions", [])+ if actions:+ return await _execute_action(actions[0], method, path,+ headers, body, query_params)++ return (502, {"Content-Type": "application/json"},+ json.dumps({"message": "No matching ALB rule found"}).encode())+++def reset():+ _lbs.clear()+ _tgs.clear()+ _listeners.clear()+ _rules.clear()+ _targets.clear()+ _tags.clear()+ _lb_attrs.clear()+ _tg_attrs.clear()diff --git a/pyproject.toml b/pyproject.tomlindex 8af1f5c1..0a21338b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "ministack"-version = "1.1.3"+version = "1.1.4"description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"readme = "README.md"license = { file = "LICENSE" }diff --git a/tests/conftest.py b/tests/conftest.pyindex 72ea7494..c71a7b25 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -149,6 +149,10 @@ def ec2():def emr():return make_client("emr")[email protected](scope="session")+def elbv2():+ return make_client("elbv2")+@pytest.fixture(scope="session")def ebs():return make_client("ec2")diff --git a/tests/test_services.py b/tests/test_services.pyindex 2f8adeb3..388f7353 100644--- a/tests/test_services.py+++ b/tests/test_services.py@@ -11348,6 +11348,534 @@ def test_emr_instance_groups(emr):# ---------------------------------------------------------------------------+# ALB / ELBv2+# ---------------------------------------------------------------------------++def test_elbv2_create_describe_delete_lb(elbv2):+ resp = elbv2.create_load_balancer(Name="qa-alb", Type="application", Scheme="internet-facing")+ lb = resp["LoadBalancers"][0]+ lb_arn = lb["LoadBalancerArn"]+ assert lb_arn.startswith("arn:aws:elasticloadbalancing")+ assert lb["LoadBalancerName"] == "qa-alb"+ assert lb["Type"] == "application"+ assert lb["Scheme"] == "internet-facing"+ assert "DNSName" in lb+ assert lb["State"]["Code"] == "active"++ desc = elbv2.describe_load_balancers(LoadBalancerArns=[lb_arn])+ assert desc["LoadBalancers"][0]["LoadBalancerArn"] == lb_arn++ elbv2.delete_load_balancer(LoadBalancerArn=lb_arn)+ desc2 = elbv2.describe_load_balancers()+ assert not any(l["LoadBalancerArn"] == lb_arn for l in desc2["LoadBalancers"])+++def test_elbv2_describe_lb_by_name(elbv2):+ elbv2.create_load_balancer(Name="qa-alb-named")+ resp = elbv2.describe_load_balancers(Names=["qa-alb-named"])+ assert len(resp["LoadBalancers"]) == 1+ assert resp["LoadBalancers"][0]["LoadBalancerName"] == "qa-alb-named"+ elbv2.delete_load_balancer(LoadBalancerArn=resp["LoadBalancers"][0]["LoadBalancerArn"])+++def test_elbv2_duplicate_lb_name(elbv2):+ elbv2.create_load_balancer(Name="qa-alb-dup")+ import botocore.exceptions+ try:+ elbv2.create_load_balancer(Name="qa-alb-dup")+ assert False, "should have raised"+ except botocore.exceptions.ClientError as e:+ assert "DuplicateLoadBalancerName" in str(e)+ finally:+ lbs = elbv2.describe_load_balancers(Names=["qa-alb-dup"])["LoadBalancers"]+ if lbs:+ elbv2.delete_load_balancer(LoadBalancerArn=lbs[0]["LoadBalancerArn"])+++def test_elbv2_lb_attributes(elbv2):+ lb_arn = elbv2.create_load_balancer(Name="qa-alb-attrs")["LoadBalancers"][0]["LoadBalancerArn"]+ attrs = elbv2.describe_load_balancer_attributes(LoadBalancerArn=lb_arn)["Attributes"]+ keys = {a["Key"] for a in attrs}+ assert "idle_timeout.timeout_seconds" in keys++ elbv2.modify_load_balancer_attributes(+ LoadBalancerArn=lb_arn,+ Attributes=[{"Key": "idle_timeout.timeout_seconds", "Value": "120"}],+ )+ updated = elbv2.describe_load_balancer_attributes(LoadBalancerArn=lb_arn)["Attributes"]+ val = next(a["Value"] for a in updated if a["Key"] == "idle_timeout.timeout_seconds")+ assert val == "120"+ elbv2.delete_load_balancer(LoadBalancerArn=lb_arn)+++def test_elbv2_create_describe_delete_tg(elbv2):+ resp = elbv2.create_target_group(+ Name="qa-tg", Protocol="HTTP", Port=80, VpcId="vpc-00000001",+ HealthCheckPath="/health",+ )+ tg = resp["TargetGroups"][0]+ tg_arn = tg["TargetGroupArn"]+ assert tg_arn.startswith("arn:aws:elasticloadbalancing")+ assert tg["TargetGroupName"] == "qa-tg"+ assert tg["HealthCheckPath"] == "/health"++ desc = elbv2.describe_target_groups(TargetGroupArns=[tg_arn])+ assert desc["TargetGroups"][0]["TargetGroupArn"] == tg_arn++ elbv2.delete_target_group(TargetGroupArn=tg_arn)+ desc2 = elbv2.describe_target_groups()+ assert not any(t["TargetGroupArn"] == tg_arn for t in desc2["TargetGroups"])+++def test_elbv2_tg_attributes(elbv2):+ tg_arn = elbv2.create_target_group(+ Name="qa-tg-attrs", Protocol="HTTP", Port=80, VpcId="vpc-00000001",+ )["TargetGroups"][0]["TargetGroupArn"]+ attrs = elbv2.describe_target_group_attributes(TargetGroupArn=tg_arn)["Attributes"]+ keys = {a["Key"] for a in attrs}+ assert "deregistration_delay.timeout_seconds" in keys++ elbv2.modify_target_group_attributes(+ TargetGroupArn=tg_arn,+ Attributes=[{"Key": "deregistration_delay.timeout_seconds", "Value": "60"}],+ )+ updated = elbv2.describe_target_group_attributes(TargetGroupArn=tg_arn)["Attributes"]+ val = next(a["Value"] for a in updated if a["Key"] == "deregistration_delay.timeout_seconds")+ assert val == "60"+ elbv2.delete_target_group(TargetGroupArn=tg_arn)+++def test_elbv2_listener_crud(elbv2):+ lb_arn = elbv2.create_load_balancer(Name="qa-alb-listener")["LoadBalancers"][0]["LoadBalancerArn"]+ tg_arn = elbv2.create_target_group(+ Name="qa-tg-l", Protocol="HTTP", Port=80, VpcId="vpc-00000001",+ )["TargetGroups"][0]["TargetGroupArn"]++ l_resp = elbv2.create_listener(+ LoadBalancerArn=lb_arn,+ Protocol="HTTP",+ Port=80,+ DefaultActions=[{"Type": "forward", "TargetGroupArn": tg_arn}],+ )+ listener = l_resp["Listeners"][0]+ l_arn = listener["ListenerArn"]+ assert l_arn.startswith("arn:aws:elasticloadbalancing")+ assert listener["Port"] == 80+ assert listener["Protocol"] == "HTTP"++ desc = elbv2.describe_listeners(LoadBalancerArn=lb_arn)+ assert any(l["ListenerArn"] == l_arn for l in desc["Listeners"])++ # TG should now reference LB+ tg_desc = elbv2.describe_target_groups(TargetGroupArns=[tg_arn])["TargetGroups"][0]+ assert lb_arn in tg_desc["LoadBalancerArns"]++ elbv2.modify_listener(ListenerArn=l_arn, Port=8080)+ updated = elbv2.describe_listeners(ListenerArns=[l_arn])["Listeners"][0]+ assert updated["Port"] == 8080++ elbv2.delete_listener(ListenerArn=l_arn)+ desc2 = elbv2.describe_listeners(LoadBalancerArn=lb_arn)+ assert not any(l["ListenerArn"] == l_arn for l in desc2["Listeners"])++ elbv2.delete_target_group(TargetGroupArn=tg_arn)+ elbv2.delete_load_balancer(LoadBalancerArn=lb_arn)+++def test_elbv2_rule_crud(elbv2):+ lb_arn = elbv2.create_load_balancer(Name="qa-alb-rules")["LoadBalancers"][0]["LoadBalancerArn"]+ tg_arn = elbv2.create_target_group(+ Name="qa-tg-r", Protocol="HTTP", Port=80, VpcId="vpc-00000001",+ )["TargetGroups"][0]["TargetGroupArn"]+ l_arn = elbv2.create_listener(+ LoadBalancerArn=lb_arn, Protocol="HTTP", Port=80,+ DefaultActions=[{"Type": "forward", "TargetGroupArn": tg_arn}],+ )["Listeners"][0]["ListenerArn"]++ # describe should include default rule+ rules = elbv2.describe_rules(ListenerArn=l_arn)["Rules"]+ assert any(r["IsDefault"] for r in rules)++ # create a custom rule+ rule_resp = elbv2.create_rule(+ ListenerArn=l_arn,+ Priority=10,+ Conditions=[{"Field": "path-pattern", "Values": ["/api/*"]}],+ Actions=[{"Type": "forward", "TargetGroupArn": tg_arn}],+ )+ rule = rule_resp["Rules"][0]+ r_arn = rule["RuleArn"]+ assert not rule["IsDefault"]+ assert rule["Priority"] == "10"++ rules2 = elbv2.describe_rules(ListenerArn=l_arn)["Rules"]+ assert any(r["RuleArn"] == r_arn for r in rules2)++ elbv2.delete_rule(RuleArn=r_arn)+ rules3 = elbv2.describe_rules(ListenerArn=l_arn)["Rules"]+ assert not any(r["RuleArn"] == r_arn for r in rules3)++ elbv2.delete_listener(ListenerArn=l_arn)+ elbv2.delete_target_group(TargetGroupArn=tg_arn)+ elbv2.delete_load_balancer(LoadBalancerArn=lb_arn)+++def test_elbv2_register_deregister_targets(elbv2):+ tg_arn = elbv2.create_target_group(+ Name="qa-tg-targets", Protocol="HTTP", Port=80, VpcId="vpc-00000001",+ )["TargetGroups"][0]["TargetGroupArn"]++ elbv2.register_targets(+ TargetGroupArn=tg_arn,+ Targets=[{"Id": "i-0001", "Port": 80}, {"Id": "i-0002", "Port": 80}],+ )+ health = elbv2.describe_target_health(TargetGroupArn=tg_arn)+ assert len(health["TargetHealthDescriptions"]) == 2+ ids = {d["Target"]["Id"] for d in health["TargetHealthDescriptions"]}+ assert ids == {"i-0001", "i-0002"}+ for d in health["TargetHealthDescriptions"]:+ assert d["TargetHealth"]["State"] == "healthy"++ elbv2.deregister_targets(TargetGroupArn=tg_arn, Targets=[{"Id": "i-0001"}])+ health2 = elbv2.describe_target_health(TargetGroupArn=tg_arn)+ assert len(health2["TargetHealthDescriptions"]) == 1+ assert health2["TargetHealthDescriptions"][0]["Target"]["Id"] == "i-0002"++ elbv2.delete_target_group(TargetGroupArn=tg_arn)+++def test_elbv2_tags(elbv2):+ lb_arn = elbv2.create_load_balancer(+ Name="qa-alb-tags", Tags=[{"Key": "env", "Value": "test"}],+ )["LoadBalancers"][0]["LoadBalancerArn"]++ elbv2.add_tags(+ ResourceArns=[lb_arn],+ Tags=[{"Key": "team", "Value": "infra"}],+ )+ desc = elbv2.describe_tags(ResourceArns=[lb_arn])+ tag_map = {t["Key"]: t["Value"] for t in desc["TagDescriptions"][0]["Tags"]}+ assert tag_map["env"] == "test"+ assert tag_map["team"] == "infra"++ elbv2.remove_tags(ResourceArns=[lb_arn], TagKeys=["env"])+ desc2 = elbv2.describe_tags(ResourceArns=[lb_arn])+ tag_map2 = {t["Key"]: t["Value"] for t in desc2["TagDescriptions"][0]["Tags"]}+ assert "env" not in tag_map2+ assert tag_map2["team"] == "infra"++ elbv2.delete_load_balancer(LoadBalancerArn=lb_arn)+++# ---------------------------------------------------------------------------+# ALB data-plane (traffic routing)+# ---------------------------------------------------------------------------++def _alb_zip(code: str) -> bytes:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ return buf.getvalue()+++def _alb_setup(elbv2, lam, lb_name, fn_name, fn_code,+ listener_port=80, extra_rules=None):+ """Create LB + Lambda TG + listener + register Lambda as target.+ Returns (lb_arn, tg_arn, l_arn, fn_arn).+ """+ # Lambda+ lam.create_function(+ FunctionName=fn_name,+ Runtime="python3.9",+ Role="arn:aws:iam::000000000000:role/test-role",+ Handler="index.handler",+ Code={"ZipFile": _alb_zip(fn_code)},+ )+ fn_arn = lam.get_function(FunctionName=fn_name)["Configuration"]["FunctionArn"]++ # ALB infra+ lb_arn = elbv2.create_load_balancer(Name=lb_name)["LoadBalancers"][0]["LoadBalancerArn"]+ tg_arn = elbv2.create_target_group(+ Name=f"{lb_name}-tg", Protocol="HTTP", Port=80,+ VpcId="vpc-00000001", TargetType="lambda",+ )["TargetGroups"][0]["TargetGroupArn"]+ elbv2.register_targets(TargetGroupArn=tg_arn, Targets=[{"Id": fn_arn}])++ l_arn = elbv2.create_listener(+ LoadBalancerArn=lb_arn,+ Protocol="HTTP", Port=listener_port,+ DefaultActions=[{"Type": "forward", "TargetGroupArn": tg_arn}],+ )["Listeners"][0]["ListenerArn"]++ for rule_kwargs in (extra_rules or []):+ elbv2.create_rule(ListenerArn=l_arn, **rule_kwargs)++ return lb_arn, tg_arn, l_arn, fn_arn+++def _alb_teardown(elbv2, lam, lb_arn, tg_arn, l_arn, fn_name):+ try:+ elbv2.delete_listener(ListenerArn=l_arn)+ except Exception:+ pass+ try:+ elbv2.delete_target_group(TargetGroupArn=tg_arn)+ except Exception:+ pass+ try:+ elbv2.delete_load_balancer(LoadBalancerArn=lb_arn)+ except Exception:+ pass+ try:+ lam.delete_function(FunctionName=fn_name)+ except Exception:+ pass+++def test_alb_dataplane_forward_lambda(elbv2, lam):+ """ALB forwards request to Lambda via /_alb/{lb-name}/ path prefix."""+ import urllib.request as _req++ fn_code = (+ "import json\n"+ "def handler(event, context):\n"+ " return {\n"+ " 'statusCode': 200,\n"+ " 'headers': {'Content-Type': 'application/json'},\n"+ " 'body': json.dumps({'method': event['httpMethod'], 'path': event['path']}),\n"+ " }\n"+ )+ lb_arn, tg_arn, l_arn, fn_arn = _alb_setup(+ elbv2, lam, "dp-alb-fwd", "dp-alb-fwd-fn", fn_code+ )+ try:+ url = f"{_endpoint}/_alb/dp-alb-fwd/api/hello"+ resp = _req.urlopen(_req.Request(url, method="GET"))+ assert resp.status == 200+ body = json.loads(resp.read())+ assert body["method"] == "GET"+ assert body["path"] == "/api/hello"+ finally:+ _alb_teardown(elbv2, lam, lb_arn, tg_arn, l_arn, "dp-alb-fwd-fn")+++def test_alb_dataplane_event_shape(elbv2, lam):+ """ALB event passed to Lambda contains all required fields."""+ import urllib.request as _req+ import urllib.parse as _parse++ fn_code = (+ "import json\n"+ "def handler(event, context):\n"+ " return {\n"+ " 'statusCode': 200,\n"+ " 'headers': {'Content-Type': 'application/json'},\n"+ " 'body': json.dumps(event),\n"+ " }\n"+ )+ lb_arn, tg_arn, l_arn, fn_arn = _alb_setup(+ elbv2, lam, "dp-alb-evt", "dp-alb-evt-fn", fn_code+ )+ try:+ url = f"{_endpoint}/_alb/dp-alb-evt/check?foo=bar"+ resp = _req.urlopen(_req.Request(url, method="GET"))+ body = json.loads(resp.read())+ assert "requestContext" in body+ assert "elb" in body["requestContext"]+ assert body["httpMethod"] == "GET"+ assert body["path"] == "/check"+ assert body["queryStringParameters"].get("foo") == "bar"+ assert "headers" in body+ assert body["isBase64Encoded"] is False+ finally:+ _alb_teardown(elbv2, lam, lb_arn, tg_arn, l_arn, "dp-alb-evt-fn")+++def test_alb_dataplane_fixed_response(elbv2, lam):+ """ALB fixed-response action returns configured status/body without invoking Lambda."""+ import urllib.request as _req+ import urllib.error as _err++ fn_code = "def handler(event, context):\n return {'statusCode': 200, 'body': 'should-not-reach'}\n"+ lb_arn = elbv2.create_load_balancer(Name="dp-alb-fixed")["LoadBalancers"][0]["LoadBalancerArn"]+ tg_arn = elbv2.create_target_group(+ Name="dp-alb-fixed-tg", Protocol="HTTP", Port=80,+ VpcId="vpc-00000001", TargetType="lambda",+ )["TargetGroups"][0]["TargetGroupArn"]+ l_arn = elbv2.create_listener(+ LoadBalancerArn=lb_arn, Protocol="HTTP", Port=80,+ DefaultActions=[{+ "Type": "fixed-response",+ "FixedResponseConfig": {+ "StatusCode": "200",+ "ContentType": "text/plain",+ "MessageBody": "maintenance",+ },+ }],+ )["Listeners"][0]["ListenerArn"]+ try:+ url = f"{_endpoint}/_alb/dp-alb-fixed/any/path"+ resp = _req.urlopen(_req.Request(url, method="GET"))+ assert resp.status == 200+ assert resp.read() == b"maintenance"+ finally:+ elbv2.delete_listener(ListenerArn=l_arn)+ elbv2.delete_target_group(TargetGroupArn=tg_arn)+ elbv2.delete_load_balancer(LoadBalancerArn=lb_arn)+ try:+ lam.delete_function(FunctionName="dp-alb-fixed-fn")+ except Exception:+ pass+++def test_alb_dataplane_redirect(elbv2):+ """ALB redirect action returns 301 with a Location header."""+ import http.client as _http+ from urllib.parse import urlparse as _urlparse++ lb_arn = elbv2.create_load_balancer(Name="dp-alb-redir")["LoadBalancers"][0]["LoadBalancerArn"]+ tg_arn = elbv2.create_target_group(+ Name="dp-alb-redir-tg", Protocol="HTTP", Port=80,+ VpcId="vpc-00000001", TargetType="lambda",+ )["TargetGroups"][0]["TargetGroupArn"]+ l_arn = elbv2.create_listener(+ LoadBalancerArn=lb_arn, Protocol="HTTP", Port=80,+ DefaultActions=[{+ "Type": "redirect",+ "RedirectConfig": {+ "Protocol": "https",+ "Host": "example.com",+ "Path": "/new",+ "StatusCode": "HTTP_301",+ },+ }],+ )["Listeners"][0]["ListenerArn"]+ try:+ # Use http.client directly — it never auto-follows redirects+ parsed = _urlparse(_endpoint)+ conn = _http.HTTPConnection(parsed.hostname, parsed.port or 4566)+ conn.request("GET", "/_alb/dp-alb-redir/old")+ resp = conn.getresponse()+ assert resp.status == 301+ location = resp.getheader("Location", "")+ assert "example.com" in location+ conn.close()+ finally:+ elbv2.delete_listener(ListenerArn=l_arn)+ elbv2.delete_target_group(TargetGroupArn=tg_arn)+ elbv2.delete_load_balancer(LoadBalancerArn=lb_arn)+++def test_alb_dataplane_path_pattern_rule(elbv2, lam):+ """Path-pattern rule routes /api/* to one Lambda; default routes to another."""+ import urllib.request as _req++ api_code = (+ "import json\n"+ "def handler(event, context):\n"+ " return {'statusCode': 200, 'headers': {'Content-Type': 'application/json'},\n"+ " 'body': json.dumps({'target': 'api'})}\n"+ )+ default_code = (+ "import json\n"+ "def handler(event, context):\n"+ " return {'statusCode': 200, 'headers': {'Content-Type': 'application/json'},\n"+ " 'body': json.dumps({'target': 'default'})}\n"+ )+ for fn_name, fn_code in [("dp-alb-api-fn", api_code), ("dp-alb-def-fn", default_code)]:+ lam.create_function(+ FunctionName=fn_name, Runtime="python3.9",+ Role="arn:aws:iam::000000000000:role/test-role",+ Handler="index.handler", Code={"ZipFile": _alb_zip(fn_code)},+ )++ lb_arn = elbv2.create_load_balancer(Name="dp-alb-rules")["LoadBalancers"][0]["LoadBalancerArn"]+ api_tg_arn = elbv2.create_target_group(+ Name="dp-alb-api-tg", Protocol="HTTP", Port=80,+ VpcId="vpc-00000001", TargetType="lambda",+ )["TargetGroups"][0]["TargetGroupArn"]+ def_tg_arn = elbv2.create_target_group(+ Name="dp-alb-def-tg", Protocol="HTTP", Port=80,+ VpcId="vpc-00000001", TargetType="lambda",+ )["TargetGroups"][0]["TargetGroupArn"]++ api_fn_arn = lam.get_function(FunctionName="dp-alb-api-fn")["Configuration"]["FunctionArn"]+ def_fn_arn = lam.get_function(FunctionName="dp-alb-def-fn")["Configuration"]["FunctionArn"]+ elbv2.register_targets(TargetGroupArn=api_tg_arn, Targets=[{"Id": api_fn_arn}])+ elbv2.register_targets(TargetGroupArn=def_tg_arn, Targets=[{"Id": def_fn_arn}])++ l_arn = elbv2.create_listener(+ LoadBalancerArn=lb_arn, Protocol="HTTP", Port=80,+ DefaultActions=[{"Type": "forward", "TargetGroupArn": def_tg_arn}],+ )["Listeners"][0]["ListenerArn"]+ elbv2.create_rule(+ ListenerArn=l_arn, Priority=10,+ Conditions=[{"Field": "path-pattern", "Values": ["/api/*"]}],+ Actions=[{"Type": "forward", "TargetGroupArn": api_tg_arn}],+ )++ try:+ # /api/* hits the api Lambda+ resp_api = _req.urlopen(_req.Request(f"{_endpoint}/_alb/dp-alb-rules/api/users", method="GET"))+ body_api = json.loads(resp_api.read())+ assert body_api["target"] == "api"++ # /other hits the default Lambda+ resp_def = _req.urlopen(_req.Request(f"{_endpoint}/_alb/dp-alb-rules/other", method="GET"))+ body_def = json.loads(resp_def.read())+ assert body_def["target"] == "default"+ finally:+ elbv2.delete_listener(ListenerArn=l_arn)+ for tg in (api_tg_arn, def_tg_arn):+ elbv2.delete_target_group(TargetGroupArn=tg)+ elbv2.delete_load_balancer(LoadBalancerArn=lb_arn)+ for fn_name in ("dp-alb-api-fn", "dp-alb-def-fn"):+ try:+ lam.delete_function(FunctionName=fn_name)+ except Exception:+ pass+++def test_alb_dataplane_no_listener_returns_503(elbv2):+ """Request to an ALB with no listeners returns 503."""+ import urllib.request as _req+ import urllib.error as _err++ lb_arn = elbv2.create_load_balancer(Name="dp-alb-empty")["LoadBalancers"][0]["LoadBalancerArn"]+ try:+ req = _req.Request(f"{_endpoint}/_alb/dp-alb-empty/anything", method="GET")+ try:+ _req.urlopen(req)+ assert False, "Expected 503"+ except _err.HTTPError as e:+ assert e.code == 503+ finally:+ elbv2.delete_load_balancer(LoadBalancerArn=lb_arn)+++def test_alb_dataplane_host_header_routing(elbv2, lam):+ """ALB matches requests by {lb-name}.alb.localhost Host header."""+ import urllib.request as _req++ fn_code = (+ "import json\n"+ "def handler(event, context):\n"+ " return {'statusCode': 200, 'headers': {'Content-Type': 'application/json'},\n"+ " 'body': json.dumps({'routed': True})}\n"+ )+ lb_arn, tg_arn, l_arn, fn_arn = _alb_setup(+ elbv2, lam, "dp-alb-host", "dp-alb-host-fn", fn_code+ )+ try:+ # Send to the plain ministack port but with the ALB host header+ req = _req.Request(f"{_endpoint}/hello", method="GET")+ req.add_header("Host", f"dp-alb-host.alb.localhost:{_EXECUTE_PORT}")+ resp = _req.urlopen(req)+ assert resp.status == 200+ body = json.loads(resp.read())+ assert body["routed"] is True+ finally:+ _alb_teardown(elbv2, lam, lb_arn, tg_arn, l_arn, "dp-alb-host-fn")# EBS (Elastic Block Store) — uses ec2 client# ---------------------------------------------------------------------------