Skip to content

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

Scope CodeBuild state by region (#1129)

Ian Oberstd16494d2461c
diff --git a/ministack/core/persistence.py b/ministack/core/persistence.py
index ce75aa76..491ba986 100644
--- a/ministack/core/persistence.py
+++ b/ministack/core/persistence.py
@@ -21,11 +21,15 @@ STATE_DIR = os.environ.get("STATE_DIR", "/tmp/ministack-state")
# {"__ministack_format__": N, "payload": <service state>}
# load_state refuses a file whose version is NEWER than this binary understands
# rather than mis-parsing it (the downgrade-corruption guard). Version 2 is the
-# default and introduced region-scoped (AccountRegionScopedDict) stores. ECS
-# uses version 3 because its service state was regionalized. Legacy unwrapped
-# files (implicit v1, account-scoped) still load and migrate. (U4)
+# default and introduced region-scoped (AccountRegionScopedDict) stores.
+# Services regionalized after v2 use version 3 so a v2 rollback refuses their
+# incompatible snapshots. Legacy unwrapped files (implicit v1, account-scoped)
+# still load and migrate. (U4)
STATE_FORMAT_VERSION = 2
-SERVICE_STATE_FORMAT_VERSIONS = {"ecs": 3}
+SERVICE_STATE_FORMAT_VERSIONS = {
+ "codebuild": 3,
+ "ecs": 3,
+}
def _state_format_version(service: str) -> int:
diff --git a/ministack/services/codebuild.py b/ministack/services/codebuild.py
index 1d6146d7..83fddb97 100644
--- a/ministack/services/codebuild.py
+++ b/ministack/services/codebuild.py
@@ -18,7 +18,7 @@ import time
from ministack.core.arn import ArnParseError, is_arn, parse_arn
from ministack.core.persistence import PERSIST_STATE, load_state
from ministack.core.responses import (
- AccountScopedDict,
+ AccountRegionScopedDict,
error_response_json,
get_account_id,
get_region,
@@ -33,8 +33,8 @@ REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# ---------------------------------------------------------------------------
# In-memory state
# ---------------------------------------------------------------------------
-_projects = AccountScopedDict() # project_name -> project record
-_builds = AccountScopedDict() # build_id -> build record
+_projects = AccountRegionScopedDict() # project_name -> project record
+_builds = AccountRegionScopedDict() # build_id -> build record
def reset():
diff --git a/tests/test_codebuild.py b/tests/test_codebuild.py
index bd91cf05..d5a374ff 100644
--- a/tests/test_codebuild.py
+++ b/tests/test_codebuild.py
@@ -1,8 +1,39 @@
+import os
+
+import boto3
import pytest
+from botocore.config import Config
from botocore.exceptions import ClientError
# ========== CodeBuild ==========
+
+def _client(region):
+ return boto3.client(
+ "codebuild",
+ endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),
+ region_name=region,
+ aws_access_key_id="test",
+ aws_secret_access_key="test",
+ config=Config(retries={"mode": "standard"}),
+ )
+
+
+def _project_args(name, description):
+ return {
+ "name": name,
+ "description": description,
+ "source": {"type": "NO_SOURCE"},
+ "artifacts": {"type": "NO_ARTIFACTS"},
+ "environment": {
+ "type": "LINUX_CONTAINER",
+ "image": "aws/codebuild/standard:7.0",
+ "computeType": "BUILD_GENERAL1_SMALL",
+ },
+ "serviceRole": "arn:aws:iam::000000000000:role/codebuild-role",
+ }
+
+
def _ensure_codebuild_project(codebuild, name):
if codebuild.batch_get_projects(names=[name])["projects"]:
return
@@ -153,3 +184,84 @@ def test_codebuild_delete_nonexistent_project(codebuild):
with pytest.raises(ClientError) as exc:
codebuild.delete_project(name="nonexistent")
assert "ResourceNotFoundException" in str(exc.value)
+
+
+def test_codebuild_projects_and_builds_are_region_scoped():
+ east = _client("us-east-1")
+ west = _client("us-west-2")
+ name = "same-name-regional-project"
+
+ east.create_project(**_project_args(name, "east"))
+ west.create_project(**_project_args(name, "west"))
+ try:
+ east_project = east.batch_get_projects(names=[name])["projects"][0]
+ west_project = west.batch_get_projects(names=[name])["projects"][0]
+ assert east_project["description"] == "east"
+ assert west_project["description"] == "west"
+ assert ":us-east-1:" in east_project["arn"]
+ assert ":us-west-2:" in west_project["arn"]
+ assert name in east.list_projects()["projects"]
+ assert name in west.list_projects()["projects"]
+
+ east_build = east.start_build(projectName=name)["build"]
+ west_build = west.start_build(projectName=name)["build"]
+ assert ":us-east-1:" in east_build["arn"]
+ assert ":us-west-2:" in west_build["arn"]
+ assert east_build["id"] in east.list_builds()["ids"]
+ assert east_build["id"] not in west.list_builds()["ids"]
+ assert west_build["id"] in west.list_builds()["ids"]
+ assert west_build["id"] not in east.list_builds()["ids"]
+ finally:
+ east.delete_project(name=name)
+ west.delete_project(name=name)
+
+
+def test_codebuild_restore_legacy_state_uses_resource_arn_region():
+ from ministack.core.responses import (
+ AccountScopedDict,
+ set_request_account_id,
+ set_request_region,
+ )
+ from ministack.services import codebuild as service
+
+ account_id = "111111111111"
+ resource_region = "us-west-2"
+ boot_region = "us-east-1"
+ project_name = "legacy-project"
+ build_id = f"{project_name}:legacy-build"
+ projects = AccountScopedDict()
+ builds = AccountScopedDict()
+
+ set_request_account_id(account_id)
+ set_request_region(boot_region)
+ projects[project_name] = {
+ "name": project_name,
+ "arn": (
+ f"arn:aws:codebuild:{resource_region}:{account_id}:"
+ f"project/{project_name}"
+ ),
+ }
+ builds[build_id] = {
+ "id": build_id,
+ "arn": (
+ f"arn:aws:codebuild:{resource_region}:{account_id}:build/{build_id}"
+ ),
+ }
+
+ service.reset()
+ try:
+ service.restore_state({"projects": projects, "builds": builds})
+ assert service._projects.get_scoped(
+ account_id, resource_region, project_name
+ )["name"] == project_name
+ assert service._builds.get_scoped(
+ account_id, resource_region, build_id
+ )["id"] == build_id
+ assert service._projects.get_scoped(
+ account_id, boot_region, project_name
+ ) is None
+ assert service._builds.get_scoped(
+ account_id, boot_region, build_id
+ ) is None
+ finally:
+ service.reset()
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
index ac978d82..ff02576c 100644
--- a/tests/test_persistence.py
+++ b/tests/test_persistence.py
@@ -1830,3 +1830,41 @@ def test_ecs_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmp_path)
# Simulate the previous binary, whose highest understood format is v2.
monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})
assert persistence.load_state("ecs") is None
+
+
+def test_codebuild_region_scoped_state_is_rejected_by_v2_reader(
+ monkeypatch, tmp_path
+):
+ """A rollback binary must reject CodeBuild's 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))
+
+ projects = AccountRegionScopedDict()
+ projects.set_scoped(
+ "000000000000",
+ "us-west-2",
+ "regional-project",
+ {
+ "arn": (
+ "arn:aws:codebuild:us-west-2:000000000000:"
+ "project/regional-project"
+ )
+ },
+ )
+ persistence.save_state("codebuild", {"projects": projects})
+
+ raw = _json.loads((tmp_path / "codebuild.json").read_text())
+ assert raw["__ministack_format__"] == 3
+ loaded_projects = persistence.load_state("codebuild")["projects"]
+ assert loaded_projects.get_scoped(
+ "000000000000", "us-west-2", "regional-project"
+ )["arn"].endswith("project/regional-project")
+
+ # Simulate the previous binary, whose highest understood format is v2.
+ monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})
+ assert persistence.load_state("codebuild") is None