Skip to content

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

fix(several): pending open issues (#1132)

Nahuel Nuceraad52b452226a
diff --git a/README.md b/README.md
index b1637122..a9d04a79 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) |
-| `test-key-do-not-use` | `000000000000` (default) |
+| `AKIAIOSFODNN7EXAMPLE` | `000000000000` (default) |
**Terraform** — set `access_key` in your provider block:
```hcl
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index 78ddc262..4f2a9928 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -1020,10 +1020,39 @@ def _describe_security_groups(p):
f"<securityGroupInfo>{items}</securityGroupInfo>")
-def _sg_rule_xml(sg_id, rule, idx, is_egress=False):
- """Build <securityGroupRuleSet> items for Authorize responses (provider v6)."""
+def _sg_rule_id(sg_id, is_egress, rule):
+ """Stable, content-derived SecurityGroupRuleId.
+
+ Real AWS assigns a durable ``sgr-*`` id at authorize time, and Terraform's
+ ``aws_vpc_security_group_ingress_rule`` tracks that id across refreshes. An
+ index-based id shifts when any earlier rule is revoked, so a later
+ DescribeSecurityGroupRules by id returns nothing -- issue #1121. Deriving the
+ id from the rule's content keeps it stable regardless of list position or
+ process restarts, and identical between Authorize and Describe.
+ """
direction = "egress" if is_egress else "ingress"
- rule_id = f"sgr-{sg_id[3:]}-{direction}-{idx}"
+ parts = [
+ sg_id,
+ direction,
+ str(rule.get("IpProtocol", "-1")),
+ str(rule.get("FromPort", -1)),
+ str(rule.get("ToPort", -1)),
+ ]
+ for cidr in rule.get("IpRanges", []):
+ parts.append("v4:" + (cidr.get("CidrIp", "") if isinstance(cidr, dict) else str(cidr)))
+ for cidr6 in rule.get("Ipv6Ranges", []):
+ parts.append("v6:" + (cidr6.get("CidrIpv6", "") if isinstance(cidr6, dict) else str(cidr6)))
+ for pair in rule.get("UserIdGroupPairs", []):
+ parts.append("g:" + (pair.get("GroupId", "") if isinstance(pair, dict) else str(pair)))
+ for prefix in rule.get("PrefixListIds", []):
+ parts.append("p:" + (prefix.get("PrefixListId", "") if isinstance(prefix, dict) else str(prefix)))
+ digest = hashlib.sha1("|".join(parts).encode()).hexdigest()[:17]
+ return f"sgr-{digest}"
+
+
+def _sg_rule_xml(sg_id, rule, is_egress=False):
+ """Build <securityGroupRuleSet> items for Authorize responses (provider v6)."""
+ rule_id = _sg_rule_id(sg_id, is_egress, rule)
items = ""
for cidr in rule.get("IpRanges", []):
items += (f"<item>"
@@ -1076,9 +1105,8 @@ def _sg_rule_xml(sg_id, rule, idx, is_egress=False):
return items
-def _revoked_sg_rule_xml(sg_id, rule, idx, is_egress=False):
- direction = "egress" if is_egress else "ingress"
- rule_id = f"sgr-{sg_id[3:]}-{direction}-{idx}"
+def _revoked_sg_rule_xml(sg_id, rule, is_egress=False):
+ rule_id = _sg_rule_id(sg_id, is_egress, rule)
def _item(extra_xml=""):
from_port = f"<fromPort>{rule['FromPort']}</fromPort>" if "FromPort" in rule else ""
@@ -1147,8 +1175,7 @@ def _authorize_sg_ingress(p):
# Terraform InvalidPermission.Duplicate when the provider re-authorizes unchanged rules).
if not any(_rules_match(r, existing) for existing in sg["IpPermissions"]):
sg["IpPermissions"].append(r)
- idx = len(sg["IpPermissions"]) - 1
- rule_items += _sg_rule_xml(sg_id, r, idx, is_egress=False)
+ rule_items += _sg_rule_xml(sg_id, r, is_egress=False)
return _xml(200, "AuthorizeSecurityGroupIngressResponse",
f"<return>true</return><securityGroupRuleSet>{rule_items}</securityGroupRuleSet>")
@@ -1174,8 +1201,7 @@ def _authorize_sg_egress(p):
for r in rules:
if not any(_rules_match(r, existing) for existing in sg["IpPermissionsEgress"]):
sg["IpPermissionsEgress"].append(r)
- idx = len(sg["IpPermissionsEgress"]) - 1
- rule_items += _sg_rule_xml(sg_id, r, idx, is_egress=True)
+ rule_items += _sg_rule_xml(sg_id, r, is_egress=True)
return _xml(200, "AuthorizeSecurityGroupEgressResponse",
f"<return>true</return><securityGroupRuleSet>{rule_items}</securityGroupRuleSet>")
@@ -1188,9 +1214,9 @@ def _revoke_sg_egress(p):
rules = _parse_ip_permissions(p, "IpPermissions")
revoked_items = ""
remaining = []
- for idx, existing in enumerate(sg["IpPermissionsEgress"]):
+ for existing in sg["IpPermissionsEgress"]:
if any(_rules_match(r, existing) for r in rules):
- revoked_items += _revoked_sg_rule_xml(sg_id, existing, idx, is_egress=True)
+ revoked_items += _revoked_sg_rule_xml(sg_id, existing, is_egress=True)
else:
remaining.append(existing)
sg["IpPermissionsEgress"] = remaining
@@ -4637,73 +4663,30 @@ def _describe_addresses_attribute(p):
def _describe_security_group_rules(p):
- sg_ids = _parse_member_list(p, "SecurityGroupId") or []
+ # Terraform's aws_vpc_security_group_ingress_rule refreshes by calling
+ # DescribeSecurityGroupRules with SecurityGroupRuleIds and no group filter,
+ # so honoring the rule-id filter is what stops the "Resource Not Found During
+ # Refresh" in issue #1121. group-id / SecurityGroupId still scope the scan;
+ # with neither filter, AWS returns every rule in the region.
filters = _parse_filters(p)
- sg_id_filter = filters.get("group-id", [])
- if sg_id_filter:
- sg_ids = sg_id_filter
+ rule_id_filter = set(_parse_member_list(p, "SecurityGroupRuleId") or [])
+ rule_id_filter.update(filters.get("security-group-rule-id", []))
+
+ sg_ids = filters.get("group-id") or _parse_member_list(p, "SecurityGroupId") or []
+ if sg_ids:
+ groups = [(gid, _security_groups.get(gid)) for gid in sg_ids]
+ else:
+ groups = [(sg.get("GroupId"), sg) for sg in _security_groups.values()]
items = ""
- for sg_id in sg_ids:
- sg = _security_groups.get(sg_id)
+ for sg_id, sg in groups:
if not sg:
continue
- for i, rule in enumerate(sg.get("IpPermissions", [])):
- rule_id = f"sgr-{sg_id[3:]}-ingress-{i}"
- for cidr in rule.get("IpRanges", []):
- items += f"""<item>
- <securityGroupRuleId>{rule_id}</securityGroupRuleId>
- <groupId>{sg_id}</groupId>
- <groupOwnerId>{get_account_id()}</groupOwnerId>
- <isEgress>false</isEgress>
- <ipProtocol>{rule.get('IpProtocol', '-1')}</ipProtocol>
- <fromPort>{rule.get('FromPort', -1)}</fromPort>
- <toPort>{rule.get('ToPort', -1)}</toPort>
- <cidrIpv4>{cidr.get('CidrIp', '')}</cidrIpv4>
- </item>"""
- for pair in rule.get("UserIdGroupPairs", []):
- gid = pair.get("GroupId", "") if isinstance(pair, dict) else str(pair)
- items += f"""<item>
- <securityGroupRuleId>{rule_id}</securityGroupRuleId>
- <groupId>{sg_id}</groupId>
- <groupOwnerId>{get_account_id()}</groupOwnerId>
- <isEgress>false</isEgress>
- <ipProtocol>{rule.get('IpProtocol', '-1')}</ipProtocol>
- <fromPort>{rule.get('FromPort', -1)}</fromPort>
- <toPort>{rule.get('ToPort', -1)}</toPort>
- <referencedGroupInfo>
- <groupId>{gid}</groupId>
- <userId>{get_account_id()}</userId>
- </referencedGroupInfo>
- </item>"""
- for i, rule in enumerate(sg.get("IpPermissionsEgress", [])):
- rule_id = f"sgr-{sg_id[3:]}-egress-{i}"
- for cidr in rule.get("IpRanges", []):
- items += f"""<item>
- <securityGroupRuleId>{rule_id}</securityGroupRuleId>
- <groupId>{sg_id}</groupId>
- <groupOwnerId>{get_account_id()}</groupOwnerId>
- <isEgress>true</isEgress>
- <ipProtocol>{rule.get('IpProtocol', '-1')}</ipProtocol>
- <fromPort>{rule.get('FromPort', -1)}</fromPort>
- <toPort>{rule.get('ToPort', -1)}</toPort>
- <cidrIpv4>{cidr.get('CidrIp', '')}</cidrIpv4>
- </item>"""
- for pair in rule.get("UserIdGroupPairs", []):
- gid = pair.get("GroupId", "") if isinstance(pair, dict) else str(pair)
- items += f"""<item>
- <securityGroupRuleId>{rule_id}</securityGroupRuleId>
- <groupId>{sg_id}</groupId>
- <groupOwnerId>{get_account_id()}</groupOwnerId>
- <isEgress>true</isEgress>
- <ipProtocol>{rule.get('IpProtocol', '-1')}</ipProtocol>
- <fromPort>{rule.get('FromPort', -1)}</fromPort>
- <toPort>{rule.get('ToPort', -1)}</toPort>
- <referencedGroupInfo>
- <groupId>{gid}</groupId>
- <userId>{get_account_id()}</userId>
- </referencedGroupInfo>
- </item>"""
+ for is_egress, key in ((False, "IpPermissions"), (True, "IpPermissionsEgress")):
+ for rule in sg.get(key, []):
+ if rule_id_filter and _sg_rule_id(sg_id, is_egress, rule) not in rule_id_filter:
+ continue
+ items += _sg_rule_xml(sg_id, rule, is_egress=is_egress)
return _xml(200, "DescribeSecurityGroupRulesResponse", f"<securityGroupRuleSet>{items}</securityGroupRuleSet>")
diff --git a/ministack/services/kms.py b/ministack/services/kms.py
index d67479d0..b6451aa4 100644
--- a/ministack/services/kms.py
+++ b/ministack/services/kms.py
@@ -910,10 +910,12 @@ def _generate_data_key_pair_common(data, action):
err = _check_key_state(rec)
if err:
return None, None, err
- # The CMK must be symmetric: it wraps the generated private key.
+ # The CMK must be symmetric: it wraps the generated private key. Real AWS
+ # rejects an asymmetric CMK here with InvalidKeyUsageException (the KeyUsage
+ # is incompatible with generating data keys), not UnsupportedOperationException.
if "_symmetric_key" not in rec:
return None, None, error_response_json(
- "UnsupportedOperationException",
+ "InvalidKeyUsageException",
f"{action} requires a symmetric key",
400,
)
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index abdc8b2b..890e7f8b 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -2706,21 +2706,27 @@ def _pool_clear_all() -> None:
def _pool_kill_function(account: str, func_name: str) -> None:
"""Kill every pooled docker container for a function across all qualifiers.
- The pool key is ``{account}:{func_name}:zip:{CodeSha256}`` (or
+ The pool key is ``{account}:{region}:{func_name}:zip:{CodeSha256}`` (or
``:image:{ImageUri}``). UpdateFunctionConfiguration changes attributes that
don't show up in the key (Layers / Environment / MemorySize / VpcConfig /
Architectures / FileSystemConfigs / Runtime / Handler), so the same key
would otherwise hand back a stale container that was spawned before the
- config change. Issue #816 docker-executor follow-up: a layer attached
- after the first invoke was never mounted on the reused warm container,
- so handler imports from the layer kept failing even after the layer's
- extracted dir was correct.
+ config change.
+
+ The region segment sits between ``account`` and ``func_name`` (added when the
+ warm-pool key became region-scoped). Match on the account and func_name
+ positions rather than a leading ``{account}:{func_name}:`` prefix -- that
+ prefix stopped matching any key after regionalization and left the old
+ container running with stale config after every UpdateFunctionConfiguration
+ (issue #1118). Issue #816 docker-executor follow-up: a layer attached after
+ the first invoke was never mounted on the reused warm container.
"""
- prefix = f"{account}:{func_name}:"
to_kill = []
with _warm_pool_lock:
for key in list(_warm_pool.keys()):
- if key.startswith(prefix):
+ # key == "{account}:{region}:{func_name}:{zip|image}:{...}"
+ parts = key.split(":")
+ if len(parts) >= 3 and parts[0] == account and parts[2] == func_name:
to_kill.extend(_warm_pool.pop(key))
for e in to_kill:
_kill_pool_entry(e)
diff --git a/tests/test_ec2.py b/tests/test_ec2.py
index fcd43053..d6f9f33a 100644
--- a/tests/test_ec2.py
+++ b/tests/test_ec2.py
@@ -2642,3 +2642,58 @@ def test_describe_fleets_unknown_id_returns_invalid_fleet_id(ec2):
ec2.describe_fleets(FleetIds=[bogus])
assert exc.value.response["Error"]["Code"] == "InvalidFleetId.NotFound"
+
+def test_describe_security_group_rules_by_id_without_group_filter(ec2):
+ """Regression for #1121: Terraform's aws_vpc_security_group_ingress_rule
+ refreshes by calling DescribeSecurityGroupRules(SecurityGroupRuleIds=[...])
+ with no group filter, and the rule id must stay stable when other rules on
+ the same group are revoked."""
+ vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")["Vpc"]
+ sg = ec2.create_security_group(
+ GroupName=f"sgr-1121-{_uuid_mod.uuid4().hex[:8]}",
+ Description="issue-1121",
+ VpcId=vpc["VpcId"],
+ )["GroupId"]
+
+ rule_a = ec2.authorize_security_group_ingress(
+ GroupId=sg,
+ IpPermissions=[{
+ "IpProtocol": "tcp", "FromPort": 22, "ToPort": 22,
+ "IpRanges": [{"CidrIp": "10.0.0.0/24"}],
+ }],
+ )["SecurityGroupRules"][0]["SecurityGroupRuleId"]
+ rule_b = ec2.authorize_security_group_ingress(
+ GroupId=sg,
+ IpPermissions=[{
+ "IpProtocol": "tcp", "FromPort": 80, "ToPort": 80,
+ "IpRanges": [{"CidrIp": "10.0.1.0/24"}],
+ }],
+ )["SecurityGroupRules"][0]["SecurityGroupRuleId"]
+
+ assert rule_a.startswith("sgr-") and rule_b.startswith("sgr-")
+ assert rule_a != rule_b
+
+ # Refresh by id with NO group filter -- the exact call Terraform makes.
+ found = ec2.describe_security_group_rules(
+ SecurityGroupRuleIds=[rule_b],
+ )["SecurityGroupRules"]
+ assert [r["SecurityGroupRuleId"] for r in found] == [rule_b]
+
+ # Revoking rule_a must not shift rule_b's id (index-based ids did).
+ ec2.revoke_security_group_ingress(
+ GroupId=sg,
+ IpPermissions=[{
+ "IpProtocol": "tcp", "FromPort": 22, "ToPort": 22,
+ "IpRanges": [{"CidrIp": "10.0.0.0/24"}],
+ }],
+ )
+ still_found = ec2.describe_security_group_rules(
+ SecurityGroupRuleIds=[rule_b],
+ )["SecurityGroupRules"]
+ assert [r["SecurityGroupRuleId"] for r in still_found] == [rule_b]
+
+ # The revoked rule's id no longer resolves.
+ assert ec2.describe_security_group_rules(
+ SecurityGroupRuleIds=[rule_a],
+ )["SecurityGroupRules"] == []
+
diff --git a/tests/test_kms.py b/tests/test_kms.py
index 943d9bf4..2e98a5f9 100644
--- a/tests/test_kms.py
+++ b/tests/test_kms.py
@@ -410,7 +410,7 @@ def test_kms_generate_data_key_pair_requires_symmetric_key(kms_client):
kms_client.generate_data_key_pair(
KeyId=key_id, KeyPairSpec="ECC_NIST_EDWARDS25519"
)
- assert exc.value.response["Error"]["Code"] == "UnsupportedOperationException"
+ assert exc.value.response["Error"]["Code"] == "InvalidKeyUsageException"
assert "GenerateDataKeyPair requires" in exc.value.response["Error"]["Message"]
def test_kms_generate_data_key_pair_without_plaintext_ed25519(kms_client):
@@ -535,7 +535,7 @@ def test_kms_generate_data_key_pair_without_plaintext_requires_symmetric_key(kms
kms_client.generate_data_key_pair_without_plaintext(
KeyId=key_id, KeyPairSpec="ECC_NIST_EDWARDS25519"
)
- assert exc.value.response["Error"]["Code"] == "UnsupportedOperationException"
+ assert exc.value.response["Error"]["Code"] == "InvalidKeyUsageException"
# Names this operation, not the GenerateDataKeyPair variant it shares a helper with.
assert (
"GenerateDataKeyPairWithoutPlaintext requires"
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 9acb38f1..982c048c 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -2860,7 +2860,13 @@ def test_lambda_pool_kill_function_reaps_all_qualifiers():
config-only updates leave stale entries unless explicitly reaped). Issue
#816 docker-executor follow-up. Wired into _update_config / _delete_function
so layer attach via UpdateFunctionConfiguration displaces the pre-attach
- container before the next invoke."""
+ container before the next invoke.
+
+ Regression for #1118: the warm-pool key is region-scoped
+ ({account}:{region}:{func}:zip:{sha}), so the keys here MUST carry the region
+ segment. A previous prefix match of ``{account}:{func}:`` silently matched
+ nothing once the key gained a region, so UpdateFunctionConfiguration left the
+ old docker container running with stale config."""
from ministack.services import lambda_svc as _svc
class _StubContainer:
@@ -2874,9 +2880,9 @@ def test_lambda_pool_kill_function_reaps_all_qualifiers():
stubs = [_StubContainer() for _ in range(3)]
keys = [
- "111122223333:fn-A:zip:sha-v1",
- "111122223333:fn-A:zip:sha-v2",
- "111122223333:fn-B:zip:sha-v1", # different function — must NOT be touched
+ "111122223333:us-east-1:fn-A:zip:sha-v1",
+ "111122223333:us-east-1:fn-A:zip:sha-v2",
+ "111122223333:us-east-1:fn-B:zip:sha-v1", # different function — must NOT be touched
]
with _svc._warm_pool_lock:
for k, s in zip(keys, stubs):
@@ -2889,10 +2895,10 @@ def test_lambda_pool_kill_function_reaps_all_qualifiers():
_svc._pool_kill_function("111122223333", "fn-A")
with _svc._warm_pool_lock:
- assert _svc._warm_pool.get("111122223333:fn-A:zip:sha-v1", []) == []
- assert _svc._warm_pool.get("111122223333:fn-A:zip:sha-v2", []) == []
+ assert _svc._warm_pool.get("111122223333:us-east-1:fn-A:zip:sha-v1", []) == []
+ assert _svc._warm_pool.get("111122223333:us-east-1:fn-A:zip:sha-v2", []) == []
# fn-B must be untouched
- assert len(_svc._warm_pool.get("111122223333:fn-B:zip:sha-v1", [])) == 1
+ assert len(_svc._warm_pool.get("111122223333:us-east-1:fn-B:zip:sha-v1", [])) == 1
assert stubs[0].stopped and stubs[0].removed, "fn-A v1 container not killed"
assert stubs[1].stopped and stubs[1].removed, "fn-A v2 container not killed"
diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py
index e5f6230b..c11a5779 100644
--- a/tests/test_scheduler.py
+++ b/tests/test_scheduler.py
@@ -1,3 +1,4 @@
+import asyncio
import json
import time
@@ -5,6 +6,14 @@ import boto3
import pytest
from botocore.exceptions import ClientError
+import ministack.services.scheduler as scheduler_mod
+from ministack.core.responses import (
+ get_account_id,
+ get_region,
+ set_request_account_id,
+ set_request_region,
+)
+
ENDPOINT = "http://localhost:4566"
REGION = "us-east-1"
@@ -601,3 +610,274 @@ def test_scheduler_fires_at_expression_to_sqs(scheduler):
except ClientError:
pass
sqs.delete_queue(QueueUrl=q_url)
+
+
+# ---------------------------------------------------------------------------
+# ARN adoption, region scoping, and the firing ticker. Folded from
+# test_scheduler_arn_adoption.py: these drive the scheduler module
+# in-process (scheduler_mod.*) rather than through boto3.
+# ---------------------------------------------------------------------------
+
+
[email protected](autouse=True)
+def _reset_scheduler():
+ set_request_account_id("000000000000")
+ set_request_region("us-east-1")
+ scheduler_mod.reset()
+ scheduler_mod._schedule_last_fired.clear()
+ scheduler_mod._ticker_thread = None
+ yield
+ scheduler_mod.reset()
+ scheduler_mod._schedule_last_fired.clear()
+ scheduler_mod._ticker_thread = None
+
+
+def _request(method, path, body=None, query=None):
+ payload = json.dumps(body or {}).encode()
+ return asyncio.run(
+ scheduler_mod.handle_request(method, path, {}, payload, query or {})
+ )
+
+
+def _body(resp):
+ return json.loads(resp[2].decode())
+
+
+def _create_schedule(group="default"):
+ name = f"sched-{_uid()}"
+ body = {
+ "ScheduleExpression": "rate(1 hour)",
+ "FlexibleTimeWindow": {"Mode": "OFF"},
+ "Target": {
+ "Arn": "arn:aws:lambda:us-east-1:000000000000:function:noop",
+ "RoleArn": "arn:aws:iam::000000000000:role/test",
+ },
+ }
+ if group != "default":
+ body["GroupName"] = group
+ resp = _request("POST", f"/schedules/{name}", body)
+ assert resp[0] == 200
+ return name, _body(resp)["ScheduleArn"]
+
+
+def _create_group():
+ name = f"group-{_uid()}"
+ resp = _request("POST", f"/schedule-groups/{name}")
+ assert resp[0] == 200
+ return name, _body(resp)["ScheduleGroupArn"]
+
+
+def _assert_error(resp, status, code):
+ assert resp[0] == status
+ assert _body(resp)["__type"] == code
+
+
+def test_scheduler_tag_apis_accept_local_schedule_arn():
+ name, arn = _create_schedule()
+
+ resp = _request("POST", f"/tags/{arn}", {"Tags": [{"Key": "env", "Value": "test"}]})
+ assert resp[0] == 200
+
+ resp = _request("GET", f"/tags/{arn}")
+ assert _body(resp)["Tags"] == [{"Key": "env", "Value": "test"}]
+
+ resp = _request("DELETE", f"/tags/{arn}", query={"TagKeys": ["env"]})
+ assert resp[0] == 200
+ assert _body(_request("GET", f"/tags/{arn}"))["Tags"] == []
+ assert f"default/{name}" in scheduler_mod._schedules
+
+
+def test_scheduler_tag_apis_accept_local_schedule_group_arn():
+ _name, arn = _create_group()
+
+ resp = _request("POST", f"/tags/{arn}", {"Tags": [{"Key": "team", "Value": "platform"}]})
+ assert resp[0] == 200
+
+ resp = _request("GET", f"/tags/{arn}")
+ assert _body(resp)["Tags"] == [{"Key": "team", "Value": "platform"}]
+
+
+def test_scheduler_tag_apis_accept_default_schedule_group_arn():
+ arn = "arn:aws:scheduler:us-east-1:000000000000:schedule-group/default"
+
+ resp = _request("POST", f"/tags/{arn}", {"Tags": [{"Key": "default", "Value": "yes"}]})
+ assert resp[0] == 200
+
+ resp = _request("GET", f"/tags/{arn}")
+ assert _body(resp)["Tags"] == [{"Key": "default", "Value": "yes"}]
+
+
+def test_scheduler_tag_apis_do_not_resolve_same_named_resources_from_other_region():
+ set_request_region("us-west-2")
+ _schedule_name, west_schedule_arn = _create_schedule()
+ _group_name, west_group_arn = _create_group()
+
+ set_request_region("us-east-1")
+ east_schedule_arn = west_schedule_arn.replace(":us-west-2:", ":us-east-1:")
+ east_group_arn = west_group_arn.replace(":us-west-2:", ":us-east-1:")
+
+ for arn in (east_schedule_arn, east_group_arn):
+ resp = _request("POST", f"/tags/{arn}", {"Tags": [{"Key": "env", "Value": "bad"}]})
+ _assert_error(resp, 404, "ResourceNotFoundException")
+ assert scheduler_mod._tags.get(arn) is None
+
+ assert scheduler_mod._tags.get(west_schedule_arn) is None
+ assert scheduler_mod._tags.get(west_group_arn) is None
+
+
+def test_scheduler_ticker_dispatches_in_schedule_region_and_restores_context(monkeypatch):
+ from ministack.services import eventbridge
+
+ account_id = "000000000000"
+ name = f"ticker-{_uid()}"
+ key = f"default/{name}"
+ expected = {}
+ for region in ("us-east-1", "us-west-2"):
+ schedule_arn = f"arn:aws:scheduler:{region}:{account_id}:schedule/{key}"
+ target_arn = f"arn:aws:lambda:{region}:{account_id}:function:ticker-target"
+ expected[region] = (schedule_arn, target_arn)
+ scheduler_mod._schedules.set_scoped(
+ account_id,
+ region,
+ key,
+ {
+ "Arn": schedule_arn,
+ "Name": name,
+ "GroupName": "default",
+ "ScheduleExpression": "at(1970-01-01T00:00:01)",
+ "Target": {"Arn": target_arn},
+ "State": "ENABLED",
+ "ActionAfterCompletion": "NONE",
+ "CreationDate": 1,
+ },
+ )
+ set_request_account_id("111111111111")
+ set_request_region("eu-west-1")
+
+ calls = []
+
+ def _capture_target(target, event, schedule):
+ calls.append((get_account_id(), get_region(), target, event, schedule))
+
+ monkeypatch.setattr(eventbridge, "_invoke_target", _capture_target)
+ monkeypatch.setattr(scheduler_mod.time, "time", lambda: 2.0)
+
+ scheduler_mod._tick_schedules()
+
+ assert len(calls) == 2
+ calls_by_region = {call[1]: call for call in calls}
+ assert set(calls_by_region) == set(expected)
+ for region, (schedule_arn, target_arn) in expected.items():
+ dispatch_account, dispatch_region, target, event, schedule = calls_by_region[region]
+ assert (dispatch_account, dispatch_region) == (account_id, region)
+ assert target["Arn"] == target_arn
+ assert event["Account"] == account_id
+ assert event["Region"] == region
+ assert event["Resources"] == [schedule_arn]
+ assert schedule["Arn"] == schedule_arn
+ assert (get_account_id(), get_region()) == ("111111111111", "eu-west-1")
+
+
+def test_scheduler_start_scheduler_starts_daemon_once(monkeypatch):
+ created_threads = []
+
+ class _FakeThread:
+ def __init__(self, *, target, daemon, name):
+ self.target = target
+ self.daemon = daemon
+ self.name = name
+ self.started = False
+ created_threads.append(self)
+
+ def start(self):
+ self.started = True
+
+ def is_alive(self):
+ return self.started
+
+ monkeypatch.setattr(scheduler_mod.threading, "Thread", _FakeThread)
+
+ scheduler_mod.start_scheduler()
+ scheduler_mod.start_scheduler()
+
+ assert len(created_threads) == 1
+ thread = created_threads[0]
+ assert thread.target is scheduler_mod._ticker_loop
+ assert thread.daemon is True
+ assert thread.name == "evb-scheduler-ticker"
+ assert thread.started is True
+
+
+def test_scheduler_unknown_route_returns_validation_error():
+ response = _request("GET", "/unknown")
+
+ _assert_error(response, 400, "ValidationException")
+
+
+ "bad_arn, expected_status, expected_code",
+ [
+ ("not-an-arn", 400, "ValidationException"),
+ (
+ "arn:aws-us-gov:scheduler:us-east-1:000000000000:schedule/default/{name}",
+ 404,
+ "ResourceNotFoundException",
+ ),
+ (
+ "arn:aws:events:us-east-1:000000000000:schedule/default/{name}",
+ 404,
+ "ResourceNotFoundException",
+ ),
+ (
+ "arn:aws:scheduler:us-east-1:111111111111:schedule/default/{name}",
+ 404,
+ "ResourceNotFoundException",
+ ),
+ (
+ "arn:aws:scheduler:us-west-2:000000000000:schedule/default/{name}",
+ 404,
+ "ResourceNotFoundException",
+ ),
+ (
+ "arn:aws:scheduler:us-east-1:000000000000:schedule/default",
+ 404,
+ "ResourceNotFoundException",
+ ),
+ (
+ "arn:aws:scheduler:us-east-1:000000000000:schedule/default/{name}/extra",
+ 404,
+ "ResourceNotFoundException",
+ ),
+ (
+ "arn:aws:scheduler:us-east-1:000000000000:rule/default/{name}",
+ 404,
+ "ResourceNotFoundException",
+ ),
+ (
+ "arn:aws:scheduler:us-east-1:000000000000:schedule/default/missing-{name}",
+ 404,
+ "ResourceNotFoundException",
+ ),
+ (
+ "arn:aws:scheduler:us-east-1:000000000000:schedule-group/missing-{name}",
+ 404,
+ "ResourceNotFoundException",
+ ),
+ ],
+)
[email protected]("method", ["GET", "POST", "DELETE"])
+def test_scheduler_tag_apis_reject_invalid_resource_arns_before_touching_tags(
+ method, bad_arn, expected_status, expected_code
+):
+ name, good_arn = _create_schedule()
+ _request("POST", f"/tags/{good_arn}", {"Tags": [{"Key": "env", "Value": "good"}]})
+ baseline = dict(scheduler_mod._tags.get(good_arn, {}))
+ arn = bad_arn.format(name=name)
+
+ body = {"Tags": [{"Key": "env", "Value": "bad"}]} if method == "POST" else None
+ query = {"TagKeys": ["env"]} if method == "DELETE" else None
+ resp = _request(method, f"/tags/{arn}", body=body, query=query)
+
+ _assert_error(resp, expected_status, expected_code)
+ assert scheduler_mod._tags.get(good_arn, {}) == baseline
+ assert scheduler_mod._tags.get(arn) is None
diff --git a/tests/test_scheduler_arn_adoption.py b/tests/test_scheduler_arn_adoption.py
deleted file mode 100644
index 9467e0cb..00000000
--- a/tests/test_scheduler_arn_adoption.py
+++ /dev/null
@@ -1,281 +0,0 @@
-import asyncio
-import json
-import uuid
-
-import pytest
-
-import ministack.services.scheduler as scheduler
-from ministack.core.responses import (
- get_account_id,
- get_region,
- set_request_account_id,
- set_request_region,
-)
-
-
-def _uid():
- return uuid.uuid4().hex[:8]
-
-
[email protected](autouse=True)
-def _reset_scheduler():
- set_request_account_id("000000000000")
- set_request_region("us-east-1")
- scheduler.reset()
- scheduler._schedule_last_fired.clear()
- scheduler._ticker_thread = None
- yield
- scheduler.reset()
- scheduler._schedule_last_fired.clear()
- scheduler._ticker_thread = None
-
-
-def _request(method, path, body=None, query=None):
- payload = json.dumps(body or {}).encode()
- return asyncio.run(
- scheduler.handle_request(method, path, {}, payload, query or {})
- )
-
-
-def _body(resp):
- return json.loads(resp[2].decode())
-
-
-def _create_schedule(group="default"):
- name = f"sched-{_uid()}"
- body = {
- "ScheduleExpression": "rate(1 hour)",
- "FlexibleTimeWindow": {"Mode": "OFF"},
- "Target": {
- "Arn": "arn:aws:lambda:us-east-1:000000000000:function:noop",
- "RoleArn": "arn:aws:iam::000000000000:role/test",
- },
- }
- if group != "default":
- body["GroupName"] = group
- resp = _request("POST", f"/schedules/{name}", body)
- assert resp[0] == 200
- return name, _body(resp)["ScheduleArn"]
-
-
-def _create_group():
- name = f"group-{_uid()}"
- resp = _request("POST", f"/schedule-groups/{name}")
- assert resp[0] == 200
- return name, _body(resp)["ScheduleGroupArn"]
-
-
-def _assert_error(resp, status, code):
- assert resp[0] == status
- assert _body(resp)["__type"] == code
-
-
-def test_scheduler_tag_apis_accept_local_schedule_arn():
- name, arn = _create_schedule()
-
- resp = _request("POST", f"/tags/{arn}", {"Tags": [{"Key": "env", "Value": "test"}]})
- assert resp[0] == 200
-
- resp = _request("GET", f"/tags/{arn}")
- assert _body(resp)["Tags"] == [{"Key": "env", "Value": "test"}]
-
- resp = _request("DELETE", f"/tags/{arn}", query={"TagKeys": ["env"]})
- assert resp[0] == 200
- assert _body(_request("GET", f"/tags/{arn}"))["Tags"] == []
- assert f"default/{name}" in scheduler._schedules
-
-
-def test_scheduler_tag_apis_accept_local_schedule_group_arn():
- _name, arn = _create_group()
-
- resp = _request("POST", f"/tags/{arn}", {"Tags": [{"Key": "team", "Value": "platform"}]})
- assert resp[0] == 200
-
- resp = _request("GET", f"/tags/{arn}")
- assert _body(resp)["Tags"] == [{"Key": "team", "Value": "platform"}]
-
-
-def test_scheduler_tag_apis_accept_default_schedule_group_arn():
- arn = "arn:aws:scheduler:us-east-1:000000000000:schedule-group/default"
-
- resp = _request("POST", f"/tags/{arn}", {"Tags": [{"Key": "default", "Value": "yes"}]})
- assert resp[0] == 200
-
- resp = _request("GET", f"/tags/{arn}")
- assert _body(resp)["Tags"] == [{"Key": "default", "Value": "yes"}]
-
-
-def test_scheduler_tag_apis_do_not_resolve_same_named_resources_from_other_region():
- set_request_region("us-west-2")
- _schedule_name, west_schedule_arn = _create_schedule()
- _group_name, west_group_arn = _create_group()
-
- set_request_region("us-east-1")
- east_schedule_arn = west_schedule_arn.replace(":us-west-2:", ":us-east-1:")
- east_group_arn = west_group_arn.replace(":us-west-2:", ":us-east-1:")
-
- for arn in (east_schedule_arn, east_group_arn):
- resp = _request("POST", f"/tags/{arn}", {"Tags": [{"Key": "env", "Value": "bad"}]})
- _assert_error(resp, 404, "ResourceNotFoundException")
- assert scheduler._tags.get(arn) is None
-
- assert scheduler._tags.get(west_schedule_arn) is None
- assert scheduler._tags.get(west_group_arn) is None
-
-
-def test_scheduler_ticker_dispatches_in_schedule_region_and_restores_context(monkeypatch):
- from ministack.services import eventbridge
-
- account_id = "000000000000"
- name = f"ticker-{_uid()}"
- key = f"default/{name}"
- expected = {}
- for region in ("us-east-1", "us-west-2"):
- schedule_arn = f"arn:aws:scheduler:{region}:{account_id}:schedule/{key}"
- target_arn = f"arn:aws:lambda:{region}:{account_id}:function:ticker-target"
- expected[region] = (schedule_arn, target_arn)
- scheduler._schedules.set_scoped(
- account_id,
- region,
- key,
- {
- "Arn": schedule_arn,
- "Name": name,
- "GroupName": "default",
- "ScheduleExpression": "at(1970-01-01T00:00:01)",
- "Target": {"Arn": target_arn},
- "State": "ENABLED",
- "ActionAfterCompletion": "NONE",
- "CreationDate": 1,
- },
- )
- set_request_account_id("111111111111")
- set_request_region("eu-west-1")
-
- calls = []
-
- def _capture_target(target, event, schedule):
- calls.append((get_account_id(), get_region(), target, event, schedule))
-
- monkeypatch.setattr(eventbridge, "_invoke_target", _capture_target)
- monkeypatch.setattr(scheduler.time, "time", lambda: 2.0)
-
- scheduler._tick_schedules()
-
- assert len(calls) == 2
- calls_by_region = {call[1]: call for call in calls}
- assert set(calls_by_region) == set(expected)
- for region, (schedule_arn, target_arn) in expected.items():
- dispatch_account, dispatch_region, target, event, schedule = calls_by_region[region]
- assert (dispatch_account, dispatch_region) == (account_id, region)
- assert target["Arn"] == target_arn
- assert event["Account"] == account_id
- assert event["Region"] == region
- assert event["Resources"] == [schedule_arn]
- assert schedule["Arn"] == schedule_arn
- assert (get_account_id(), get_region()) == ("111111111111", "eu-west-1")
-
-
-def test_scheduler_start_scheduler_starts_daemon_once(monkeypatch):
- created_threads = []
-
- class _FakeThread:
- def __init__(self, *, target, daemon, name):
- self.target = target
- self.daemon = daemon
- self.name = name
- self.started = False
- created_threads.append(self)
-
- def start(self):
- self.started = True
-
- def is_alive(self):
- return self.started
-
- monkeypatch.setattr(scheduler.threading, "Thread", _FakeThread)
-
- scheduler.start_scheduler()
- scheduler.start_scheduler()
-
- assert len(created_threads) == 1
- thread = created_threads[0]
- assert thread.target is scheduler._ticker_loop
- assert thread.daemon is True
- assert thread.name == "evb-scheduler-ticker"
- assert thread.started is True
-
-
-def test_scheduler_unknown_route_returns_validation_error():
- response = _request("GET", "/unknown")
-
- _assert_error(response, 400, "ValidationException")
-
-
- "bad_arn, expected_status, expected_code",
- [
- ("not-an-arn", 400, "ValidationException"),
- (
- "arn:aws-us-gov:scheduler:us-east-1:000000000000:schedule/default/{name}",
- 404,
- "ResourceNotFoundException",
- ),
- (
- "arn:aws:events:us-east-1:000000000000:schedule/default/{name}",
- 404,
- "ResourceNotFoundException",
- ),
- (
- "arn:aws:scheduler:us-east-1:111111111111:schedule/default/{name}",
- 404,
- "ResourceNotFoundException",
- ),
- (
- "arn:aws:scheduler:us-west-2:000000000000:schedule/default/{name}",
- 404,
- "ResourceNotFoundException",
- ),
- (
- "arn:aws:scheduler:us-east-1:000000000000:schedule/default",
- 404,
- "ResourceNotFoundException",
- ),
- (
- "arn:aws:scheduler:us-east-1:000000000000:schedule/default/{name}/extra",
- 404,
- "ResourceNotFoundException",
- ),
- (
- "arn:aws:scheduler:us-east-1:000000000000:rule/default/{name}",
- 404,
- "ResourceNotFoundException",
- ),
- (
- "arn:aws:scheduler:us-east-1:000000000000:schedule/default/missing-{name}",
- 404,
- "ResourceNotFoundException",
- ),
- (
- "arn:aws:scheduler:us-east-1:000000000000:schedule-group/missing-{name}",
- 404,
- "ResourceNotFoundException",
- ),
- ],
-)
[email protected]("method", ["GET", "POST", "DELETE"])
-def test_scheduler_tag_apis_reject_invalid_resource_arns_before_touching_tags(
- method, bad_arn, expected_status, expected_code
-):
- name, good_arn = _create_schedule()
- _request("POST", f"/tags/{good_arn}", {"Tags": [{"Key": "env", "Value": "good"}]})
- baseline = dict(scheduler._tags.get(good_arn, {}))
- arn = bad_arn.format(name=name)
-
- body = {"Tags": [{"Key": "env", "Value": "bad"}]} if method == "POST" else None
- query = {"TagKeys": ["env"]} if method == "DELETE" else None
- resp = _request(method, f"/tags/{arn}", body=body, query=query)
-
- _assert_error(resp, expected_status, expected_code)
- assert scheduler._tags.get(good_arn, {}) == baseline
- assert scheduler._tags.get(arn) is None