Skip to content

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

Add Resource Groups Tagging API with GetResources support - Phase1 (#372)

Akhil adiga1eb01daa6513
diff --git a/ministack/app.py b/ministack/app.py
index 99be428c..52bc2947 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -162,6 +162,7 @@ SERVICE_HANDLERS = {
"appconfigdata": _lazy_handler("appconfig"),
"scheduler": _lazy_handler("scheduler"),
"eks": _lazy_handler("eks"),
+ "tagging": _lazy_handler("tagging"),
}
SERVICE_NAME_ALIASES = {
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 4db6e59f..b25b9abc 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -214,6 +214,11 @@ SERVICE_PATTERNS = {
"host_patterns": [r"eks\."],
"credential_scope": "eks",
},
+ "tagging": {
+ "target_prefixes": ["ResourceGroupsTaggingAPI_20170126"],
+ "host_patterns": [r"tagging\."],
+ "credential_scope": "tagging",
+ },
}
@@ -276,6 +281,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
"appconfigdata": "appconfigdata",
"scheduler": "scheduler",
"eks": "eks",
+ "tagging": "tagging",
}
if svc_name in scope_map:
return scope_map[svc_name]
diff --git a/ministack/services/tagging.py b/ministack/services/tagging.py
new file mode 100644
index 00000000..7cb208c2
--- /dev/null
+++ b/ministack/services/tagging.py
@@ -0,0 +1,168 @@
+"""
+Resource Groups Tagging API emulator.
+Phase 1: GetResources across S3, Lambda, SQS, SNS, DynamoDB, EventBridge.
+"""
+
+import json
+import logging
+import os
+
+logger = logging.getLogger("tagging")
+REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+
+
+# ── Tag format normalisation ──────────────────────────────────────────────────
+
+def _normalise_flat(tag_dict):
+ """Convert {k: v} flat dict to [{"Key": k, "Value": v}] list."""
+ return [{"Key": k, "Value": v} for k, v in (tag_dict or {}).items()]
+
+
+def _normalise_list(tag_list):
+ """Pass-through [{"Key": k, "Value": v}] list (DynamoDB format)."""
+ return tag_list or []
+
+
+# ── Per-service tag collectors ────────────────────────────────────────────────
+
+def _collect_s3():
+ import ministack.services.s3 as svc
+ for name, tags in svc._bucket_tags.items():
+ yield f"arn:aws:s3:::{name}", _normalise_flat(tags)
+
+
+def _collect_lambda():
+ import ministack.services.lambda_svc as svc
+ for name, fn in svc._functions.items():
+ arn = f"arn:aws:lambda:{REGION}:{_account()}:function:{name}"
+ yield arn, _normalise_flat(fn.get("tags", {}))
+
+
+def _collect_sqs():
+ import ministack.services.sqs as svc
+ for url, q in svc._queues.items():
+ arn = q.get("attributes", {}).get("QueueArn", "")
+ if arn:
+ yield arn, _normalise_flat(q.get("tags", {}))
+
+
+def _collect_sns():
+ import ministack.services.sns as svc
+ for arn, topic in svc._topics.items():
+ yield arn, _normalise_flat(topic.get("tags", {}))
+
+
+def _collect_dynamodb():
+ import ministack.services.dynamodb as svc
+ for arn, tags in svc._tags.items():
+ yield arn, _normalise_list(tags)
+
+
+def _collect_eventbridge():
+ import ministack.services.eventbridge as svc
+ for arn, tags in svc._tags.items():
+ yield arn, _normalise_flat(tags)
+
+
+# ResourceTypeFilter prefix -> collector
+_COLLECTORS = {
+ "s3": _collect_s3,
+ "lambda": _collect_lambda,
+ "sqs": _collect_sqs,
+ "sns": _collect_sns,
+ "dynamodb": _collect_dynamodb,
+ "events": _collect_eventbridge,
+}
+
+
+# ── Helpers ───────────────────────────────────────────────────────────────────
+
+def _account():
+ from ministack.core.responses import get_account_id
+ return get_account_id()
+
+
+def _matches_type_filters(arn, type_filters):
+ if not type_filters:
+ return True
+ for tf in type_filters:
+ svc_prefix = tf.split(":")[0]
+ if f"::{svc_prefix}:" in arn or f":{svc_prefix}:" in arn:
+ return True
+ return False
+
+
+def _matches_tag_filters(tags, tag_filters):
+ """AND across filter keys, OR across values within a key."""
+ if not tag_filters:
+ return True
+ tag_map = {t["Key"]: t["Value"] for t in tags}
+ for f in tag_filters:
+ key = f.get("Key", "")
+ values = f.get("Values", [])
+ if key not in tag_map:
+ return False
+ if values and tag_map[key] not in values:
+ return False
+ return True
+
+
+# ── Operation handlers ────────────────────────────────────────────────────────
+
+def _get_resources(data):
+ tag_filters = data.get("TagFilters", [])
+ type_filters = data.get("ResourceTypeFilters", [])
+
+ if type_filters:
+ type_prefixes = {tf.split(":")[0] for tf in type_filters}
+ active = {k: v for k, v in _COLLECTORS.items() if k in type_prefixes}
+ if not active:
+ active = _COLLECTORS
+ else:
+ active = _COLLECTORS
+
+ results = []
+ for collector in active.values():
+ try:
+ for arn, tags in collector():
+ if not _matches_type_filters(arn, type_filters):
+ continue
+ if not _matches_tag_filters(tags, tag_filters):
+ continue
+ results.append({"ResourceARN": arn, "Tags": tags})
+ except Exception:
+ pass # service not yet initialised — skip silently
+
+ return 200, {"Content-Type": "application/x-amz-json-1.1"}, json.dumps({
+ "ResourceTagMappingList": results,
+ "PaginationToken": "",
+ }).encode()
+
+
+# ── Entry point ───────────────────────────────────────────────────────────────
+
+_HANDLERS = {
+ "GetResources": _get_resources,
+}
+
+
+async def handle_request(method, path, headers, body, query_params):
+ target = headers.get("x-amz-target", "")
+ action = target.split(".")[-1] if "." in target else ""
+
+ try:
+ data = json.loads(body) if body else {}
+ except json.JSONDecodeError:
+ return 400, {"Content-Type": "application/x-amz-json-1.1"}, json.dumps({
+ "__type": "SerializationException",
+ "message": "Invalid JSON",
+ }).encode()
+
+ handler = _HANDLERS.get(action)
+ if not handler:
+ return 400, {"Content-Type": "application/x-amz-json-1.1"}, json.dumps({
+ "__type": "InvalidRequestException",
+ "message": f"Unknown action: {action}",
+ }).encode()
+
+ return handler(data)
diff --git a/tests/conftest.py b/tests/conftest.py
index 6bb8dbd6..46c6e5d5 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -299,3 +299,7 @@ def transfer():
@pytest.fixture(scope="session")
def eks():
return make_client("eks")
+
[email protected](scope="session")
+def tagging():
+ return make_client("resourcegroupstaggingapi")
diff --git a/tests/test_tagging.py b/tests/test_tagging.py
new file mode 100644
index 00000000..e6f25b5e
--- /dev/null
+++ b/tests/test_tagging.py
@@ -0,0 +1,171 @@
+import pytest
+from botocore.exceptions import ClientError
+
+# ========== Resource Groups Tagging API ==========
+
+# Unique tag key scopes all resources to this test file — avoids collisions with other tests
+_TAG_KEY = "tagging-test"
+
+
+# ========== S3 ==========
+
+def test_tagging_get_resources_s3_basic(tagging, s3):
+ s3.create_bucket(Bucket="tg-s3-basic")
+ s3.put_bucket_tagging(Bucket="tg-s3-basic", Tagging={
+ "TagSet": [{"Key": _TAG_KEY, "Value": "s3-basic"}]
+ })
+
+ resp = tagging.get_resources(TagFilters=[{"Key": _TAG_KEY, "Values": ["s3-basic"]}])
+ arns = [r["ResourceARN"] for r in resp["ResourceTagMappingList"]]
+ assert "arn:aws:s3:::tg-s3-basic" in arns
+
+
+def test_tagging_get_resources_s3_tags_returned(tagging, s3):
+ s3.create_bucket(Bucket="tg-s3-tags")
+ s3.put_bucket_tagging(Bucket="tg-s3-tags", Tagging={
+ "TagSet": [{"Key": _TAG_KEY, "Value": "s3-tags"}, {"Key": "team", "Value": "platform"}]
+ })
+
+ resp = tagging.get_resources(TagFilters=[{"Key": _TAG_KEY, "Values": ["s3-tags"]}])
+ matched = [r for r in resp["ResourceTagMappingList"] if r["ResourceARN"] == "arn:aws:s3:::tg-s3-tags"]
+ assert len(matched) == 1
+ tag_map = {t["Key"]: t["Value"] for t in matched[0]["Tags"]}
+ assert tag_map[_TAG_KEY] == "s3-tags"
+ assert tag_map["team"] == "platform"
+
+
+# ========== SQS ==========
+
+def test_tagging_get_resources_sqs(tagging, sqs):
+ url = sqs.create_queue(QueueName="tg-sqs-basic")["QueueUrl"]
+ sqs.tag_queue(QueueUrl=url, Tags={_TAG_KEY: "sqs-basic"})
+
+ resp = tagging.get_resources(TagFilters=[{"Key": _TAG_KEY, "Values": ["sqs-basic"]}])
+ arns = [r["ResourceARN"] for r in resp["ResourceTagMappingList"]]
+ assert any("tg-sqs-basic" in a for a in arns)
+
+
+# ========== SNS ==========
+
+def test_tagging_get_resources_sns(tagging, sns):
+ topic_arn = sns.create_topic(Name="tg-sns-basic")["TopicArn"]
+ sns.tag_resource(ResourceArn=topic_arn, Tags=[{"Key": _TAG_KEY, "Value": "sns-basic"}])
+
+ resp = tagging.get_resources(TagFilters=[{"Key": _TAG_KEY, "Values": ["sns-basic"]}])
+ arns = [r["ResourceARN"] for r in resp["ResourceTagMappingList"]]
+ assert topic_arn in arns
+
+
+# ========== DynamoDB ==========
+
+def test_tagging_get_resources_dynamodb(tagging, ddb):
+ ddb.create_table(
+ TableName="tg-ddb-basic",
+ AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
+ KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ table_arn = ddb.describe_table(TableName="tg-ddb-basic")["Table"]["TableArn"]
+ ddb.tag_resource(ResourceArn=table_arn, Tags=[{"Key": _TAG_KEY, "Value": "ddb-basic"}])
+
+ resp = tagging.get_resources(TagFilters=[{"Key": _TAG_KEY, "Values": ["ddb-basic"]}])
+ arns = [r["ResourceARN"] for r in resp["ResourceTagMappingList"]]
+ assert table_arn in arns
+
+
+# ========== Cross-service fan-out ==========
+
+def test_tagging_get_resources_cross_service(tagging, s3, sqs):
+ s3.create_bucket(Bucket="tg-cross-s3")
+ s3.put_bucket_tagging(Bucket="tg-cross-s3", Tagging={
+ "TagSet": [{"Key": _TAG_KEY, "Value": "cross-svc"}]
+ })
+ url = sqs.create_queue(QueueName="tg-cross-sqs")["QueueUrl"]
+ sqs.tag_queue(QueueUrl=url, Tags={_TAG_KEY: "cross-svc"})
+
+ resp = tagging.get_resources(TagFilters=[{"Key": _TAG_KEY, "Values": ["cross-svc"]}])
+ arns = [r["ResourceARN"] for r in resp["ResourceTagMappingList"]]
+ assert "arn:aws:s3:::tg-cross-s3" in arns
+ assert any("tg-cross-sqs" in a for a in arns)
+
+
+# ========== Tag filter semantics ==========
+
+def test_tagging_get_resources_tag_filter_or_values(tagging, s3):
+ """Values list within a TagFilter uses OR — either value matches."""
+ s3.create_bucket(Bucket="tg-or-prod")
+ s3.put_bucket_tagging(Bucket="tg-or-prod", Tagging={
+ "TagSet": [{"Key": _TAG_KEY, "Value": "or-prod"}]
+ })
+ s3.create_bucket(Bucket="tg-or-staging")
+ s3.put_bucket_tagging(Bucket="tg-or-staging", Tagging={
+ "TagSet": [{"Key": _TAG_KEY, "Value": "or-staging"}]
+ })
+ s3.create_bucket(Bucket="tg-or-other")
+ s3.put_bucket_tagging(Bucket="tg-or-other", Tagging={
+ "TagSet": [{"Key": _TAG_KEY, "Value": "or-other"}]
+ })
+
+ resp = tagging.get_resources(
+ TagFilters=[{"Key": _TAG_KEY, "Values": ["or-prod", "or-staging"]}]
+ )
+ arns = [r["ResourceARN"] for r in resp["ResourceTagMappingList"]]
+ assert "arn:aws:s3:::tg-or-prod" in arns
+ assert "arn:aws:s3:::tg-or-staging" in arns
+ assert "arn:aws:s3:::tg-or-other" not in arns
+
+
+def test_tagging_get_resources_tag_filter_and_keys(tagging, s3):
+ """Multiple TagFilters use AND — resource must match all keys."""
+ s3.create_bucket(Bucket="tg-and-both")
+ s3.put_bucket_tagging(Bucket="tg-and-both", Tagging={
+ "TagSet": [
+ {"Key": _TAG_KEY, "Value": "and-match"},
+ {"Key": "and-extra-key", "Value": "and-extra-val"},
+ ]
+ })
+ s3.create_bucket(Bucket="tg-and-one")
+ s3.put_bucket_tagging(Bucket="tg-and-one", Tagging={
+ "TagSet": [{"Key": _TAG_KEY, "Value": "and-match"}]
+ })
+
+ resp = tagging.get_resources(TagFilters=[
+ {"Key": _TAG_KEY, "Values": ["and-match"]},
+ {"Key": "and-extra-key", "Values": ["and-extra-val"]},
+ ])
+ arns = [r["ResourceARN"] for r in resp["ResourceTagMappingList"]]
+ assert "arn:aws:s3:::tg-and-both" in arns
+ assert "arn:aws:s3:::tg-and-one" not in arns
+
+
+# ========== ResourceTypeFilters ==========
+
+def test_tagging_get_resources_resource_type_filter_s3_only(tagging, s3, sqs):
+ s3.create_bucket(Bucket="tg-type-s3")
+ s3.put_bucket_tagging(Bucket="tg-type-s3", Tagging={
+ "TagSet": [{"Key": _TAG_KEY, "Value": "type-filter"}]
+ })
+ url = sqs.create_queue(QueueName="tg-type-sqs")["QueueUrl"]
+ sqs.tag_queue(QueueUrl=url, Tags={_TAG_KEY: "type-filter"})
+
+ resp = tagging.get_resources(
+ TagFilters=[{"Key": _TAG_KEY, "Values": ["type-filter"]}],
+ ResourceTypeFilters=["s3"],
+ )
+ arns = [r["ResourceARN"] for r in resp["ResourceTagMappingList"]]
+ assert "arn:aws:s3:::tg-type-s3" in arns
+ assert not any("tg-type-sqs" in a for a in arns)
+
+
+# ========== Edge cases ==========
+
+def test_tagging_get_resources_no_match(tagging):
+ resp = tagging.get_resources(
+ TagFilters=[{"Key": _TAG_KEY, "Values": ["__nonexistent__"]}]
+ )
+ assert resp["ResourceTagMappingList"] == []
+
+
+def test_tagging_get_resources_pagination_token_empty(tagging):
+ resp = tagging.get_resources()
+ assert resp.get("PaginationToken", "") == ""