Repository navigation
Expand file tree
/
Copy pathtest_alb.py
More file actions
1869 lines (1576 loc) · 73.3 KB
/
Copy pathtest_alb.py
File metadata and controls
1869 lines (1576 loc) · 73.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import io
import json
import os
import time
import urllib.request as _req
import uuid as _uuid_mod
import zipfile
from urllib.error import HTTPError
from urllib.parse import parse_qs, urlparse
import pytest
from botocore.exceptions import ClientError
_endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
_EXECUTE_PORT = urlparse(_endpoint).port or 4566
# Predict the server-side loopback port. Under the matched-port protocol,
# MINISTACK_ENDPOINT alone implies a direct connection (endpoint port == server port);
# split-port topologies must export GATEWAY_PORT/EDGE_PORT into the test env.
_SERVER_GATEWAY_PORT = int(
os.environ.get("GATEWAY_PORT") or os.environ.get("EDGE_PORT") or _EXECUTE_PORT
)
def test_elbv2_arn_tail_helpers_require_elbv2_resource_scope():
from ministack.services import alb
assert alb._load_balancer_id_from_arn(
"arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/app/my-lb/lb-id"
) == "lb-id"
assert alb._listener_id_from_arn(
"arn:aws:elasticloadbalancing:us-east-1:000000000000:listener/app/my-lb/lb-id/listener-id"
) == "listener-id"
assert alb._target_group_full_name_from_arn(
"arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/my-tg/tg-id"
) == "my-tg/tg-id"
assert alb._load_balancer_id_from_arn(
"arn:aws:sqs:us-east-1:000000000000:loadbalancer/app/my-lb/lb-id"
) == ""
assert alb._listener_id_from_arn(
"arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/my-tg/tg-id"
) == ""
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_describe_listener_attributes(elbv2):
lb_arn = elbv2.create_load_balancer(Name="qa-alb-listener-attrs")["LoadBalancers"][0]["LoadBalancerArn"]
tg_arn = elbv2.create_target_group(
Name="qa-tg-la",
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"]
resp = elbv2.describe_listener_attributes(ListenerArn=l_arn)
attrs = {a["Key"]: a["Value"] for a in resp["Attributes"]}
assert attrs.get("routing.http.response.server.enabled") == "true"
elbv2.delete_listener(ListenerArn=l_arn)
elbv2.delete_target_group(TargetGroupArn=tg_arn)
elbv2.delete_load_balancer(LoadBalancerArn=lb_arn)
def test_elbv2_describe_listener_attributes_not_found(elbv2):
with pytest.raises(ClientError) as exc:
elbv2.describe_listener_attributes(ListenerArn="arn:aws:elasticloadbalancing:us-east-1:000000000000:listener/app/missing/abc/def")
assert exc.value.response["Error"]["Code"] == "ListenerNotFound"
def test_elbv2_modify_listener_attributes(elbv2):
lb_arn = elbv2.create_load_balancer(Name="qa-alb-mod-listener-attrs")["LoadBalancers"][0]["LoadBalancerArn"]
tg_arn = elbv2.create_target_group(
Name="qa-tg-mla",
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"]
resp = elbv2.modify_listener_attributes(
ListenerArn=l_arn,
Attributes=[
{"Key": "routing.http.response.server.enabled", "Value": "false"},
{"Key": "routing.http.response.strict_transport_security.header_value", "Value": "max-age=31536000"},
],
)
attrs = {a["Key"]: a["Value"] for a in resp["Attributes"]}
assert attrs["routing.http.response.server.enabled"] == "false"
assert attrs["routing.http.response.strict_transport_security.header_value"] == "max-age=31536000"
desc = elbv2.describe_listener_attributes(ListenerArn=l_arn)
desc_attrs = {a["Key"]: a["Value"] for a in desc["Attributes"]}
assert desc_attrs["routing.http.response.server.enabled"] == "false"
assert desc_attrs["routing.http.response.strict_transport_security.header_value"] == "max-age=31536000"
elbv2.delete_listener(ListenerArn=l_arn)
elbv2.delete_target_group(TargetGroupArn=tg_arn)
elbv2.delete_load_balancer(LoadBalancerArn=lb_arn)
def test_elbv2_modify_listener_attributes_not_found(elbv2):
with pytest.raises(ClientError) as exc:
elbv2.modify_listener_attributes(
ListenerArn="arn:aws:elasticloadbalancing:us-east-1:000000000000:listener/app/missing/abc/def",
Attributes=[{"Key": "routing.http.response.server.enabled", "Value": "false"}],
)
assert exc.value.response["Error"]["Code"] == "ListenerNotFound"
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)
@pytest.mark.parametrize(
("arn", "code"),
[
("not-an-arn", "ValidationError"),
(
"arn:aws:sqs:us-east-1:000000000000:loadbalancer/app/qa-alb-tags/missing",
"ValidationError",
),
(
"arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/qa-alb-tags/missing",
"ValidationError",
),
(
"arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/app/qa-alb-tags/missing",
"LoadBalancerNotFound",
),
],
)
def test_elbv2_tag_arns_must_parse_to_local_resources(elbv2, arn, code):
with pytest.raises(ClientError) as exc:
elbv2.add_tags(ResourceArns=[arn], Tags=[{"Key": "env", "Value": "test"}])
assert exc.value.response["Error"]["Code"] == code
def test_elbv2_add_tags_validates_all_arns_before_mutating(elbv2):
lb_arn = elbv2.create_load_balancer(Name="qa-alb-tags-atomic")["LoadBalancers"][0]["LoadBalancerArn"]
missing_arn = (
"arn:aws:elasticloadbalancing:us-east-1:000000000000:"
"loadbalancer/app/qa-alb-tags-atomic/missing"
)
with pytest.raises(ClientError) as exc:
elbv2.add_tags(
ResourceArns=[lb_arn, missing_arn],
Tags=[{"Key": "team", "Value": "infra"}],
)
assert exc.value.response["Error"]["Code"] == "LoadBalancerNotFound"
desc = elbv2.describe_tags(ResourceArns=[lb_arn])
assert desc["TagDescriptions"][0]["Tags"] == []
elbv2.delete_load_balancer(LoadBalancerArn=lb_arn)
# Migrated from test_alb.py
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.12",
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
@pytest.mark.serial
def test_elbv2_dataplane_forward_lambda(elbv2, lam, cw):
"""ALB forwards request to Lambda via /_alb/{lb-name}/ path prefix."""
import urllib.request as _req
fn_name = "dp-alb-fwd-fn"
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", fn_name, 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"
end = time.time() + 60
start = end - 600
invocations = cw.get_metric_statistics(
Namespace="AWS/Lambda",
MetricName="Invocations",
Dimensions=[{"Name": "FunctionName", "Value": fn_name}],
StartTime=start,
EndTime=end,
Period=60,
Statistics=["Sum"],
)
total = sum(p["Sum"] for p in invocations["Datapoints"])
assert total >= 1, f"expected ALB Lambda target to emit metrics, got {total}"
finally:
_alb_teardown(elbv2, lam, lb_arn, tg_arn, l_arn, fn_name)
@pytest.mark.serial
def test_elbv2_dataplane_lambda_target_emits_metrics(elbv2, lam, cw):
import urllib.request as _req
suffix = _uuid_mod.uuid4().hex[:8]
lb_name = f"alb-met-{suffix}"
fn_name = f"alb-met-fn-{suffix}"
fn_code = (
"def handler(event, context):\n"
" return {'statusCode': 200, 'body': 'ok'}\n"
)
lb_arn, tg_arn, l_arn, _fn_arn = _alb_setup(elbv2, lam, lb_name, fn_name, fn_code)
try:
url = f"{_endpoint}/_alb/{lb_name}/metrics"
resp = _req.urlopen(_req.Request(url, method="GET"))
assert resp.status == 200
end = time.time() + 1
start = end - 600
invocations = cw.get_metric_statistics(
Namespace="AWS/Lambda",
MetricName="Invocations",
Dimensions=[{"Name": "FunctionName", "Value": fn_name}],
StartTime=start, EndTime=end,
Period=60, Statistics=["Sum"],
)
total = sum(p["Sum"] for p in invocations["Datapoints"])
assert total >= 1, f"expected >=1 invocation, got {total}"
duration = cw.get_metric_statistics(
Namespace="AWS/Lambda",
MetricName="Duration",
Dimensions=[{"Name": "FunctionName", "Value": fn_name}],
StartTime=start, EndTime=end,
Period=60, Statistics=["Average"],
)
assert duration["Datapoints"], "no Duration datapoints recorded"
finally:
_alb_teardown(elbv2, lam, lb_arn, tg_arn, l_arn, fn_name)
def test_elbv2_dataplane_event_shape(elbv2, lam):
"""ALB event passed to Lambda contains all required fields."""
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(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_elbv2_dataplane_fixed_response(elbv2, lam):
"""ALB fixed-response action returns configured status/body without invoking Lambda."""
import urllib.request as _req
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_elbv2_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_elbv2_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.12",
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_elbv2_dataplane_no_listener_returns_503(elbv2):
"""Request to an ALB with no listeners returns 503."""
import urllib.error as _err
import urllib.request as _req
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_elbv2_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")
def test_alb_set_subnets_updates_lb(elbv2):
"""SetSubnets replaces the LB's Subnets and returns AvailabilityZones."""
arn = elbv2.create_load_balancer(
Name="qa-alb-setsub",
Subnets=["subnet-aaa"],
)["LoadBalancers"][0]["LoadBalancerArn"]
resp = elbv2.set_subnets(LoadBalancerArn=arn, Subnets=["subnet-bbb", "subnet-ccc"])
assert resp["IpAddressType"] in ("ipv4", "dualstack", "dualstack-without-public-ipv4")
zone_subnets = {z["SubnetId"] for z in resp["AvailabilityZones"]}
assert zone_subnets == {"subnet-bbb", "subnet-ccc"}
def test_alb_set_ip_address_type(elbv2):
arn = elbv2.create_load_balancer(Name="qa-alb-setip")["LoadBalancers"][0]["LoadBalancerArn"]
resp = elbv2.set_ip_address_type(LoadBalancerArn=arn, IpAddressType="dualstack")
assert resp["IpAddressType"] == "dualstack"
desc = elbv2.describe_load_balancers(LoadBalancerArns=[arn])["LoadBalancers"][0]
assert desc["IpAddressType"] == "dualstack"
def test_alb_set_security_groups(elbv2):
"""SetSecurityGroups returns SecurityGroupIds per botocore output shape."""
arn = elbv2.create_load_balancer(
Name="qa-alb-setsg",
SecurityGroups=["sg-aaa"],
)["LoadBalancers"][0]["LoadBalancerArn"]
resp = elbv2.set_security_groups(LoadBalancerArn=arn, SecurityGroups=["sg-bbb", "sg-ccc"])
assert resp["SecurityGroupIds"] == ["sg-bbb", "sg-ccc"]
def _alb_http_target_setup(elbv2, lb_name, target_id, target_port, target_type="ip"):
"""Create LB + instance/ip TG + listener + register an HTTP target.
Returns (lb_arn, tg_arn, l_arn).
"""
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=target_port,
VpcId="vpc-00000001",
TargetType=target_type,
)["TargetGroups"][0]["TargetGroupArn"]
elbv2.register_targets(TargetGroupArn=tg_arn, Targets=[{"Id": target_id, "Port": target_port}])
l_arn = elbv2.create_listener(
LoadBalancerArn=lb_arn,
Protocol="HTTP",
Port=80,
DefaultActions=[{"Type": "forward", "TargetGroupArn": tg_arn}],
)["Listeners"][0]["ListenerArn"]
return lb_arn, tg_arn, l_arn
def _alb_http_target_teardown(elbv2, lb_arn, tg_arn, l_arn):
for fn, kwargs in (
(elbv2.delete_listener, {"ListenerArn": l_arn}),
(elbv2.delete_target_group, {"TargetGroupArn": tg_arn}),
(elbv2.delete_load_balancer, {"LoadBalancerArn": lb_arn}),
):
try:
fn(**kwargs)
except Exception:
pass
@pytest.mark.serial
def test_elbv2_dataplane_forward_ip_target(elbv2):
"""ALB data plane proxies instance/ip targets over HTTP.
The emulator's own health endpoint (127.0.0.1 at the configured gateway port from inside the
server process) doubles as the backend, so the test needs no external
HTTP server and works both in-container and locally.
"""
import urllib.request as _req
lb_name = "dp-alb-ip"
lb_arn, tg_arn, l_arn = _alb_http_target_setup(
elbv2, lb_name, "127.0.0.1", _SERVER_GATEWAY_PORT
)
try:
url = f"{_endpoint}/_alb/{lb_name}/_ministack/health"
resp = _req.urlopen(_req.Request(url, method="GET"))
assert resp.status == 200
body = json.loads(resp.read())
assert "services" in body
finally:
_alb_http_target_teardown(elbv2, lb_arn, tg_arn, l_arn)
def _start_chunked_server(chunks, delay):
"""Serve `chunks` with `delay` seconds between them and no Content-Length."""
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class _Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "application/octet-stream")
self.send_header("Transfer-Encoding", "chunked")
self.end_headers()
for i, chunk in enumerate(chunks):
if i:
time.sleep(delay)
self.wfile.write(b"%x\r\n%s\r\n" % (len(chunk), chunk))
self.wfile.flush()
self.wfile.write(b"0\r\n\r\n")
self.wfile.flush()
def log_message(self, _format, *_args):
return
server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
return server, thread
def _start_fixed_body_server(body):
"""Serve `body` in one shot with a Content-Length."""
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class _Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "application/octet-stream")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, _format, *_args):
return
server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
return server, thread
def _set_alb_config(**values):
"""Set alb module config on the server via the runtime config endpoint."""
import urllib.request as _req
payload = json.dumps({f"alb.{k}": v for k, v in values.items()}).encode()
_req.urlopen(_req.Request(f"{_endpoint}/_ministack/config", data=payload, method="POST"))
def _start_dying_chunked_server(chunk):
"""Chunked target that sends one chunk then dies without the 0-length end.
Chunked is the framing where a premature close is invisible: there is no
declared length for the client to check, so a proxy that terminates the
body cleanly makes a truncated stream look finished.
"""
import socket
import threading
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", 0))
sock.listen(1)
def _serve():
try:
conn, _ = sock.accept()
conn.recv(4096)
conn.sendall(
b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n"
b"Transfer-Encoding: chunked\r\n\r\n"
b"%x\r\n%s\r\n" % (len(chunk), chunk)
)
conn.close()
except OSError:
pass
thread = threading.Thread(target=_serve, daemon=True)
thread.start()
return sock, thread
@pytest.mark.serial
def test_elbv2_dataplane_truncated_target_body_is_not_passed_off_as_complete(elbv2):
"""A target that dies mid-body must not read as a short but valid response.
The proxy must withhold the terminating frame, otherwise a truncated
chunked stream reaches the client as a well-formed one and there is nothing
left for it to detect.
"""
import urllib.request as _req
sock, thread = _start_dying_chunked_server(b"partial")
port = sock.getsockname()[1]
lb_name = "dp-alb-dying"
lb_arn, tg_arn, l_arn = _alb_http_target_setup(elbv2, lb_name, "127.0.0.1", port)
try:
resp = _req.urlopen(_req.Request(f"{_endpoint}/_alb/{lb_name}/", method="GET"))
with pytest.raises(Exception) as excinfo:
resp.read()
assert "IncompleteRead" in type(excinfo.value).__name__ or "Incomplete" in str(excinfo.value)
finally:
_alb_http_target_teardown(elbv2, lb_arn, tg_arn, l_arn)
sock.close()
thread.join(timeout=5)
def _start_raw_server(script):
"""Serve one connection by running `script(conn)` on a raw socket."""
import socket as _socket
import threading
sock = _socket.socket()
sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", 0))
sock.listen(1)
def _serve():
try:
conn, _ = sock.accept()
conn.recv(4096)
script(conn)
conn.close()
except OSError:
pass
thread = threading.Thread(target=_serve, daemon=True)
thread.start()
return sock, thread
@pytest.mark.parametrize("chunked", [False, True], ids=["content-length", "chunked"])
@pytest.mark.parametrize("cookie_names", [
["Set-Cookie", "Set-Cookie", "Set-Cookie"],