Repository navigation
Expand file tree
/
Copy pathtest_eks.py
More file actions
1984 lines (1691 loc) · 78 KB
/
Copy pathtest_eks.py
File metadata and controls
1984 lines (1691 loc) · 78 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
"""
Integration tests for EKS service emulator.
Tests cluster CRUD, nodegroup CRUD, tags, and CloudFormation provisioning.
k3s Docker container tests require Docker socket access.
"""
import asyncio
import base64
import datetime as dt
import json
import os
import threading
import time
import uuid
from types import SimpleNamespace
from unittest.mock import patch
from urllib.parse import quote
import boto3
import pytest
from botocore.auth import SigV4Auth, SigV4QueryAuth
from botocore.awsrequest import AWSRequest
from botocore.credentials import Credentials
from botocore.exceptions import ClientError
import ministack.app as app
from ministack.core.responses import AccountRegionScopedDict, AccountScopedDict, request_scope
from ministack.services import eks as eks_service
from ministack.services import iam, sts
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
REGION = "us-east-1"
@pytest.fixture(scope="module")
def eks():
return boto3.client("eks", endpoint_url=ENDPOINT,
aws_access_key_id="test", aws_secret_access_key="test",
region_name=REGION)
@pytest.fixture(scope="module")
def cfn():
return boto3.client("cloudformation", endpoint_url=ENDPOINT,
aws_access_key_id="test", aws_secret_access_key="test",
region_name=REGION)
def _uid():
return uuid.uuid4().hex[:8]
@pytest.fixture
def eks_mod(monkeypatch):
from ministack.core.responses import set_request_account_id, set_request_region
from ministack.services import eks as eks_service
monkeypatch.setattr(eks_service, "_get_docker", lambda: None)
set_request_account_id("000000000000")
set_request_region(REGION)
eks_service.reset()
yield eks_service
eks_service.reset()
def _eks_direct(eks_service, method, path, body=None, query=None):
payload = json.dumps(body or {}).encode("utf-8") if body is not None else b""
status, headers, raw_body = asyncio.run(
eks_service.handle_request(method, path, {}, payload, query or {})
)
if raw_body:
parsed_body = json.loads(raw_body.decode("utf-8"))
else:
parsed_body = {}
return status, headers, parsed_body
def _eks_direct_create_cluster(eks_service, name):
status, _headers, body = _eks_direct(
eks_service,
"POST",
"/clusters",
{
"name": name,
"roleArn": "arn:aws:iam::000000000000:role/eks-role",
"resourcesVpcConfig": {},
},
)
assert status == 200
return body["cluster"]["arn"]
def _eks_exec_token(cluster_name, access_key="test", secret_key="test"):
request = AWSRequest(
method="GET",
url="https://sts.us-east-1.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15",
headers={"x-k8s-aws-id": cluster_name},
)
SigV4QueryAuth(
Credentials(access_key, secret_key), "sts", "us-east-1", expires=60
).add_auth(request)
encoded = base64.urlsafe_b64encode(request.url.encode()).decode().rstrip("=")
return "k8s-aws-v1." + encoded
# ---------------------------------------------------------------------------
# Cluster CRUD
# ---------------------------------------------------------------------------
def test_eks_create_describe_delete_cluster(eks):
"""Test EKS API contract: create → describe → delete → gone."""
name = f"test-cluster-{_uid()}"
resp = eks.create_cluster(
name=name,
version="1.30",
roleArn="arn:aws:iam::000000000000:role/eks-role",
resourcesVpcConfig={"subnetIds": ["subnet-1", "subnet-2"]},
)
cluster = resp["cluster"]
assert cluster["name"] == name
assert cluster["status"] in ("CREATING", "ACTIVE")
assert cluster["version"] == "1.30"
assert "arn" in cluster
assert f"cluster/{name}" in cluster["arn"]
assert "endpoint" in cluster
assert "certificateAuthority" in cluster
assert "identity" in cluster
assert "oidc" in cluster["identity"]
# Describe — wait for background thread to finish.
# In CI the first describe can transiently fail; retry with backoff.
resp = None
for attempt in range(60):
try:
resp = eks.describe_cluster(name=name)
if resp["cluster"]["status"] == "ACTIVE":
break
except ClientError as e:
if e.response["Error"]["Code"] != "ResourceNotFoundException":
raise
time.sleep(0.5)
assert resp is not None, f"Cluster {name} never became describable after 30s"
assert resp["cluster"]["name"] == name
assert resp["cluster"]["status"] in ("ACTIVE", "CREATING")
# Delete
resp = eks.delete_cluster(name=name)
assert resp["cluster"]["name"] == name
# Verify gone
with pytest.raises(ClientError) as exc:
eks.describe_cluster(name=name)
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
def test_eks_create_duplicate_cluster(eks):
name = f"dup-cluster-{_uid()}"
eks.create_cluster(name=name, roleArn="arn:aws:iam::000000000000:role/r",
resourcesVpcConfig={})
with pytest.raises(ClientError) as exc:
eks.create_cluster(name=name, roleArn="arn:aws:iam::000000000000:role/r",
resourcesVpcConfig={})
assert exc.value.response["Error"]["Code"] == "ResourceInUseException"
eks.delete_cluster(name=name)
def test_eks_list_clusters(eks):
name = f"list-cluster-{_uid()}"
eks.create_cluster(name=name, roleArn="arn:aws:iam::000000000000:role/r",
resourcesVpcConfig={})
resp = eks.list_clusters()
assert name in resp["clusters"]
eks.delete_cluster(name=name)
def test_eks_resources_are_region_scoped_direct(eks_mod):
"""Same-name clusters and children remain independent across regions."""
from ministack.core.responses import set_request_region
cluster_name = f"regional-{_uid()}"
nodegroup_name = "workers"
addon_name = "vpc-cni"
idp_name = "regional-idp"
principal_arn = "arn:aws:iam::000000000000:role/regional-access"
policy_arn = (
"arn:aws:eks::aws:cluster-access-policy/AmazonEKSViewPolicy"
)
regions = {
"us-east-1": "east",
"us-west-2": "west",
}
cluster_arns = {}
for region, marker in regions.items():
set_request_region(region)
cluster_arn = _eks_direct_create_cluster(eks_mod, cluster_name)
cluster_arns[region] = cluster_arn
assert f":{region}:" in cluster_arn
status, _headers, _body = _eks_direct(
eks_mod,
"POST",
f"/clusters/{cluster_name}/node-groups",
{
"nodegroupName": nodegroup_name,
"nodeRole": "arn:aws:iam::000000000000:role/node-role",
"subnets": ["subnet-1"],
},
)
assert status == 200
status, _headers, _body = _eks_direct(
eks_mod,
"POST",
f"/clusters/{cluster_name}/addons",
{"addonName": addon_name},
)
assert status == 200
status, _headers, _body = _eks_direct(
eks_mod,
"POST",
f"/clusters/{cluster_name}/access-entries",
{"principalArn": principal_arn},
)
assert status == 200
encoded_principal = quote(principal_arn, safe="")
status, _headers, _body = _eks_direct(
eks_mod,
"POST",
(
f"/clusters/{cluster_name}/access-entries/"
f"{encoded_principal}/access-policies"
),
{
"policyArn": policy_arn,
"accessScope": {"type": "cluster", "namespaces": []},
},
)
assert status == 200
status, _headers, _body = _eks_direct(
eks_mod,
"POST",
f"/clusters/{cluster_name}/identity-provider-configs/associate",
{
"oidc": {
"identityProviderConfigName": idp_name,
"issuerUrl": f"https://{marker}.example/issuer",
"clientId": f"{marker}-client",
},
},
)
assert status == 200
status, _headers, _body = _eks_direct(
eks_mod,
"POST",
f"/tags/{quote(cluster_arn, safe='')}",
{"tags": {"region": marker}},
)
assert status == 200
for region, marker in regions.items():
set_request_region(region)
status, _headers, body = _eks_direct(
eks_mod, "GET", f"/clusters/{cluster_name}"
)
assert status == 200
assert body["cluster"]["arn"] == cluster_arns[region]
status, _headers, body = _eks_direct(
eks_mod, "GET", f"/clusters/{cluster_name}/node-groups"
)
assert status == 200
assert body["nodegroups"] == [nodegroup_name]
status, _headers, body = _eks_direct(
eks_mod, "GET", f"/clusters/{cluster_name}/addons"
)
assert status == 200
assert body["addons"] == [addon_name]
status, _headers, body = _eks_direct(
eks_mod, "GET", f"/clusters/{cluster_name}/access-entries"
)
assert status == 200
assert body["accessEntries"] == [principal_arn]
status, _headers, body = _eks_direct(
eks_mod,
"GET",
(
f"/clusters/{cluster_name}/access-entries/"
f"{quote(principal_arn, safe='')}/access-policies"
),
)
assert status == 200
assert [policy["policyArn"] for policy in body["associatedAccessPolicies"]] == [
policy_arn
]
status, _headers, body = _eks_direct(
eks_mod,
"POST",
f"/clusters/{cluster_name}/identity-provider-configs/describe",
{"identityProviderConfig": {"type": "oidc", "name": idp_name}},
)
assert status == 200
oidc = body["identityProviderConfig"]["oidc"]
assert oidc["clientId"] == f"{marker}-client"
status, _headers, body = _eks_direct(
eks_mod,
"GET",
f"/tags/{quote(cluster_arns[region], safe='')}",
)
assert status == 200
assert body["tags"] == {"region": marker}
set_request_region("us-east-1")
status, _headers, _body = _eks_direct(
eks_mod, "DELETE", f"/clusters/{cluster_name}"
)
assert status == 200
set_request_region("us-west-2")
status, _headers, body = _eks_direct(
eks_mod, "GET", f"/clusters/{cluster_name}"
)
assert status == 200
assert body["cluster"]["arn"] == cluster_arns["us-west-2"]
status, _headers, body = _eks_direct(
eks_mod, "GET", f"/clusters/{cluster_name}/node-groups"
)
assert status == 200
assert body["nodegroups"] == [nodegroup_name]
def test_eks_delete_nonexistent_cluster(eks):
with pytest.raises(ClientError) as exc:
eks.delete_cluster(name="nonexistent-cluster-xyz")
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
# ---------------------------------------------------------------------------
# Nodegroup CRUD
# ---------------------------------------------------------------------------
def test_eks_create_describe_delete_nodegroup(eks):
cluster = f"ng-cluster-{_uid()}"
eks.create_cluster(name=cluster, roleArn="arn:aws:iam::000000000000:role/r",
resourcesVpcConfig={})
ng_name = f"ng-{_uid()}"
resp = eks.create_nodegroup(
clusterName=cluster,
nodegroupName=ng_name,
scalingConfig={"minSize": 1, "maxSize": 3, "desiredSize": 2},
instanceTypes=["t3.large"],
nodeRole="arn:aws:iam::000000000000:role/node-role",
subnets=["subnet-1"],
diskSize=50,
)
ng = resp["nodegroup"]
assert ng["nodegroupName"] == ng_name
assert ng["clusterName"] == cluster
assert ng["status"] == "ACTIVE"
assert ng["scalingConfig"]["desiredSize"] == 2
assert ng["instanceTypes"] == ["t3.large"]
assert ng["diskSize"] == 50
assert "nodegroupArn" in ng
# Describe
resp = eks.describe_nodegroup(clusterName=cluster, nodegroupName=ng_name)
assert resp["nodegroup"]["nodegroupName"] == ng_name
# List
resp = eks.list_nodegroups(clusterName=cluster)
assert ng_name in resp["nodegroups"]
# Delete
resp = eks.delete_nodegroup(clusterName=cluster, nodegroupName=ng_name)
assert resp["nodegroup"]["status"] == "DELETING"
# Verify gone
with pytest.raises(ClientError) as exc:
eks.describe_nodegroup(clusterName=cluster, nodegroupName=ng_name)
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
eks.delete_cluster(name=cluster)
def test_eks_nodegroup_nonexistent_cluster(eks):
with pytest.raises(ClientError) as exc:
eks.create_nodegroup(clusterName="no-such-cluster", nodegroupName="ng1",
nodeRole="arn:aws:iam::000000000000:role/r",
subnets=["subnet-1"])
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
def test_eks_delete_cluster_cascades_nodegroups(eks):
cluster = f"cascade-{_uid()}"
eks.create_cluster(name=cluster, roleArn="arn:aws:iam::000000000000:role/r",
resourcesVpcConfig={})
for i in range(3):
eks.create_nodegroup(clusterName=cluster, nodegroupName=f"ng-{i}",
nodeRole="arn:aws:iam::000000000000:role/r",
subnets=["subnet-1"])
resp = eks.list_nodegroups(clusterName=cluster)
assert len(resp["nodegroups"]) == 3
eks.delete_cluster(name=cluster)
with pytest.raises(ClientError):
eks.list_nodegroups(clusterName=cluster)
# ---------------------------------------------------------------------------
# Tags
# ---------------------------------------------------------------------------
def test_eks_tag_cluster(eks):
name = f"tag-cluster-{_uid()}"
eks.create_cluster(name=name, roleArn="arn:aws:iam::000000000000:role/r",
resourcesVpcConfig={}, tags={"env": "test"})
arn = eks.describe_cluster(name=name)["cluster"]["arn"]
resp = eks.list_tags_for_resource(resourceArn=arn)
assert resp["tags"]["env"] == "test"
eks.tag_resource(resourceArn=arn, tags={"team": "platform"})
resp = eks.list_tags_for_resource(resourceArn=arn)
assert resp["tags"]["team"] == "platform"
assert resp["tags"]["env"] == "test"
eks.untag_resource(resourceArn=arn, tagKeys=["env"])
resp = eks.list_tags_for_resource(resourceArn=arn)
assert "env" not in resp["tags"]
assert resp["tags"]["team"] == "platform"
eks.delete_cluster(name=name)
def test_eks_tag_resource_accepts_supported_local_arn_shapes_direct(eks_mod):
cluster = f"tag-shapes-{_uid()}"
cluster_arn = _eks_direct_create_cluster(eks_mod, cluster)
status, _headers, body = _eks_direct(
eks_mod,
"POST",
f"/clusters/{cluster}/node-groups",
{
"nodegroupName": "workers",
"nodeRole": "arn:aws:iam::000000000000:role/node-role",
"subnets": ["subnet-1"],
},
)
assert status == 200
nodegroup_arn = body["nodegroup"]["nodegroupArn"]
status, _headers, body = _eks_direct(
eks_mod,
"POST",
f"/clusters/{cluster}/addons",
{"addonName": "vpc-cni"},
)
assert status == 200
addon_arn = body["addon"]["addonArn"]
principal = "arn:aws:iam::000000000000:role/eks-access"
status, _headers, body = _eks_direct(
eks_mod,
"POST",
f"/clusters/{cluster}/access-entries",
{"principalArn": principal},
)
assert status == 200
access_entry_arn = body["accessEntry"]["accessEntryArn"]
status, _headers, _body = _eks_direct(
eks_mod,
"POST",
f"/clusters/{cluster}/identity-provider-configs/associate",
{
"oidc": {
"identityProviderConfigName": "tag-idp",
"issuerUrl": "https://example/issuer",
"clientId": "client-1",
},
},
)
assert status == 200
status, _headers, body = _eks_direct(
eks_mod,
"POST",
f"/clusters/{cluster}/identity-provider-configs/describe",
{"identityProviderConfig": {"type": "oidc", "name": "tag-idp"}},
)
assert status == 200
idp_arn = body["identityProviderConfig"]["oidc"]["identityProviderConfigArn"]
for arn in (cluster_arn, nodegroup_arn, addon_arn, access_entry_arn, idp_arn):
path_arn = quote(arn, safe="") if arn == cluster_arn else arn
status, _headers, body = _eks_direct(
eks_mod,
"POST",
f"/tags/{path_arn}",
{"tags": {"scope": "local"}},
)
assert status == 200
assert body == {}
status, _headers, body = _eks_direct(eks_mod, "GET", f"/tags/{path_arn}")
assert status == 200
assert body["tags"]["scope"] == "local"
assert eks_mod._tags.get(arn) == {"scope": "local"}
def test_eks_tag_apis_reject_invalid_resource_arns_before_tags_direct(eks_mod):
cluster = f"tag-invalid-{_uid()}"
cluster_arn = _eks_direct_create_cluster(eks_mod, cluster)
_eks_direct(eks_mod, "POST", f"/tags/{cluster_arn}", {"tags": {"existing": "tag"}})
existing_tags = dict(eks_mod._tags.items())
invalid_arns = [
"not-an-arn",
cluster_arn.replace("arn:aws:", "arn:aws-cn:"),
cluster_arn.replace(":eks:", ":sqs:"),
cluster_arn.replace(":000000000000:", ":111111111111:"),
cluster_arn.replace(f":{REGION}:", ":us-west-2:"),
f"{cluster_arn}/extra",
f"arn:aws:eks:{REGION}:000000000000:fargateprofile/{cluster}/fp/abc123",
]
for arn in invalid_arns:
for method, request_body, query in (
("GET", None, None),
("POST", {"tags": {"bad": "tag"}}, None),
("DELETE", None, {"tagKeys": "existing"}),
):
status, _headers, body = _eks_direct(
eks_mod,
method,
f"/tags/{arn}",
request_body,
query,
)
assert status == 400
assert body["__type"] == "InvalidParameterException"
assert dict(eks_mod._tags.items()) == existing_tags
def test_eks_tag_apis_reject_missing_local_resources_before_tags_direct(eks_mod):
cluster = f"tag-missing-{_uid()}"
cluster_arn = _eks_direct_create_cluster(eks_mod, cluster)
_eks_direct(eks_mod, "POST", f"/tags/{cluster_arn}", {"tags": {"existing": "tag"}})
existing_tags = dict(eks_mod._tags.items())
missing_arn = f"arn:aws:eks:{REGION}:000000000000:cluster/no-such-cluster"
for method, request_body, query in (
("GET", None, None),
("POST", {"tags": {"bad": "tag"}}, None),
("DELETE", None, {"tagKeys": "existing"}),
):
status, _headers, body = _eks_direct(
eks_mod,
method,
f"/tags/{missing_arn}",
request_body,
query,
)
assert status == 404
assert body["__type"] == "ResourceNotFoundException"
assert dict(eks_mod._tags.items()) == existing_tags
# ---------------------------------------------------------------------------
# CloudFormation
# ---------------------------------------------------------------------------
def test_eks_cfn_cluster(cfn, eks):
uid = _uid()
cluster_name = f"cfn-eks-{uid}"
template = json.dumps({
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
"Cluster": {
"Type": "AWS::EKS::Cluster",
"Properties": {
"Name": cluster_name,
"Version": "1.30",
"RoleArn": "arn:aws:iam::000000000000:role/eks-role",
"ResourcesVpcConfig": {
"subnetIds": ["subnet-1", "subnet-2"],
},
},
},
},
})
stack_name = f"eks-stack-{uid}"
cfn.create_stack(StackName=stack_name, TemplateBody=template)
# Poll for stack — deploy runs as an async task
stack = None
for _ in range(30):
try:
stack = cfn.describe_stacks(StackName=stack_name)["Stacks"][0]
if stack["StackStatus"] not in ("CREATE_IN_PROGRESS",):
break
except Exception:
pass
time.sleep(1)
assert stack is not None, f"Stack {stack_name} never appeared"
assert stack["StackStatus"] == "CREATE_COMPLETE"
resp = eks.describe_cluster(name=cluster_name)
assert resp["cluster"]["name"] == cluster_name
cfn.delete_stack(StackName=stack_name)
time.sleep(2)
# -- k3s container run kwargs ----------------------------------------------
#
# Issue #611: k3s requires `--privileged` to remount /sys/fs/cgroup; without
# it the container exits on boot with "failed to evacuate root cgroup". The
# kwargs builder is unit-tested in isolation so this doesn't depend on Docker
# being available in CI.
def test_eks_k3s_run_kwargs_includes_privileged():
"""Regression for #611: k3s server mode needs privileged=True."""
from ministack.services.eks import _k3s_run_kwargs
kwargs = _k3s_run_kwargs(name="test-cluster", region=REGION, port=16443)
assert kwargs["privileged"] is True, (
"k3s requires privileged=True — without it the cgroup remount fails "
"with 'failed to evacuate root cgroup' (issue #611)"
)
def test_eks_k3s_run_kwargs_port_mapping():
"""The 6443 port mapping must be present (the issue report flagged this
as missing — it wasn't, but lock it in so it stays present)."""
from ministack.services.eks import _k3s_run_kwargs
kwargs = _k3s_run_kwargs(name="test-cluster", region=REGION, port=16443)
assert kwargs["ports"] == {"6443/tcp": 16443}
def test_eks_k3s_run_kwargs_network_optional():
"""`network` is set only when ms_network is provided."""
from ministack.services.eks import _k3s_run_kwargs
no_net = _k3s_run_kwargs(name="c1", region=REGION, port=16443)
assert "network" not in no_net
with_net = _k3s_run_kwargs(
name="c1", region=REGION, port=16443, ms_network="ministack-net"
)
assert with_net["network"] == "ministack-net"
def test_eks_k3s_run_kwargs_container_name_and_labels_are_region_scoped():
"""Same-name clusters in different regions need distinct containers."""
from ministack.services.eks import _k3s_run_kwargs
east = _k3s_run_kwargs(name="my-cluster", region="us-east-1", port=16443)
west = _k3s_run_kwargs(name="my-cluster", region="us-west-2", port=16444)
assert east["name"] == "ministack-eks-us-east-1-my-cluster"
assert west["name"] == "ministack-eks-us-west-2-my-cluster"
# Subset, not equality: containers also carry the ownership labels
# (`ministack.instance` / `ministack.boot`) that scope reaping to this
# MiniStack. This test is about region scoping, so it asserts only that.
assert {
"ministack": "eks",
"cluster_name": "my-cluster",
"region": "us-east-1",
}.items() <= east["labels"].items()
assert west["labels"]["region"] == "us-west-2"
def test_eks_k3s_run_kwargs_host_gateway_extra_host():
"""The k3s node must be able to reach a host-run MiniStack for ECR
registry mirroring (#1054) — host.docker.internal via host-gateway."""
from ministack.services.eks import _k3s_run_kwargs
kwargs = _k3s_run_kwargs(name="c1", region=REGION, port=16443)
assert kwargs["extra_hosts"] == {"host.docker.internal": "host-gateway"}
def test_eks_ecr_registry_hosts_from_cluster_arn():
"""ECR mirror hostnames derive from the cluster ARN, not contextvars,
so restore/restart paths (no request context) behave like create (#1054)."""
from ministack.services.eks import _ecr_registry_hosts
cluster = {"arn": "arn:aws:eks:eu-west-1:123456789012:cluster/my-cluster"}
assert _ecr_registry_hosts(cluster) == ["123456789012.dkr.ecr.eu-west-1.amazonaws.com"]
assert _ecr_registry_hosts({"arn": "not-an-arn"}) == []
assert _ecr_registry_hosts({}) == []
def test_eks_k3s_registries_yaml_shape(monkeypatch):
"""registries.yaml maps the cluster's ECR hostname to the gateway; with
no shared network the endpoint goes through host.docker.internal (#1054)."""
from ministack.services.eks import _k3s_registries_yaml
monkeypatch.delenv("GATEWAY_PORT", raising=False)
monkeypatch.delenv("EDGE_PORT", raising=False)
yaml_bytes = _k3s_registries_yaml(
None, None, ["123456789012.dkr.ecr.eu-west-1.amazonaws.com"])
text = yaml_bytes.decode()
assert text == (
"mirrors:\n"
' "123456789012.dkr.ecr.eu-west-1.amazonaws.com":\n'
" endpoint:\n"
' - "http://host.docker.internal:4566"\n'
)
assert _k3s_registries_yaml(None, None, []) is None
def test_eks_addon_lifecycle(eks):
"""CreateAddon / DescribeAddon / ListAddons / UpdateAddon / DeleteAddon.
Issue #752: terraform aws_eks_addon fails on missing POST /clusters/{name}/addons."""
import uuid as _uuid
cn = f"addons-{_uuid.uuid4().hex[:8]}"
eks.create_cluster(
name=cn, roleArn="arn:aws:iam::000000000000:role/eks",
resourcesVpcConfig={"subnetIds": ["subnet-1", "subnet-2"]},
)
try:
# Create the 4 standard addons in one go.
for name in ("vpc-cni", "coredns", "kube-proxy", "aws-ebs-csi-driver"):
r = eks.create_addon(clusterName=cn, addonName=name)
assert r["addon"]["addonName"] == name
assert r["addon"]["status"] == "ACTIVE"
assert f":addon/{cn}/{name}/" in r["addon"]["addonArn"]
# Describe one.
r = eks.describe_addon(clusterName=cn, addonName="coredns")
assert r["addon"]["status"] == "ACTIVE"
assert r["addon"]["addonName"] == "coredns"
# List all.
lst = eks.list_addons(clusterName=cn)["addons"]
assert set(lst) == {"vpc-cni", "coredns", "kube-proxy", "aws-ebs-csi-driver"}
# Update changes the version and surfaces a successful update record.
upd = eks.update_addon(
clusterName=cn, addonName="coredns",
addonVersion="v1.11.4-eksbuild.1",
)
assert upd["update"]["status"] == "Successful"
r = eks.describe_addon(clusterName=cn, addonName="coredns")
assert r["addon"]["addonVersion"] == "v1.11.4-eksbuild.1"
# Delete returns DELETING and the addon is gone afterwards.
d = eks.delete_addon(clusterName=cn, addonName="vpc-cni")
assert d["addon"]["status"] == "DELETING"
with pytest.raises(ClientError) as e:
eks.describe_addon(clusterName=cn, addonName="vpc-cni")
assert e.value.response["Error"]["Code"] == "ResourceNotFoundException"
finally:
try:
eks.delete_cluster(name=cn)
except Exception:
pass
def test_eks_addon_create_on_missing_cluster_404(eks):
import uuid as _uuid
missing = f"no-such-cluster-{_uuid.uuid4().hex[:6]}"
with pytest.raises(ClientError) as e:
eks.create_addon(clusterName=missing, addonName="vpc-cni")
assert e.value.response["Error"]["Code"] == "ResourceNotFoundException"
def test_eks_addon_create_duplicate_returns_resource_in_use(eks):
import uuid as _uuid
cn = f"addons-dup-{_uuid.uuid4().hex[:8]}"
eks.create_cluster(
name=cn, roleArn="arn:aws:iam::000000000000:role/eks",
resourcesVpcConfig={"subnetIds": ["subnet-1"]},
)
try:
eks.create_addon(clusterName=cn, addonName="vpc-cni")
with pytest.raises(ClientError) as e:
eks.create_addon(clusterName=cn, addonName="vpc-cni")
assert e.value.response["Error"]["Code"] == "ResourceInUseException"
finally:
try:
eks.delete_cluster(name=cn)
except Exception:
pass
# ---------------------------------------------------------------------------
# AssociateEncryptionConfig
# ---------------------------------------------------------------------------
def test_eks_associate_encryption_config(eks):
cn = f"enc-{_uid()}"
key_arn = f"arn:aws:kms:{REGION}:000000000000:key/{uuid.uuid4()}"
eks.create_cluster(
name=cn, roleArn="arn:aws:iam::000000000000:role/eks",
resourcesVpcConfig={"subnetIds": ["subnet-1"]},
)
try:
resp = eks.associate_encryption_config(
clusterName=cn,
encryptionConfig=[{"resources": ["secrets"], "provider": {"keyArn": key_arn}}],
)
upd = resp["update"]
assert upd["type"] == "AssociateEncryptionConfig"
assert upd["status"] == "Successful"
assert upd["id"]
desc = eks.describe_cluster(name=cn)["cluster"]
assert desc["encryptionConfig"][0]["provider"]["keyArn"] == key_arn
finally:
try:
eks.delete_cluster(name=cn)
except Exception:
pass
def test_eks_associate_encryption_config_missing_cluster(eks):
with pytest.raises(ClientError) as e:
eks.associate_encryption_config(
clusterName=f"nope-{_uid()}",
encryptionConfig=[{"resources": ["secrets"],
"provider": {"keyArn": "arn:aws:kms:us-east-1:000000000000:key/x"}}],
)
assert e.value.response["Error"]["Code"] == "ResourceNotFoundException"
def test_eks_associate_encryption_config_already_set(eks):
cn = f"enc-dup-{_uid()}"
cfg = [{"resources": ["secrets"],
"provider": {"keyArn": f"arn:aws:kms:{REGION}:000000000000:key/{uuid.uuid4()}"}}]
eks.create_cluster(
name=cn, roleArn="arn:aws:iam::000000000000:role/eks",
resourcesVpcConfig={"subnetIds": ["subnet-1"]},
encryptionConfig=cfg,
)
try:
with pytest.raises(ClientError) as e:
eks.associate_encryption_config(clusterName=cn, encryptionConfig=cfg)
assert e.value.response["Error"]["Code"] == "InvalidRequestException"
finally:
try:
eks.delete_cluster(name=cn)
except Exception:
pass
# ---------------------------------------------------------------------------
# OIDC discovery / JWKS (IRSA)
# ---------------------------------------------------------------------------
def test_eks_oidc_issuer_is_ministack_hosted(eks):
cn = f"oidc-{_uid()}"
eks.create_cluster(
name=cn, roleArn="arn:aws:iam::000000000000:role/eks",
resourcesVpcConfig={"subnetIds": ["subnet-1"]},
)
try:
issuer = eks.describe_cluster(name=cn)["cluster"]["identity"]["oidc"]["issuer"]
# Must be reachable from clients — points at ministack, not real AWS.
assert issuer.startswith("http://"), issuer
assert "/oidc/id/" in issuer, issuer
assert "amazonaws.com" not in issuer, issuer
finally:
try:
eks.delete_cluster(name=cn)
except Exception:
pass
def test_eks_oidc_discovery_document(eks):
import urllib.request
cn = f"oidc-disc-{_uid()}"
eks.create_cluster(
name=cn, roleArn="arn:aws:iam::000000000000:role/eks",
resourcesVpcConfig={"subnetIds": ["subnet-1"]},
)
try:
issuer = eks.describe_cluster(name=cn)["cluster"]["identity"]["oidc"]["issuer"]
with urllib.request.urlopen(f"{issuer}/.well-known/openid-configuration") as r:
doc = json.loads(r.read())
assert doc["issuer"] == issuer
assert doc["jwks_uri"] == f"{issuer}/keys"
assert "RS256" in doc["id_token_signing_alg_values_supported"]
# JWKS must also be reachable and contain at least one RSA signing key.
with urllib.request.urlopen(doc["jwks_uri"]) as r:
jwks = json.loads(r.read())
assert jwks["keys"]
assert jwks["keys"][0]["kty"] == "RSA"
assert jwks["keys"][0]["use"] == "sig"
finally:
try:
eks.delete_cluster(name=cn)
except Exception:
pass
def test_eks_oidc_issuer_scheme_https_when_tls(monkeypatch):
"""With USE_SSL=1 the gateway serves TLS, so the advertised OIDC issuer and
the discovery document both report https (terraform's
aws_iam_openid_connect_provider rejects non-https urls). Called in-process."""
from ministack.services import eks as eks_svc
monkeypatch.setenv("USE_SSL", "1")
oidc_id = eks_svc._new_oidc_id()
issuer = eks_svc._issuer_url(oidc_id)
assert issuer.startswith("https://"), issuer
assert "/oidc/id/" in issuer, issuer
status, _headers, body = eks_svc._oidc_discovery(oidc_id)
assert status == 200
doc = json.loads(body)
assert doc["issuer"] == issuer
assert doc["jwks_uri"] == f"{issuer}/keys"
def test_eks_oidc_issuer_scheme_http_without_tls(monkeypatch):
"""Default (no TLS) keeps http, matching what the plain-http gateway serves."""
from ministack.services import eks as eks_svc
monkeypatch.delenv("USE_SSL", raising=False)
assert eks_svc._ministack_issuer_base().startswith("http://")
# ---------------------------------------------------------------------------
# Access Entries — modern EKS IAM bindings (replace aws-auth ConfigMap).
# Crossplane / Terraform `aws_eks_access_entry` + `aws_eks_access_policy_association`
# both flow through these APIs.
# ---------------------------------------------------------------------------
def _create_basic_cluster(eks):
cn = f"ae-{_uid()}"
eks.create_cluster(
name=cn, roleArn="arn:aws:iam::000000000000:role/eks",
resourcesVpcConfig={"subnetIds": ["subnet-1"]},
)
return cn
def test_eks_pod_identity_association_lifecycle(eks):
"""EKS Pod Identity: the five operations a controller reading pod identity
needs. Create returns the full association, List the six-field summary,
Describe the record, Update the mutable members, and Delete answers with
the association it removed."""
cn = _create_basic_cluster(eks)
role = f"arn:aws:iam::000000000000:role/lbc-{_uid()}"
try:
created = eks.create_pod_identity_association(
clusterName=cn, namespace="kube-system",
serviceAccount="aws-load-balancer-controller",
roleArn=role, tags={"team": "platform"},
)["association"]
assoc_id = created["associationId"]
assert created["clusterName"] == cn
assert created["namespace"] == "kube-system"
assert created["serviceAccount"] == "aws-load-balancer-controller"
assert created["roleArn"] == role
assert created["tags"] == {"team": "platform"}
assert created["associationArn"] == (
f"arn:aws:eks:{REGION}:000000000000:podidentityassociation/{cn}/{assoc_id}")
assert created["createdAt"] == created["modifiedAt"]
described = eks.describe_pod_identity_association(
clusterName=cn, associationId=assoc_id)["association"]
assert described["roleArn"] == role
# The list shape is the summary, not the whole association.
listed = eks.list_pod_identity_associations(clusterName=cn)["associations"]
assert len(listed) == 1
assert set(listed[0]) == {
"clusterName", "namespace", "serviceAccount",
"associationArn", "associationId", "ownerArn",
}
updated = eks.update_pod_identity_association(
clusterName=cn, associationId=assoc_id, roleArn=role + "-v2")["association"]
assert updated["roleArn"] == role + "-v2"
# namespace and serviceAccount are not members of the update request.
assert updated["namespace"] == "kube-system"
assert updated["serviceAccount"] == "aws-load-balancer-controller"
deleted = eks.delete_pod_identity_association(
clusterName=cn, associationId=assoc_id)["association"]
assert deleted["associationId"] == assoc_id
assert eks.list_pod_identity_associations(clusterName=cn)["associations"] == []
with pytest.raises(ClientError) as e:
eks.describe_pod_identity_association(clusterName=cn, associationId=assoc_id)
assert e.value.response["Error"]["Code"] == "ResourceNotFoundException"
finally: