Skip to content

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

feat(eks): scope resources by region (#1199)

Ian Oberst7cf1af9b1c2d
diff --git a/README.md b/README.md
index 18e76655..5b352c00 100644
--- a/README.md
+++ b/README.md
@@ -160,7 +160,7 @@ Since 1.4.0 state is additionally isolated per **region** — see [Multi-Region]
| `111111111111` | `111111111111` |
| `048408301323` | `048408301323` |
| `test` | `000000000000` (default) |
-| `AKIAIOSFODNN7EXAMPLE` | `000000000000` (default) |
+| `AKIA_TEST_KEY_DO_NOT_USE` | `000000000000` (default) |
**Terraform** — set `access_key` in your provider block:
```hcl
@@ -958,9 +958,10 @@ aws --endpoint-url=http://localhost:4566 eks create-cluster \
--name my-cluster --role-arn arn:aws:iam::000000000000:role/eks \
--resources-vpc-config subnetIds=subnet-1
-# Get the k3s kubeconfig (container name follows ministack-eks-{name} pattern)
-docker exec ministack-eks-my-cluster cat /etc/rancher/k3s/k3s.yaml \
- | sed "s/127.0.0.1:6443/localhost:$(docker port ministack-eks-my-cluster 6443/tcp | cut -d: -f2)/" \
+# Get the k3s kubeconfig (container name follows
+# ministack-eks-{region}-{name}; this example uses eu-central-1)
+docker exec ministack-eks-eu-central-1-my-cluster cat /etc/rancher/k3s/k3s.yaml \
+ | sed "s/127.0.0.1:6443/localhost:$(docker port ministack-eks-eu-central-1-my-cluster 6443/tcp | cut -d: -f2)/" \
> /tmp/ministack-kubeconfig.yaml
# Use kubectl against real Kubernetes
diff --git a/ministack/core/persistence.py b/ministack/core/persistence.py
index ae557b04..0aa173ca 100644
--- a/ministack/core/persistence.py
+++ b/ministack/core/persistence.py
@@ -31,6 +31,7 @@ SERVICE_STATE_FORMAT_VERSIONS = {
"autoscaling": 3,
"athena": 3,
"emr": 3,
+ "eks": 3,
"inspector2": 3,
"efs": 3,
"s3files": 3,
diff --git a/ministack/services/eks.py b/ministack/services/eks.py
index 2b44e680..0de0a3fa 100644
--- a/ministack/services/eks.py
+++ b/ministack/services/eks.py
@@ -25,6 +25,7 @@ import urllib.parse
from ministack.core.arn import ArnParseError, parse_arn
from ministack.core.persistence import load_state
from ministack.core.responses import (
+ AccountRegionScopedDict,
AccountScopedDict,
apply_image_prefix,
error_response_json,
@@ -54,13 +55,13 @@ except ImportError:
# State
# ---------------------------------------------------------------------------
-_clusters = AccountScopedDict() # name -> cluster record
-_nodegroups = AccountScopedDict() # "cluster/nodegroup" -> nodegroup record
-_addons = AccountScopedDict() # "cluster/addonName" -> addon record
-_access_entries = AccountScopedDict() # "cluster\x00principalArn" -> access entry record
-_access_policies = AccountScopedDict()# "cluster\x00principalArn\x00policyArn" -> associated policy
+_clusters = AccountRegionScopedDict() # name -> cluster record
+_nodegroups = AccountRegionScopedDict() # "cluster/nodegroup" -> nodegroup record
+_addons = AccountRegionScopedDict() # "cluster/addonName" -> addon record
+_access_entries = AccountRegionScopedDict() # "cluster\x00principalArn" -> access entry record
+_access_policies = AccountRegionScopedDict()# "cluster\x00principalArn\x00policyArn" -> associated policy
_tags = AccountScopedDict() # arn -> {key: value}
-_idp_configs = AccountScopedDict() # "cluster\x00idp_name" -> idp record
+_idp_configs = AccountRegionScopedDict() # "cluster\x00idp_name" -> idp record
_port_counter_lock = threading.Lock()
_port_counter = [EKS_BASE_PORT]
_oidc_keypair_lock = threading.Lock()
@@ -138,7 +139,7 @@ def reset():
def get_state():
clusters = copy.deepcopy(_clusters)
# Strip Docker container IDs (not restorable across restarts)
- if isinstance(clusters, AccountScopedDict):
+ if isinstance(clusters, AccountRegionScopedDict):
for key in list(clusters._data):
clusters._data[key].pop("_docker_id", None)
else:
@@ -156,14 +157,55 @@ def get_state():
}
+def _restore_cluster_child_store(store, restored, cluster_regions, separator):
+ """Adopt legacy child records into their parent cluster's region.
+
+ Legacy account-scoped EKS state allowed a request in one region to create
+ a child for a cluster created in another. Preserve that reachable parent /
+ child relationship instead of splitting the records by their individual
+ ARNs. Orphans retain the generic ARN-derived (or boot-region) fallback.
+ """
+ if isinstance(restored, AccountRegionScopedDict):
+ store.update(restored)
+ return
+
+ if not restored:
+ return
+
+ if isinstance(restored, AccountScopedDict):
+ items = restored._data.items()
+ else:
+ account_id = get_account_id()
+ items = (((account_id, key), value) for key, value in restored.items())
+
+ for (account_id, key), value in items:
+ cluster_name = key.split(separator, 1)[0] if isinstance(key, str) else None
+ region = cluster_regions.get((account_id, cluster_name))
+ if region is None:
+ region = store._region_for_legacy_value(key, value)
+ store.set_scoped(account_id, region, key, value)
+
+
def restore_state(data):
_clusters.update(data.get("clusters", {}))
- _nodegroups.update(data.get("nodegroups", {}))
- _addons.update(data.get("addons", {}))
- _access_entries.update(data.get("access_entries", {}))
- _access_policies.update(data.get("access_policies", {}))
+ cluster_regions = {
+ (account_id, cluster_name): region
+ for (account_id, region, cluster_name), _cluster in _clusters.all_items()
+ }
+ for store, state_key, separator in (
+ (_nodegroups, "nodegroups", "/"),
+ (_addons, "addons", "/"),
+ (_access_entries, "access_entries", "\x00"),
+ (_access_policies, "access_policies", "\x00"),
+ (_idp_configs, "idp_configs", "\x00"),
+ ):
+ _restore_cluster_child_store(
+ store,
+ data.get(state_key, {}),
+ cluster_regions,
+ separator,
+ )
_tags.update(data.get("tags", {}))
- _idp_configs.update(data.get("idp_configs", {}))
if "port_counter" in data:
_port_counter[0] = data["port_counter"]
# Restored clusters have no running k3s container. Drop the stale docker id and
@@ -176,7 +218,11 @@ def restore_state(data):
# to_dict() yields every account's live record dict so the rewrite is applied
# across all tenants — the account-scoped views (values()/items()) would see
# only the default account because no request scope is set at import time.
- clusters = _clusters.to_dict().values() if isinstance(_clusters, AccountScopedDict) else _clusters.values()
+ clusters = (
+ _clusters.to_dict().values()
+ if isinstance(_clusters, AccountRegionScopedDict)
+ else _clusters.values()
+ )
for c in clusters:
c["_docker_id"] = None
port = c.get("_port")
@@ -325,7 +371,14 @@ def _collect_node_labels(cluster: dict) -> list[str]:
return [f"--node-label={k}={v}" for k, v in labels.items()]
-def _k3s_run_kwargs(name: str, port: int, ms_network: str | None = None, oidc_args: list[str] | None = None, node_labels: list[str] | None = None) -> dict:
+def _k3s_run_kwargs(
+ name: str,
+ region: str,
+ port: int,
+ ms_network: str | None = None,
+ oidc_args: list[str] | None = None,
+ node_labels: list[str] | None = None,
+) -> dict:
"""Build the docker run kwargs for a k3s server container.
`privileged=True` is required: k3s server mode remounts `/sys/fs/cgroup`,
@@ -362,8 +415,8 @@ def _k3s_run_kwargs(name: str, port: int, ms_network: str | None = None, oidc_ar
security_opt=["seccomp=unconfined", "apparmor=unconfined"],
devices=["/dev/fuse"],
ports={"6443/tcp": port},
- name=f"ministack-eks-{name}",
- labels={"ministack": "eks", "cluster_name": name},
+ name=f"ministack-eks-{region}-{name}",
+ labels={"ministack": "eks", "cluster_name": name, "region": region},
environment={"K3S_KUBECONFIG_MODE": "644"},
volumes={"/lib/modules": {"bind": "/lib/modules", "mode": "ro"}},
tmpfs={"/run": "", "/var/run": "", "/tmp": ""},
@@ -555,6 +608,7 @@ def _create_cluster(body):
if cluster["tags"]:
_tags[arn] = dict(cluster["tags"])
+ region = get_region()
oidc_args, _idp_cfg_refs = _collect_oidc_state(name)
node_labels = _collect_node_labels(cluster)
@@ -567,7 +621,14 @@ def _create_cluster(body):
ms_network = None
try:
ms_network = _get_ministack_network(client)
- run_kwargs = _k3s_run_kwargs(name=name, port=port, ms_network=ms_network, oidc_args=oidc_args, node_labels=node_labels)
+ run_kwargs = _k3s_run_kwargs(
+ name=name,
+ region=region,
+ port=port,
+ ms_network=ms_network,
+ oidc_args=oidc_args,
+ node_labels=node_labels,
+ )
registries_yaml = _k3s_registries_yaml(client, ms_network, _ecr_registry_hosts(cluster))
container = _start_k3s_container(client, run_kwargs, registries_yaml)
@@ -1022,9 +1083,9 @@ def _restart_k3s(cluster_name, oidc_args=None, idp_cfg_refs=None):
"""Restart the cluster's k3s container with the supplied OIDC args.
Both ``oidc_args`` and ``idp_cfg_refs`` must be captured by the CALLER
- inside the request context (where AccountScopedDict can resolve the
- account). The background thread closes over them so it never needs the
- request's contextvars.
+ inside the request context (where AccountRegionScopedDict can resolve the
+ account and region). The background thread closes over them so it never
+ needs the request's contextvars.
"""
cluster = _clusters.get(cluster_name)
if not cluster:
@@ -1038,6 +1099,7 @@ def _restart_k3s(cluster_name, oidc_args=None, idp_cfg_refs=None):
# only.
oidc_args = oidc_args or []
idp_cfg_refs = idp_cfg_refs or []
+ region = get_region()
node_labels = _collect_node_labels(cluster)
def _mark_idp_active():
@@ -1058,7 +1120,14 @@ def _restart_k3s(cluster_name, oidc_args=None, idp_cfg_refs=None):
cluster["_docker_id"] = None
ms_network = _get_ministack_network(client)
- run_kwargs = _k3s_run_kwargs(name=cluster_name, port=cluster["_port"], ms_network=ms_network, oidc_args=oidc_args, node_labels=node_labels)
+ run_kwargs = _k3s_run_kwargs(
+ name=cluster_name,
+ region=region,
+ port=cluster["_port"],
+ ms_network=ms_network,
+ oidc_args=oidc_args,
+ node_labels=node_labels,
+ )
registries_yaml = _k3s_registries_yaml(client, ms_network, _ecr_registry_hosts(cluster))
container = _start_k3s_container(client, run_kwargs, registries_yaml)
@@ -1257,15 +1326,19 @@ def _resolve_tag_resource_arn(arn):
spec.partition != "aws"
or spec.service != "eks"
or spec.account_id != get_account_id()
- or spec.region != get_region()
):
return None, _invalid_tag_resource_arn(arn)
+ request_region = get_region()
parts = spec.resource.split("/")
resource_type = parts[0] if parts else ""
+ # Legacy account-scoped state could create a child in a different region
+ # from its parent. Restore co-locates those children with the parent while
+ # preserving their ARN (and the ARN-keyed persisted tags). Accept that
+ # exact ARN only when the child exists in the current scoped store.
if resource_type == "cluster":
- if len(parts) != 2 or not parts[1]:
+ if len(parts) != 2 or not parts[1] or spec.region != request_region:
return None, _invalid_tag_resource_arn(arn)
cluster = _clusters.get(parts[1])
if not cluster or cluster.get("arn") != arn:
@@ -1277,6 +1350,8 @@ def _resolve_tag_resource_arn(arn):
return None, _invalid_tag_resource_arn(arn)
nodegroup = _nodegroups.get(f"{parts[1]}/{parts[2]}")
if not nodegroup or nodegroup.get("nodegroupArn") != arn:
+ if spec.region != request_region:
+ return None, _invalid_tag_resource_arn(arn)
return None, _tag_resource_not_found(arn)
return nodegroup["nodegroupArn"], None
@@ -1285,6 +1360,8 @@ def _resolve_tag_resource_arn(arn):
return None, _invalid_tag_resource_arn(arn)
addon = _addons.get(f"{parts[1]}/{parts[2]}")
if not addon or addon.get("addonArn") != arn:
+ if spec.region != request_region:
+ return None, _invalid_tag_resource_arn(arn)
return None, _tag_resource_not_found(arn)
return addon["addonArn"], None
@@ -1294,6 +1371,8 @@ def _resolve_tag_resource_arn(arn):
for entry in _access_entries.values():
if entry.get("clusterName") == parts[1] and entry.get("accessEntryArn") == arn:
return entry["accessEntryArn"], None
+ if spec.region != request_region:
+ return None, _invalid_tag_resource_arn(arn)
return None, _tag_resource_not_found(arn)
if resource_type == "identityproviderconfig":
@@ -1301,6 +1380,8 @@ def _resolve_tag_resource_arn(arn):
return None, _invalid_tag_resource_arn(arn)
cfg = _idp_configs.get(f"{parts[1]}\x00{parts[3]}")
if not cfg or cfg.get("arn") != arn:
+ if spec.region != request_region:
+ return None, _invalid_tag_resource_arn(arn)
return None, _tag_resource_not_found(arn)
return cfg["arn"], None
diff --git a/tests/test_eks.py b/tests/test_eks.py
index 4a7e8b56..b484062e 100644
--- a/tests/test_eks.py
+++ b/tests/test_eks.py
@@ -145,6 +145,171 @@ def test_eks_list_clusters(eks):
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")
@@ -440,7 +605,7 @@ 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", port=16443)
+ 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 "
@@ -453,7 +618,7 @@ def test_eks_k3s_run_kwargs_port_mapping():
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", port=16443)
+ kwargs = _k3s_run_kwargs(name="test-cluster", region=REGION, port=16443)
assert kwargs["ports"] == {"6443/tcp": 16443}
@@ -461,21 +626,30 @@ 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", port=16443)
+ no_net = _k3s_run_kwargs(name="c1", region=REGION, port=16443)
assert "network" not in no_net
- with_net = _k3s_run_kwargs(name="c1", port=16443, ms_network="ministack-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():
- """Each cluster's k3s container is named and labelled so `_stop_all_k3s`
- can find it. Lock the shape used by that lookup."""
+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
- kwargs = _k3s_run_kwargs(name="my-cluster", port=16443)
- assert kwargs["name"] == "ministack-eks-my-cluster"
- assert kwargs["labels"] == {"ministack": "eks", "cluster_name": "my-cluster"}
+ 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"
+ assert east["labels"] == {
+ "ministack": "eks",
+ "cluster_name": "my-cluster",
+ "region": "us-east-1",
+ }
+ assert west["labels"]["region"] == "us-west-2"
def test_eks_k3s_run_kwargs_host_gateway_extra_host():
@@ -483,7 +657,7 @@ def test_eks_k3s_run_kwargs_host_gateway_extra_host():
registry mirroring (#1054) — host.docker.internal via host-gateway."""
from ministack.services.eks import _k3s_run_kwargs
- kwargs = _k3s_run_kwargs(name="c1", port=16443)
+ kwargs = _k3s_run_kwargs(name="c1", region=REGION, port=16443)
assert kwargs["extra_hosts"] == {"host.docker.internal": "host-gateway"}
@@ -1108,6 +1282,7 @@ def test_eks_k3s_run_kwargs_appends_node_labels():
run_kwargs = _k3s_run_kwargs(
name="t",
+ region=REGION,
port=16443,
node_labels=["--node-label=topology.kubernetes.io/zone=us-east-1a"],
)
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
index b6aa1538..0d6073a1 100644
--- a/tests/test_persistence.py
+++ b/tests/test_persistence.py
@@ -500,6 +500,297 @@ def test_eks_round_trip():
_round_trip("eks", "eks", populate, observe)
+def test_eks_access_policies_round_trip_outside_boot_region():
+ from ministack.core.responses import (
+ get_account_id,
+ get_region,
+ set_request_account_id,
+ set_request_region,
+ )
+
+ original_account = get_account_id()
+ original_region = get_region()
+ account_id = "000000000000"
+ boot_region = "us-east-1"
+ resource_region = "us-west-2"
+ cluster_name = "regional-cluster"
+ principal_arn = f"arn:aws:iam::{account_id}:role/regional-role"
+ entry_key = f"{cluster_name}\x00{principal_arn}"
+ policy_arn = (
+ "arn:aws:eks::aws:cluster-access-policy/AmazonEKSViewPolicy"
+ )
+ policy_key = f"{entry_key}\x00{policy_arn}"
+ mod = _module("eks")
+
+ def populate(mod):
+ mod._access_entries.set_scoped(
+ account_id,
+ resource_region,
+ entry_key,
+ {
+ "clusterName": cluster_name,
+ "principalArn": principal_arn,
+ "accessEntryArn": (
+ f"arn:aws:eks:{resource_region}:{account_id}:"
+ f"access-entry/{cluster_name}/role/{account_id}/"
+ "regional-role/id"
+ ),
+ },
+ )
+ mod._access_policies.set_scoped(
+ account_id,
+ resource_region,
+ policy_key,
+ {
+ "policyArn": policy_arn,
+ "accessScope": {"type": "cluster", "namespaces": []},
+ },
+ )
+ # Restore below runs in the boot scope, where this west-only store is
+ # false even though it contains persisted data in another region.
+ set_request_region(boot_region)
+
+ def observe(mod):
+ assert mod._access_policies.contains_scoped(
+ account_id, resource_region, policy_key
+ )
+ assert not mod._access_policies.contains_scoped(
+ account_id, boot_region, policy_key
+ )
+
+ try:
+ set_request_account_id(account_id)
+ set_request_region(resource_region)
+ _round_trip("eks", "eks", populate, observe)
+ finally:
+ mod.reset()
+ set_request_account_id(original_account)
+ set_request_region(original_region)
+
+
+def test_eks_legacy_state_uses_arn_and_parent_regions():
+ import json as _json
+
+ from ministack.core.responses import (
+ AccountScopedDict,
+ get_account_id,
+ get_region,
+ set_request_account_id,
+ set_request_region,
+ )
+ from ministack.services import eks as mod
+
+ original_account = get_account_id()
+ original_region = get_region()
+ account_id = "000000000000"
+ boot_region = "us-east-1"
+ parent_region = "us-west-2"
+ child_arn_region = "eu-west-1"
+ cluster_name = "legacy-cluster"
+ principal_arn = f"arn:aws:iam::{account_id}:role/legacy-role"
+ entry_key = f"{cluster_name}\x00{principal_arn}"
+ policy_arn = (
+ "arn:aws:eks::aws:cluster-access-policy/AmazonEKSViewPolicy"
+ )
+ policy_key = f"{entry_key}\x00{policy_arn}"
+ orphan_key = f"orphan-cluster\x00{principal_arn}\x00{policy_arn}"
+
+ legacy_clusters = AccountScopedDict()
+ legacy_clusters._data[(account_id, cluster_name)] = {
+ "name": cluster_name,
+ "arn": (
+ f"arn:aws:eks:{parent_region}:{account_id}:"
+ f"cluster/{cluster_name}"
+ ),
+ "status": "ACTIVE",
+ "_port": 16443,
+ "_docker_id": "stale-container",
+ }
+ legacy_entries = AccountScopedDict()
+ legacy_entries._data[(account_id, entry_key)] = {
+ "clusterName": cluster_name,
+ "principalArn": principal_arn,
+ "accessEntryArn": (
+ f"arn:aws:eks:{child_arn_region}:{account_id}:"
+ f"access-entry/{cluster_name}/legacy-entry-id"
+ ),
+ }
+ nodegroup_key = f"{cluster_name}/legacy-workers"
+ legacy_nodegroups = AccountScopedDict()
+ legacy_nodegroups._data[(account_id, nodegroup_key)] = {
+ "clusterName": cluster_name,
+ "nodegroupName": "legacy-workers",
+ "nodegroupArn": (
+ f"arn:aws:eks:{child_arn_region}:{account_id}:"
+ f"nodegroup/{cluster_name}/legacy-workers/id"
+ ),
+ }
+ addon_key = f"{cluster_name}/vpc-cni"
+ legacy_addons = AccountScopedDict()
+ legacy_addons._data[(account_id, addon_key)] = {
+ "clusterName": cluster_name,
+ "addonName": "vpc-cni",
+ "addonArn": (
+ f"arn:aws:eks:{child_arn_region}:{account_id}:"
+ f"addon/{cluster_name}/vpc-cni/id"
+ ),
+ }
+ legacy_policies = AccountScopedDict()
+ legacy_policies._data[(account_id, policy_key)] = {
+ "policyArn": policy_arn,
+ "accessScope": {"type": "cluster", "namespaces": []},
+ }
+ legacy_policies._data[(account_id, orphan_key)] = {
+ "policyArn": policy_arn,
+ "accessScope": {"type": "cluster", "namespaces": []},
+ }
+ idp_key = f"{cluster_name}\x00legacy-idp"
+ legacy_idp_configs = AccountScopedDict()
+ legacy_idp_configs._data[(account_id, idp_key)] = {
+ "clusterName": cluster_name,
+ "name": "legacy-idp",
+ "oidc": {
+ "clientId": "legacy-client",
+ "issuerUrl": "https://legacy.example.test",
+ },
+ "arn": (
+ f"arn:aws:eks:{child_arn_region}:{account_id}:"
+ f"identityproviderconfig/{cluster_name}/oidc/legacy-idp/id"
+ ),
+ }
+ child_arns = (
+ legacy_nodegroups._data[(account_id, nodegroup_key)]["nodegroupArn"],
+ legacy_addons._data[(account_id, addon_key)]["addonArn"],
+ legacy_entries._data[(account_id, entry_key)]["accessEntryArn"],
+ legacy_idp_configs._data[(account_id, idp_key)]["arn"],
+ )
+ legacy_tags = AccountScopedDict()
+ for child_arn in child_arns:
+ legacy_tags._data[(account_id, child_arn)] = {"legacy": "true"}
+
+ mod.reset()
+ try:
+ set_request_account_id(account_id)
+ set_request_region(boot_region)
+ mod.restore_state(
+ {
+ "clusters": legacy_clusters,
+ "nodegroups": legacy_nodegroups,
+ "addons": legacy_addons,
+ "access_entries": legacy_entries,
+ "access_policies": legacy_policies,
+ "idp_configs": legacy_idp_configs,
+ "tags": legacy_tags,
+ }
+ )
+
+ cluster = mod._clusters.get_scoped(
+ account_id, parent_region, cluster_name
+ )
+ assert cluster["_docker_id"] is None
+ assert cluster["endpoint"] == "https://localhost:16443"
+ assert mod._access_entries.contains_scoped(
+ account_id, parent_region, entry_key
+ )
+ assert mod._nodegroups.contains_scoped(
+ account_id, parent_region, nodegroup_key
+ )
+ assert mod._addons.contains_scoped(
+ account_id, parent_region, addon_key
+ )
+ assert mod._access_policies.contains_scoped(
+ account_id, parent_region, policy_key
+ )
+ assert not mod._access_policies.contains_scoped(
+ account_id, boot_region, policy_key
+ )
+ assert mod._access_policies.contains_scoped(
+ account_id, boot_region, orphan_key
+ )
+ assert mod._idp_configs.contains_scoped(
+ account_id, parent_region, idp_key
+ )
+ for store, key in (
+ (mod._nodegroups, nodegroup_key),
+ (mod._addons, addon_key),
+ (mod._access_entries, entry_key),
+ (mod._access_policies, policy_key),
+ (mod._idp_configs, idp_key),
+ ):
+ assert not store.contains_scoped(account_id, child_arn_region, key)
+
+ # The legacy child records remain reachable through their normal API
+ # paths in the restored parent region even though their persisted ARNs
+ # were minted by cross-region legacy requests.
+ set_request_region(parent_region)
+ status, _, body = mod._list_nodegroups(cluster_name, {})
+ assert status == 200
+ assert _json.loads(body)["nodegroups"] == ["legacy-workers"]
+ status, _, body = mod._describe_nodegroup(
+ cluster_name, "legacy-workers"
+ )
+ assert status == 200
+ assert _json.loads(body)["nodegroup"]["nodegroupName"] == "legacy-workers"
+
+ status, _, body = mod._list_addons(cluster_name, {})
+ assert status == 200
+ assert _json.loads(body)["addons"] == ["vpc-cni"]
+ status, _, body = mod._describe_addon(cluster_name, "vpc-cni")
+ assert status == 200
+ assert _json.loads(body)["addon"]["addonName"] == "vpc-cni"
+
+ status, _, body = mod._list_access_entries(cluster_name, {})
+ assert status == 200
+ assert _json.loads(body)["accessEntries"] == [principal_arn]
+ status, _, body = mod._list_associated_access_policies(
+ cluster_name, principal_arn, {}
+ )
+ assert status == 200
+ assert _json.loads(body)["associatedAccessPolicies"][0][
+ "policyArn"
+ ] == policy_arn
+
+ status, _, body = mod._describe_identity_provider_config(
+ cluster_name,
+ {
+ "identityProviderConfig": {
+ "type": "oidc",
+ "name": "legacy-idp",
+ }
+ },
+ )
+ assert status == 200
+ assert _json.loads(body)["identityProviderConfig"]["oidc"][
+ "identityProviderConfigName"
+ ] == "legacy-idp"
+
+ # Tag APIs accept the original child ARN in the region where migration
+ # co-located the child with its parent. Keep that persisted ARN as the
+ # tag-store key so legacy tags survive the round trip.
+ for child_arn in child_arns:
+ status, _, body = mod._list_tags(child_arn)
+ assert status == 200
+ assert _json.loads(body)["tags"] == {"legacy": "true"}
+
+ nodegroup_arn = child_arns[0]
+ status, _, _body = mod._tag_resource(
+ nodegroup_arn, {"tags": {"owner": "platform"}}
+ )
+ assert status == 200
+ status, _, _body = mod._untag_resource(
+ nodegroup_arn, {"tagKeys": ["legacy"]}
+ )
+ assert status == 200
+ status, _, body = mod._list_tags(nodegroup_arn)
+ assert status == 200
+ assert _json.loads(body)["tags"] == {"owner": "platform"}
+ assert mod._tags.get(nodegroup_arn) == {"owner": "platform"}
+ finally:
+ mod.reset()
+ set_request_account_id(original_account)
+ set_request_region(original_region)
+
+
def test_scheduler_round_trip():
# Production code keys _schedules by `f"{group}/{name}"` strings (see
# scheduler.py CreateSchedule etc.), not tuples — even though the
@@ -1868,6 +2159,41 @@ def test_appsync_region_scoped_state_is_rejected_by_v2_reader(
assert persistence.load_state("appsync") is None
+def test_eks_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmp_path):
+ """A rollback binary must reject EKS regional state instead of dropping it."""
+ import json as _json
+
+ from ministack.core.responses import AccountRegionScopedDict
+
+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)
+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))
+
+ clusters = AccountRegionScopedDict()
+ clusters.set_scoped(
+ "000000000000",
+ "us-west-2",
+ "regional-cluster",
+ {
+ "name": "regional-cluster",
+ "arn": (
+ "arn:aws:eks:us-west-2:000000000000:"
+ "cluster/regional-cluster"
+ ),
+ },
+ )
+ persistence.save_state("eks", {"clusters": clusters})
+
+ raw = _json.loads((tmp_path / "eks.json").read_text())
+ assert raw["__ministack_format__"] == 3
+ loaded_clusters = persistence.load_state("eks")["clusters"]
+ assert loaded_clusters.get_scoped(
+ "000000000000", "us-west-2", "regional-cluster"
+ )["arn"].endswith("cluster/regional-cluster")
+
+ monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})
+ assert persistence.load_state("eks") is None
+
+
def test_emr_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmp_path):
"""A rollback binary must reject EMR regional state instead of dropping it."""
import json as _json