Skip to content

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

Scope Resource Groups state by region (#1128)

Ian Oberst606c5f9db30c
diff --git a/ministack/core/persistence.py b/ministack/core/persistence.py
index 491ba986..b059e258 100644
--- a/ministack/core/persistence.py
+++ b/ministack/core/persistence.py
@@ -27,8 +27,9 @@ STATE_DIR = os.environ.get("STATE_DIR", "/tmp/ministack-state")
# still load and migrate. (U4)
STATE_FORMAT_VERSION = 2
SERVICE_STATE_FORMAT_VERSIONS = {
- "codebuild": 3,
"ecs": 3,
+ "resource_groups": 3,
+ "codebuild": 3,
}
diff --git a/ministack/services/resource_groups.py b/ministack/services/resource_groups.py
index 69db5a2f..905cfe1b 100644
--- a/ministack/services/resource_groups.py
+++ b/ministack/services/resource_groups.py
@@ -24,6 +24,7 @@ import re
from ministack.core.arn import ArnParseError, parse_arn
from ministack.core.persistence import load_state
from ministack.core.responses import (
+ AccountRegionScopedDict,
AccountScopedDict,
get_account_id,
get_region,
@@ -35,12 +36,12 @@ _GROUP_NAME_RE = re.compile(r"^[A-Za-z0-9_.\-]{1,300}$")
_AWS_PARTITION_RE = re.compile(r"^aws(?:-[a-z]+)*$")
_VALID_QUERY_TYPES = {"TAG_FILTERS_1_0", "CLOUDFORMATION_STACK_1_0"}
-_groups = AccountScopedDict() # name -> Group dict
-_group_queries = AccountScopedDict() # name -> ResourceQuery dict
-_group_configs = AccountScopedDict() # name -> [GroupConfigurationItem]
-_group_members = AccountScopedDict() # name -> [resource_arn]
-_group_tags = AccountScopedDict() # name -> {tag_key: tag_value}
-_account_settings = AccountScopedDict() # "settings" -> AccountSettings dict
+_groups = AccountRegionScopedDict() # name -> Group dict
+_group_queries = AccountRegionScopedDict() # name -> ResourceQuery dict
+_group_configs = AccountRegionScopedDict() # name -> [GroupConfigurationItem]
+_group_members = AccountRegionScopedDict() # name -> [resource_arn]
+_group_tags = AccountRegionScopedDict() # name -> {tag_key: tag_value}
+_account_settings = AccountRegionScopedDict() # "settings" -> AccountSettings dict
def get_state():
@@ -57,14 +58,39 @@ def get_state():
def restore_state(data):
if not data:
return
- _groups.update(data.get("groups", {}))
- _group_queries.update(data.get("group_queries", {}))
- _group_configs.update(data.get("group_configs", {}))
- _group_members.update(data.get("group_members", {}))
- _group_tags.update(data.get("group_tags", {}))
+ restored_groups = data.get("groups", {})
+ legacy_group_regions = {}
+ if isinstance(restored_groups, AccountScopedDict):
+ legacy_group_regions = {
+ (account_id, group_name): _groups._region_for_legacy_value(
+ group_name, group
+ )
+ for (account_id, group_name), group in restored_groups._data.items()
+ }
+ _groups.update(restored_groups)
+ for store, key in (
+ (_group_queries, "group_queries"),
+ (_group_configs, "group_configs"),
+ (_group_members, "group_members"),
+ (_group_tags, "group_tags"),
+ ):
+ _restore_group_child_store(
+ store, data.get(key, {}), legacy_group_regions
+ )
_account_settings.update(data.get("account_settings", {}))
+def _restore_group_child_store(store, restored, legacy_group_regions):
+ """Adopt legacy name-keyed child state into its parent group's region."""
+ if not isinstance(restored, AccountScopedDict):
+ store.update(restored)
+ return
+
+ for (account_id, group_name), value in restored._data.items():
+ region = legacy_group_regions.get((account_id, group_name), get_region())
+ store.set_scoped(account_id, region, group_name, value)
+
+
try:
_restored = load_state("resource_groups")
if _restored:
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
index ff02576c..38f1495c 100644
--- a/tests/test_persistence.py
+++ b/tests/test_persistence.py
@@ -1832,6 +1832,45 @@ def test_ecs_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmp_path)
assert persistence.load_state("ecs") is None
+def test_resource_groups_region_scoped_state_is_rejected_by_v2_reader(
+ monkeypatch, tmp_path
+):
+ """A rollback binary must reject Resource Groups' regional schema instead
+ of accepting it as v2 and silently dropping every regional store."""
+
+ import json as _json
+
+ from ministack.core.responses import AccountRegionScopedDict
+
+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)
+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))
+
+ groups = AccountRegionScopedDict()
+ groups.set_scoped(
+ "000000000000",
+ "us-west-2",
+ "regional-group",
+ {
+ "GroupArn": (
+ "arn:aws:resource-groups:us-west-2:000000000000:"
+ "group/regional-group"
+ )
+ },
+ )
+ persistence.save_state("resource_groups", {"groups": groups})
+
+ raw = _json.loads((tmp_path / "resource_groups.json").read_text())
+ assert raw["__ministack_format__"] == 3
+ loaded_groups = persistence.load_state("resource_groups")["groups"]
+ assert loaded_groups.get_scoped(
+ "000000000000", "us-west-2", "regional-group"
+ )["GroupArn"].endswith("group/regional-group")
+
+ # Simulate the previous binary, whose highest understood format is v2.
+ monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})
+ assert persistence.load_state("resource_groups") is None
+
+
def test_codebuild_region_scoped_state_is_rejected_by_v2_reader(
monkeypatch, tmp_path
):
diff --git a/tests/test_resource_groups.py b/tests/test_resource_groups.py
index 7a92a732..aa781fb6 100644
--- a/tests/test_resource_groups.py
+++ b/tests/test_resource_groups.py
@@ -6,6 +6,7 @@ exercised — they aren't reachable through the AWS CLI or Terraform.
"""
import json
+import os
import uuid
import boto3
@@ -13,15 +14,15 @@ import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
-ENDPOINT = "http://localhost:4566"
+ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
REGION = "us-east-1"
-def _client(account="test"):
+def _client(account="test", region=REGION):
return boto3.client(
"resource-groups",
endpoint_url=ENDPOINT,
- region_name=REGION,
+ region_name=region,
aws_access_key_id=account,
aws_secret_access_key="test",
config=Config(retries={"mode": "standard"}),
@@ -393,3 +394,87 @@ def test_account_isolation_for_groups():
assert exc.value.response["Error"]["Code"] == "NotFoundException"
finally:
a.delete_group(Group=name)
+
+
+def test_region_isolation_for_groups_and_account_settings():
+ east = _client(region="us-east-1")
+ west = _client(region="us-west-2")
+ name = f"region-{_uid()}"
+
+ east.create_group(
+ Name=name,
+ Description="east",
+ ResourceQuery=_tag_query("region", "east"),
+ )
+ west.create_group(
+ Name=name,
+ Description="west",
+ ResourceQuery=_tag_query("region", "west"),
+ )
+ try:
+ east_group = east.get_group(GroupName=name)["Group"]
+ west_group = west.get_group(GroupName=name)["Group"]
+ assert east_group["Description"] == "east"
+ assert west_group["Description"] == "west"
+ assert ":us-east-1:" in east_group["GroupArn"]
+ assert ":us-west-2:" in west_group["GroupArn"]
+
+ east.update_account_settings(GroupLifecycleEventsDesiredStatus="ACTIVE")
+ assert (
+ east.get_account_settings()["AccountSettings"][
+ "GroupLifecycleEventsDesiredStatus"
+ ]
+ == "ACTIVE"
+ )
+ assert (
+ west.get_account_settings()["AccountSettings"][
+ "GroupLifecycleEventsDesiredStatus"
+ ]
+ == "INACTIVE"
+ )
+ finally:
+ east.update_account_settings(GroupLifecycleEventsDesiredStatus="INACTIVE")
+ east.delete_group(Group=name)
+ west.delete_group(Group=name)
+
+
+def test_restore_legacy_child_state_uses_parent_group_region():
+ from ministack.core.responses import (
+ AccountScopedDict,
+ set_request_account_id,
+ set_request_region,
+ )
+ from ministack.services import resource_groups as service
+
+ account_id = "111111111111"
+ group_name = "legacy-group"
+ resource_region = "us-west-2"
+ boot_region = "us-east-1"
+ groups = AccountScopedDict()
+ queries = AccountScopedDict()
+
+ set_request_account_id(account_id)
+ set_request_region(boot_region)
+ groups[group_name] = {
+ "GroupArn": (
+ f"arn:aws:resource-groups:{resource_region}:{account_id}:"
+ f"group/{group_name}"
+ ),
+ "Name": group_name,
+ }
+ queries[group_name] = _tag_query("region", "legacy")
+
+ service.reset()
+ try:
+ service.restore_state({"groups": groups, "group_queries": queries})
+ assert service._groups.get_scoped(
+ account_id, resource_region, group_name
+ )["Name"] == group_name
+ assert service._group_queries.get_scoped(
+ account_id, resource_region, group_name
+ ) == _tag_query("region", "legacy")
+ assert service._group_queries.get_scoped(
+ account_id, boot_region, group_name
+ ) is None
+ finally:
+ service.reset()