Skip to content

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

feat(iam): no SigV4-Full IAM enforcment with auth=true (#1471)

Nahuel Nucerac38485c13037
diff --git a/ministack/app.py b/ministack/app.py
index 29ec527d..dad6f0ce 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -25,6 +25,7 @@ from urllib.parse import parse_qs, unquote
_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
_MINISTACK_PORT = os.environ.get("GATEWAY_PORT", "4566")
+AUTH = os.environ.get("AUTH", "false").lower() == "true"
_VERSION = os.environ.get("MINISTACK_VERSION") or "dev"
if _VERSION == "dev":
@@ -1380,6 +1381,12 @@ async def _handle_execute_api_request(
if parsed is None:
return None
api_id, tentative_stage, execute_path = parsed
+
+ denied = _enforce_data_plane("apigateway", "execute-api:Invoke",
+ headers, query_params, "")
+ if denied:
+ return denied
+
try:
# WebSocket @connections management API — /{stage}/@connections/{id}.
# The @connections prefix is authoritative; skip $default resolution.
@@ -1446,6 +1453,12 @@ async def _handle_lambda_url_request(
if parsed is None:
return None
url_id, function_path = parsed
+
+ denied = _enforce_data_plane("lambda", "lambda:InvokeFunctionUrl",
+ headers, query_params, "")
+ if denied:
+ return denied
+
try:
return await _get_module("lambda_svc").handle_function_url_request(
url_id, method, function_path, headers, body, query_params
@@ -1517,6 +1530,20 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: d
return None
vhost_path = "/" + bucket + path if path != "/" else "/" + bucket + "/"
+
+ # IAM enforcement for S3 virtual-hosted requests
+ if AUTH:
+ from ministack.core.iam_actions import _s3_action, extract_resource_arn
+ s3_action = _s3_action(method, vhost_path, query_params)
+ if s3_action:
+ s3_resource = extract_resource_arn(
+ "s3", method, vhost_path, headers, body, query_params, "", "")
+ denied = _enforce_data_plane("s3", f"s3:{s3_action}", headers,
+ query_params, "",
+ resource_arn=s3_resource)
+ if denied:
+ return denied
+
try:
# Pass the original (pre-rewrite) URI as signed_path so a presigned
# virtual-hosted URL, which signed the canonical URI without the bucket,
@@ -1554,6 +1581,28 @@ def _with_data_plane_headers(response, request_id: str, include_s3_id: bool = Fa
return status, headers, body
+def _enforce_data_plane(service: str, iam_action: str, headers: dict,
+ query_params: dict, request_id: str,
+ resource_arn: str = "*"):
+ """Enforce IAM auth on a data-plane path. Returns error tuple or None."""
+ if not AUTH:
+ return None
+ from ministack.core.iam_actions import access_denied_response
+ from ministack.core.iam_evaluator import AuthError, enforce
+ access_key = extract_access_key_id(headers, query_params)
+ denied = enforce(access_key, iam_action, service,
+ extract_region(headers, query_params),
+ resource_arn=resource_arn)
+ if denied:
+ if isinstance(denied, AuthError):
+ return access_denied_response(
+ service, iam_action, "", request_id,
+ error_code=denied.code, message=denied.message)
+ return access_denied_response(
+ service, iam_action, denied.principal_arn, request_id)
+ return None
+
+
async def _handle_special_data_plane_request(
method: str,
path: str,
@@ -1829,6 +1878,31 @@ async def _dispatch_service_request(
if service == "unknown_query":
return _unknown_query_error(body, request_id)
+ if AUTH:
+ from ministack.core.iam_actions import (
+ access_denied_response,
+ extract_iam_action,
+ extract_resource_arn,
+ )
+ from ministack.core.iam_evaluator import AuthError, enforce
+ from ministack.core.responses import get_account_id
+ iam_action = extract_iam_action(
+ service, method, path, headers, body, routing_params)
+ if iam_action is not None:
+ access_key = extract_access_key_id(headers, query_params)
+ resource_arn = extract_resource_arn(
+ service, method, path, headers, body,
+ routing_params, region, get_account_id())
+ denied = enforce(access_key, iam_action, service, region,
+ resource_arn=resource_arn)
+ if denied:
+ if isinstance(denied, AuthError):
+ return access_denied_response(
+ service, iam_action, "", request_id,
+ error_code=denied.code, message=denied.message)
+ return access_denied_response(
+ service, iam_action, denied.principal_arn, request_id)
+
handler = SERVICE_HANDLERS.get(service)
if not handler:
return (
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
new file mode 100644
index 00000000..58d7ed15
--- /dev/null
+++ b/ministack/core/iam_actions.py
@@ -0,0 +1,1280 @@
+"""IAM action extraction and AccessDenied response formatting.
+
+Maps MiniStack's internal service names to IAM namespaces, extracts the
+IAM action string (``service:ActionName``) from each request's protocol,
+and formats per-protocol AccessDenied error responses.
+"""
+
+import json
+import logging
+import os
+import re
+
+logger = logging.getLogger("ministack")
+
+# ---------------------------------------------------------------------------
+# Service name → IAM namespace mapping
+# ---------------------------------------------------------------------------
+# Keys are the service names returned by router.detect_service().
+# Values are the IAM authorization namespace (botocore signingName).
+
+SERVICE_TO_IAM_NAMESPACE: dict[str, str] = {
+ "account": "account",
+ "acm": "acm",
+ "airflow": "airflow",
+ "apigateway": "apigateway",
+ "appconfig": "appconfig",
+ "appconfigdata": "appconfig",
+ "appsync": "appsync",
+ "appsync-events": "appsync",
+ "athena": "athena",
+ "autoscaling": "autoscaling",
+ "backup": "backup",
+ "batch": "batch",
+ "bedrock": "bedrock",
+ "bedrock-agent": "bedrock",
+ "bedrock-agent-runtime": "bedrock",
+ "bedrock-agentcore": "bedrock",
+ "bedrock-runtime": "bedrock",
+ "cloudcontrol": "cloudformation",
+ "cloudformation": "cloudformation",
+ "cloudfront": "cloudfront",
+ "cloudfront-keyvaluestore": "cloudfront-keyvaluestore",
+ "cloudtrail": "cloudtrail",
+ "codebuild": "codebuild",
+ "cognito-identity": "cognito-identity",
+ "cognito-idp": "cognito-idp",
+ "config": "config",
+ "cur": "cur",
+ "dsql": "dsql",
+ "dynamodb": "dynamodb",
+ "dynamodbstreams": "dynamodb",
+ "ec2": "ec2",
+ "ecr": "ecr",
+ "ecs": "ecs",
+ "ecs-metadata": "ecs",
+ "eks": "eks",
+ "elasticache": "elasticache",
+ "elasticfilesystem": "elasticfilesystem",
+ "elasticloadbalancing": "elasticloadbalancing",
+ "elasticmapreduce": "elasticmapreduce",
+ "events": "events",
+ "firehose": "firehose",
+ "glue": "glue",
+ "iam": "iam",
+ "imds": "ec2",
+ "inspector2": "inspector2",
+ "iot": "iot",
+ "iot-data": "iot",
+ "iot-jobs-data": "iot",
+ "kafka": "kafka",
+ "kinesis": "kinesis",
+ "kms": "kms",
+ "lambda": "lambda",
+ "lambda-microvms": "lambda",
+ "logs": "logs",
+ "mediaconnect": "mediaconnect",
+ "monitoring": "cloudwatch",
+ "mq": "mq",
+ "opensearch": "es",
+ "organizations": "organizations",
+ "pipes": "pipes",
+ "rds": "rds",
+ "rds-data": "rds-data",
+ "resource-groups": "resource-groups",
+ "route53": "route53",
+ "s3": "s3",
+ "s3files": "s3",
+ "s3tables": "s3tables",
+ "scheduler": "scheduler",
+ "secretsmanager": "secretsmanager",
+ "servicediscovery": "servicediscovery",
+ "ses": "ses",
+ "sns": "sns",
+ "sqs": "sqs",
+ "ssm": "ssm",
+ "states": "states",
+ "sts": "sts",
+ "tagging": "tag",
+ "transfer": "transfer",
+ "waf": "waf",
+ "waf-regional": "waf-regional",
+ "wafv2": "wafv2",
+}
+
+
+# ---------------------------------------------------------------------------
+# Action extraction
+# ---------------------------------------------------------------------------
+
+def _action_from_query(query_params: dict, body: bytes,
+ content_type: str) -> str | None:
+ """Extract Action from query params or form-encoded body."""
+ action = query_params.get("Action")
+ if isinstance(action, list):
+ action = action[0] if action else None
+ if action:
+ return action
+ if body and "x-www-form-urlencoded" in (content_type or ""):
+ from urllib.parse import parse_qs
+ bp = parse_qs(body.decode("utf-8", "replace"), keep_blank_values=True)
+ action = bp.get("Action", [None])[0]
+ if action:
+ return action
+ return None
+
+
+def _action_from_target(headers: dict) -> str | None:
+ """Extract action from X-Amz-Target header (JSON protocol services)."""
+ target = headers.get("x-amz-target", "")
+ if "." in target:
+ return target.rsplit(".", 1)[-1]
+ return None
+
+
+# S3 REST path → IAM action
+_S3_ACTIONS: dict[tuple[str, int], str] = {
+ ("GET", 0): "ListAllMyBuckets",
+ ("PUT", 1): "CreateBucket",
+ ("DELETE", 1): "DeleteBucket",
+ ("HEAD", 1): "ListBucket",
+ ("GET", 1): "ListBucket",
+ ("PUT", 2): "PutObject",
+ ("GET", 2): "GetObject",
+ ("DELETE", 2): "DeleteObject",
+ ("HEAD", 2): "GetObject",
+ ("POST", 2): "PutObject",
+ ("POST", 1): "DeleteObject", # DeleteObjects (batch)
+}
+
+# S3 query-param sub-operations
+_S3_QUERY_ACTIONS: dict[str, dict[str, str]] = {
+ "tagging": {"GET": "GetBucketTagging", "PUT": "PutBucketTagging", "DELETE": "DeleteBucketTagging"},
+ "versioning": {"GET": "GetBucketVersioning", "PUT": "PutBucketVersioning"},
+ "policy": {"GET": "GetBucketPolicy", "PUT": "PutBucketPolicy", "DELETE": "DeleteBucketPolicy"},
+ "cors": {"GET": "GetBucketCors", "PUT": "PutBucketCors", "DELETE": "DeleteBucketCors"},
+ "lifecycle": {"GET": "GetLifecycleConfiguration", "PUT": "PutLifecycleConfiguration",
+ "DELETE": "DeleteLifecycleConfiguration"},
+ "encryption": {"GET": "GetEncryptionConfiguration", "PUT": "PutEncryptionConfiguration",
+ "DELETE": "DeleteEncryptionConfiguration"},
+ "notification": {"GET": "GetBucketNotification", "PUT": "PutBucketNotification"},
+ "acl": {"GET": "GetBucketAcl", "PUT": "PutBucketAcl"},
+ "website": {"GET": "GetBucketWebsite", "PUT": "PutBucketWebsite", "DELETE": "DeleteBucketWebsite"},
+ "logging": {"GET": "GetBucketLogging", "PUT": "PutBucketLogging"},
+ "replication": {"GET": "GetReplicationConfiguration", "PUT": "PutReplicationConfiguration",
+ "DELETE": "DeleteReplicationConfiguration"},
+ "location": {"GET": "GetBucketLocation"},
+ "uploads": {"GET": "ListMultipartUploads", "POST": "CreateMultipartUpload"},
+}
+
+
+def _s3_action(method: str, path: str, query_params: dict) -> str | None:
+ parts = [p for p in path.split("/") if p]
+ depth = min(len(parts), 2)
+
+ # Check sub-operation query params first (bucket-level)
+ if depth >= 1:
+ for qp, action_map in _S3_QUERY_ACTIONS.items():
+ if qp in query_params:
+ a = action_map.get(method)
+ if a:
+ return a
+
+ return _S3_ACTIONS.get((method, depth))
+
+
+# Lambda REST path → IAM action
+def _lambda_action(method: str, path: str) -> str | None:
+ parts = [p for p in path.split("/") if p]
+ if "functions" not in parts:
+ if "layers" in parts:
+ if method == "GET":
+ return "ListLayers"
+ if method == "POST":
+ return "PublishLayerVersion"
+ if "event-source-mappings" in parts:
+ if method == "GET":
+ return "ListEventSourceMappings"
+ if method == "POST":
+ return "CreateEventSourceMapping"
+ return None
+
+ fi = parts.index("functions")
+ rest = parts[fi + 1:]
+ if not rest:
+ return "CreateFunction" if method == "POST" else "ListFunctions"
+
+ sub = rest[1] if len(rest) > 1 else None
+ sub_map = {
+ "invocations": "InvokeFunction",
+ "code": "UpdateFunctionCode" if method == "PUT" else "GetFunction",
+ "configuration": ("UpdateFunctionConfiguration" if method == "PUT"
+ else "GetFunctionConfiguration"),
+ "aliases": "CreateAlias" if method == "POST" else "ListAliases",
+ "versions": "PublishVersion" if method == "POST" else "ListVersionsByFunction",
+ "policy": ("AddPermission" if method == "POST"
+ else "RemovePermission" if method == "DELETE"
+ else "GetPolicy"),
+ "event-source-mappings": "ListEventSourceMappings",
+ "concurrency": "PutFunctionConcurrency",
+ "code-signing-config": "GetFunctionCodeSigningConfig",
+ "url": "GetFunctionUrlConfig" if method == "GET" else "CreateFunctionUrlConfig",
+ "tags": "TagResource" if method == "POST" else "UntagResource" if method == "DELETE" else "ListTags",
+ }
+ if sub in sub_map:
+ return sub_map[sub]
+
+ return {
+ "GET": "GetFunction",
+ "DELETE": "DeleteFunction",
+ "PUT": "UpdateFunctionCode",
+ }.get(method)
+
+
+# ---------------------------------------------------------------------------
+# Generic botocore route matcher
+# ---------------------------------------------------------------------------
+
+# MiniStack service name → botocore data directory name(s)
+_BOTOCORE_SERVICE_MAP: dict[str, list[str]] = {
+ "apigateway": ["apigateway", "apigatewayv2"],
+ "appconfig": ["appconfig"],
+ "appconfigdata": ["appconfigdata"],
+ "appsync": ["appsync"],
+ "appsync-events": ["appsync"],
+ "backup": ["backup"],
+ "batch": ["batch"],
+ "bedrock": ["bedrock"],
+ "bedrock-runtime": ["bedrock-runtime"],
+ "bedrock-agent": ["bedrock-agent"],
+ "bedrock-agent-runtime": ["bedrock-agent-runtime"],
+ "bedrock-agentcore": [], # no botocore model yet
+ "cloudfront": ["cloudfront"],
+ "cloudfront-keyvaluestore": ["cloudfront-keyvaluestore"],
+ "dsql": ["dsql"],
+ "eks": ["eks"],
+ "elasticfilesystem": ["efs"],
+ "inspector2": ["inspector2"],
+ "iot": ["iot"],
+ "iot-data": ["iot-data"],
+ "iot-jobs-data": ["iot-jobs-data"],
+ "kafka": ["kafka"],
+ "mediaconnect": ["mediaconnect"],
+ "mq": ["mq"],
+ "airflow": ["mwaa"],
+ "opensearch": ["opensearch"],
+ "pipes": ["pipes"],
+ "resource-groups": ["resource-groups"],
+ "route53": ["route53"],
+ "s3files": [], # uses S3 namespace but different paths
+ "s3tables": ["s3tables"],
+ "scheduler": ["scheduler"],
+}
+
+# Compiled route: (http_method, compiled_regex, operation_name, specificity)
+# Compiled route: (http_method, compiled_regex, operation_name, specificity, required_query)
+_REST_ROUTE_CACHE: dict[str, list[tuple[str, re.Pattern, str, int, dict[str, str]]]] = {}
+
+
+def _compile_uri(uri_pattern: str) -> tuple[re.Pattern, int, dict[str, str]]:
+ """Compile a botocore URI pattern into a regex + specificity score +
+ required query params.
+
+ ``/clusters/{name}/addons/{addonName}`` becomes
+ ``^/clusters/[^/]+/addons/[^/]+(?:/)?$`` with specificity 2
+ (2 literal segments).
+
+ Query params from the pattern (e.g., ``?mode=import``) are returned
+ separately for disambiguation.
+ """
+ required_query: dict[str, str] = {}
+ if "?" in uri_pattern:
+ uri_path, qs = uri_pattern.split("?", 1)
+ for part in qs.split("&"):
+ if "=" in part:
+ k, v = part.split("=", 1)
+ if not v.startswith("{"):
+ required_query[k] = v
+ else:
+ required_query[part] = ""
+ else:
+ uri_path = uri_pattern
+
+ uri_path = uri_path.rstrip("/") or "/"
+
+ specificity = 0
+ segments = uri_path.split("/")
+ regex_parts = []
+ for seg in segments:
+ if not seg:
+ regex_parts.append("")
+ continue
+ if seg.startswith("{") and seg.endswith("+}"):
+ regex_parts.append(".+")
+ elif seg.startswith("{") and seg.endswith("}"):
+ regex_parts.append("[^/]+")
+ else:
+ regex_parts.append(re.escape(seg))
+ specificity += 1
+
+ pattern = "/".join(regex_parts) or "/"
+ compiled = re.compile(f"^{pattern}(?:/)?$", re.IGNORECASE)
+ return compiled, specificity, required_query
+
+
+def _load_botocore_routes(botocore_service: str) -> list[tuple[str, re.Pattern, str, int, dict[str, str]]]:
+ """Load a botocore service model and compile its URI routes."""
+ try:
+ import gzip
+
+ import botocore as _bc
+ data_dir = os.path.join(os.path.dirname(_bc.__file__), "data")
+ except ImportError:
+ logger.debug("AUTH: botocore not installed — no generic route matching")
+ return []
+
+ svc_dir = os.path.join(data_dir, botocore_service)
+ if not os.path.isdir(svc_dir):
+ return []
+
+ versions = sorted(os.listdir(svc_dir))
+ if not versions:
+ return []
+
+ model_path = os.path.join(svc_dir, versions[-1], "service-2.json.gz")
+ if not os.path.exists(model_path):
+ model_path = os.path.join(svc_dir, versions[-1], "service-2.json")
+ if not os.path.exists(model_path):
+ return []
+
+ try:
+ if model_path.endswith(".gz"):
+ import gzip
+ with gzip.open(model_path, "rt") as f:
+ model = json.load(f)
+ else:
+ with open(model_path) as f:
+ model = json.load(f)
+ except Exception:
+ logger.debug("AUTH: failed to load botocore model for %s", botocore_service)
+ return []
+
+ routes = []
+ for op_name, op_def in model.get("operations", {}).items():
+ http = op_def.get("http", {})
+ method = http.get("method", "").upper()
+ uri = http.get("requestUri", "")
+ if not method or not uri:
+ continue
+ compiled, specificity, required_query = _compile_uri(uri)
+ # Operations with required query params get a specificity boost
+ if required_query:
+ specificity += len(required_query)
+ routes.append((method, compiled, op_name, specificity, required_query))
+
+ # Sort by specificity descending so more specific routes match first
+ routes.sort(key=lambda r: -r[3])
+ return routes
+
+
+def _get_routes_for_service(service: str) -> list[tuple[str, re.Pattern, str, int, dict[str, str]]]:
+ """Get compiled routes for a MiniStack service, with lazy loading."""
+ if service in _REST_ROUTE_CACHE:
+ return _REST_ROUTE_CACHE[service]
+
+ botocore_names = _BOTOCORE_SERVICE_MAP.get(service, [])
+ all_routes = []
+ for bc_name in botocore_names:
+ all_routes.extend(_load_botocore_routes(bc_name))
+
+ all_routes.sort(key=lambda r: -r[3])
+ _REST_ROUTE_CACHE[service] = all_routes
+ return all_routes
+
+
+def _match_rest_action(service: str, method: str, path: str,
+ query_params: dict | None = None) -> str | None:
+ """Match a REST request against botocore route patterns."""
+ if service not in _BOTOCORE_SERVICE_MAP:
+ return None
+
+ routes = _get_routes_for_service(service)
+ if not routes:
+ return None
+
+ norm_path = path.rstrip("/") or "/"
+ qp = query_params or {}
+
+ best_match = None
+ best_specificity = -1
+
+ for route_method, route_re, op_name, specificity, required_query in routes:
+ if route_method != method:
+ continue
+ if not route_re.match(norm_path):
+ continue
+ # Check required query params for disambiguation
+ if required_query:
+ match_qp = True
+ for k, v in required_query.items():
+ if k not in qp:
+ match_qp = False
+ break
+ if v:
+ # Check value match (e.g., Operation=Untag)
+ actual = qp[k]
+ if isinstance(actual, list):
+ actual = actual[0] if actual else ""
+ if actual != v:
+ match_qp = False
+ break
+ if not match_qp:
+ continue
+ if specificity > best_specificity:
+ best_match = op_name
+ best_specificity = specificity
+
+ return best_match
+
+
+def extract_iam_action(service: str, method: str, path: str,
+ headers: dict, body: bytes,
+ query_params: dict) -> str | None:
+ """Return the IAM action string (``namespace:ActionName``) or None."""
+ namespace = SERVICE_TO_IAM_NAMESPACE.get(service)
+ if namespace is None:
+ logger.debug("AUTH: no IAM namespace for service %s — allowing", service)
+ return None
+
+ # Tier 1: Action query param (query-protocol services)
+ action_name = _action_from_query(query_params, body,
+ headers.get("content-type", ""))
+ if action_name:
+ return f"{namespace}:{action_name}"
+
+ # Tier 2: X-Amz-Target header (JSON-protocol services)
+ action_name = _action_from_target(headers)
+ if action_name:
+ return f"{namespace}:{action_name}"
+
+ # Tier 3: REST path-based mapping
+ if service == "s3":
+ action_name = _s3_action(method, path, query_params)
+ if action_name:
+ return f"s3:{action_name}"
+
+ if service == "lambda":
+ action_name = _lambda_action(method, path)
+ if action_name:
+ return f"lambda:{action_name}"
+
+ # Tier 4: Generic botocore route matcher (all other REST services)
+ action_name = _match_rest_action(service, method, path, query_params)
+ if action_name:
+ return f"{namespace}:{action_name}"
+
+ logger.debug("AUTH: could not extract action for %s %s %s — allowing",
+ service, method, path)
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Per-protocol AccessDenied response
+# ---------------------------------------------------------------------------
+
+# Protocol type per service (for error formatting)
+_SERVICE_PROTOCOL: dict[str, str] = {
+ "s3": "rest-xml",
+ "ec2": "ec2-xml",
+ "autoscaling": "query-xml",
+ "cloudformation": "query-xml",
+ "elasticache": "query-xml",
+ "elasticloadbalancing": "query-xml",
+ "iam": "query-xml",
+ "monitoring": "query-xml",
+ "rds": "query-xml",
+ "route53": "rest-xml",
+ "ses": "query-xml",
+ "sns": "query-xml",
+ "sts": "query-xml",
+ # Everything else defaults to JSON
+}
+
+
+def _xml_escape(s: str) -> str:
+ return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+
+
+# ---------------------------------------------------------------------------
+# Resource ARN construction
+# ---------------------------------------------------------------------------
+
+def _safe_json_field(body: bytes, field: str) -> str:
+ """Extract a field from a JSON body, returning '' on any failure."""
+ if not body:
+ return ""
+ try:
+ return json.loads(body).get(field, "") or ""
+ except (json.JSONDecodeError, TypeError, AttributeError):
+ return ""
+
+
+def _query_param(query_params: dict, key: str) -> str:
+ """Extract a single query parameter value."""
+ val = query_params.get(key, "")
+ if isinstance(val, list):
+ return val[0] if val else ""
+ return val or ""
+
+
+def extract_resource_arn(service: str, method: str, path: str,
+ headers: dict, body: bytes,
+ query_params: dict, region: str,
+ account_id: str) -> str:
+ """Construct the resource ARN for the request, or '*' if unknown."""
+
+ if service == "s3":
+ parts = [p for p in path.split("/") if p]
+ if not parts:
+ return "*" # ListBuckets — no specific resource
+ bucket = parts[0]
+ if len(parts) >= 2:
+ key = "/".join(parts[1:])
+ return f"arn:aws:s3:::{bucket}/{key}"
+ return f"arn:aws:s3:::{bucket}"
+
+ if service == "dynamodb":
+ table = _safe_json_field(body, "TableName")
+ if table:
+ return f"arn:aws:dynamodb:{region}:{account_id}:table/{table}"
+ return "*"
+
+ if service == "lambda":
+ # Path: /2015-03-31/functions/{name}/...
+ path_parts = [p for p in path.split("/") if p]
+ if "functions" in path_parts:
+ fi = path_parts.index("functions")
+ if fi + 1 < len(path_parts):
+ func_name = path_parts[fi + 1]
+ return f"arn:aws:lambda:{region}:{account_id}:function:{func_name}"
+ if "layers" in path_parts:
+ li = path_parts.index("layers")
+ if li + 1 < len(path_parts):
+ layer_name = path_parts[li + 1]
+ return f"arn:aws:lambda:{region}:{account_id}:layer:{layer_name}"
+ if "event-source-mappings" in path_parts:
+ ei = path_parts.index("event-source-mappings")
+ if ei + 1 < len(path_parts):
+ uuid = path_parts[ei + 1]
+ return f"arn:aws:lambda:{region}:{account_id}:event-source-mapping:{uuid}"
+ return "*"
+
+ if service == "sqs":
+ # Queue URL is in the path or QueueUrl param
+ queue_url = _query_param(query_params, "QueueUrl")
+ if queue_url:
+ # Extract queue name from URL
+ q_parts = queue_url.rstrip("/").split("/")
+ queue_name = q_parts[-1] if q_parts else ""
+ if queue_name:
+ return f"arn:aws:sqs:{region}:{account_id}:{queue_name}"
+ # QueueName param (CreateQueue)
+ queue_name = _query_param(query_params, "QueueName")
+ if queue_name:
+ return f"arn:aws:sqs:{region}:{account_id}:{queue_name}"
+ return "*"
+
+ if service == "sns":
+ topic_arn = _query_param(query_params, "TopicArn")
+ if topic_arn:
+ return topic_arn
+ target_arn = _query_param(query_params, "TargetArn")
+ if target_arn:
+ return target_arn
+ # CreateTopic — name in params
+ topic_name = _query_param(query_params, "Name")
+ if topic_name:
+ return f"arn:aws:sns:{region}:{account_id}:{topic_name}"
+ return "*"
+
+ if service == "kms":
+ key_id = _safe_json_field(body, "KeyId")
+ if key_id:
+ # KeyId can be an ARN, alias, or key ID
+ if key_id.startswith("arn:"):
+ return key_id
+ if key_id.startswith("alias/"):
+ return f"arn:aws:kms:{region}:{account_id}:{key_id}"
+ return f"arn:aws:kms:{region}:{account_id}:key/{key_id}"
+ return "*"
+
+ if service == "secretsmanager":
+ secret_id = _safe_json_field(body, "SecretId")
+ if not secret_id:
+ secret_id = _safe_json_field(body, "Name")
+ if secret_id:
+ if secret_id.startswith("arn:"):
+ return secret_id
+ return f"arn:aws:secretsmanager:{region}:{account_id}:secret:{secret_id}"
+ return "*"
+
+ if service == "iam":
+ # IAM actions target users, roles, policies — extract from params
+ role_name = _query_param(query_params, "RoleName")
+ if role_name:
+ return f"arn:aws:iam::{account_id}:role/{role_name}"
+ user_name = _query_param(query_params, "UserName")
+ if user_name:
+ return f"arn:aws:iam::{account_id}:user/{user_name}"
+ policy_arn = _query_param(query_params, "PolicyArn")
+ if policy_arn:
+ return policy_arn
+ group_name = _query_param(query_params, "GroupName")
+ if group_name:
+ return f"arn:aws:iam::{account_id}:group/{group_name}"
+ return "*"
+
+ if service == "sts":
+ role_arn = _query_param(query_params, "RoleArn")
+ if role_arn:
+ return role_arn
+ return "*"
+
+ # --- Target-based (JSON body) services ---
+
+ if service == "events":
+ name = _safe_json_field(body, "Name") or _safe_json_field(body, "RuleName")
+ bus = _safe_json_field(body, "EventBusName") or "default"
+ if name:
+ return f"arn:aws:events:{region}:{account_id}:rule/{bus}/{name}"
+ bus_only = _safe_json_field(body, "EventBusName")
+ if bus_only:
+ if bus_only.startswith("arn:"):
+ return bus_only
+ return f"arn:aws:events:{region}:{account_id}:event-bus/{bus_only}"
+ return "*"
+
+ if service == "states":
+ arn = _safe_json_field(body, "stateMachineArn")
+ if arn:
+ return arn
+ arn = _safe_json_field(body, "executionArn")
+ if arn:
+ return arn
+ arn = _safe_json_field(body, "activityArn")
+ if arn:
+ return arn
+ name = _safe_json_field(body, "name")
+ if name:
+ return f"arn:aws:states:{region}:{account_id}:stateMachine:{name}"
+ return "*"
+
+ if service == "kinesis":
+ arn = _safe_json_field(body, "StreamARN")
+ if arn:
+ return arn
+ name = _safe_json_field(body, "StreamName")
+ if name:
+ return f"arn:aws:kinesis:{region}:{account_id}:stream/{name}"
+ return "*"
+
+ if service == "logs":
+ name = _safe_json_field(body, "logGroupName")
+ if name:
+ return f"arn:aws:logs:{region}:{account_id}:log-group:{name}"
+ return "*"
+
+ if service == "glue":
+ db = _safe_json_field(body, "DatabaseName")
+ if db:
+ return f"arn:aws:glue:{region}:{account_id}:database/{db}"
+ name = _safe_json_field(body, "Name")
+ if name:
+ return f"arn:aws:glue:{region}:{account_id}:table/{name}"
+ crawler = _safe_json_field(body, "CrawlerName")
+ if crawler:
+ return f"arn:aws:glue:{region}:{account_id}:crawler/{crawler}"
+ job = _safe_json_field(body, "JobName")
+ if job:
+ return f"arn:aws:glue:{region}:{account_id}:job/{job}"
+ return f"arn:aws:glue:{region}:{account_id}:catalog"
+
+ if service == "codebuild":
+ name = _safe_json_field(body, "projectName") or _safe_json_field(body, "name")
+ if name:
+ return f"arn:aws:codebuild:{region}:{account_id}:project/{name}"
+ return "*"
+
+ if service == "ecr":
+ name = _safe_json_field(body, "repositoryName")
+ if name:
+ return f"arn:aws:ecr:{region}:{account_id}:repository/{name}"
+ return "*"
+
+ if service == "config":
+ name = _safe_json_field(body, "ConfigRuleName")
+ if name:
+ return f"arn:aws:config:{region}:{account_id}:config-rule/{name}"
+ return "*"
+
+ if service == "athena":
+ wg = _safe_json_field(body, "WorkGroup")
+ if wg:
+ return f"arn:aws:athena:{region}:{account_id}:workgroup/{wg}"
+ return "*"
+
+ if service == "servicediscovery":
+ sid = _safe_json_field(body, "ServiceId") or _safe_json_field(body, "Id")
+ if sid:
+ return f"arn:aws:servicediscovery:{region}:{account_id}:service/{sid}"
+ nid = _safe_json_field(body, "NamespaceId")
+ if nid:
+ return f"arn:aws:servicediscovery:{region}:{account_id}:namespace/{nid}"
+ name = _safe_json_field(body, "Name")
+ if name:
+ return f"arn:aws:servicediscovery:{region}:{account_id}:namespace/{name}"
+ return "*"
+
+ if service == "opensearch":
+ name = _safe_json_field(body, "DomainName")
+ if name:
+ return f"arn:aws:es:{region}:{account_id}:domain/{name}"
+ return "*"
+
+ if service == "organizations":
+ return f"arn:aws:organizations::{account_id}:organization/*"
+
+ if service == "wafv2":
+ arn = _safe_json_field(body, "ARN")
+ if arn:
+ return arn
+ name = _safe_json_field(body, "Name")
+ if name:
+ scope = _safe_json_field(body, "Scope") or "REGIONAL"
+ prefix = "regional" if scope == "REGIONAL" else "global"
+ return f"arn:aws:wafv2:{region}:{account_id}:{prefix}/webacl/{name}/*"
+ return "*"
+
+ if service in ("elasticmapreduce", "emr"):
+ cid = _safe_json_field(body, "ClusterId") or _safe_json_field(body, "JobFlowId")
+ if cid:
+ return f"arn:aws:elasticmapreduce:{region}:{account_id}:cluster/{cid}"
+ name = _safe_json_field(body, "Name")
+ if name:
+ return f"arn:aws:elasticmapreduce:{region}:{account_id}:cluster/*"
+ return "*"
+
+ if service == "transfer":
+ sid = _safe_json_field(body, "ServerId")
+ if sid:
+ return f"arn:aws:transfer:{region}:{account_id}:server/{sid}"
+ return "*"
+
+ if service == "firehose":
+ name = _safe_json_field(body, "DeliveryStreamName")
+ if name:
+ return f"arn:aws:firehose:{region}:{account_id}:deliverystream/{name}"
+ return "*"
+
+ if service == "backup":
+ vault = _safe_json_field(body, "BackupVaultName")
+ if vault:
+ return f"arn:aws:backup:{region}:{account_id}:backup-vault:{vault}"
+ return "*"
+
+ # --- Target-based services using JSON body for ECS/EKS ---
+
+ if service == "ecs":
+ cluster = _safe_json_field(body, "cluster")
+ if cluster:
+ if cluster.startswith("arn:"):
+ return cluster
+ return f"arn:aws:ecs:{region}:{account_id}:cluster/{cluster}"
+ task_def = _safe_json_field(body, "taskDefinition")
+ if task_def:
+ if task_def.startswith("arn:"):
+ return task_def
+ return f"arn:aws:ecs:{region}:{account_id}:task-definition/{task_def}"
+ service_name = _safe_json_field(body, "serviceName")
+ if service_name:
+ return f"arn:aws:ecs:{region}:{account_id}:service/*/{service_name}"
+ return "*"
+
+ if service == "eks":
+ name = _safe_json_field(body, "name")
+ if not name:
+ # EKS REST: /clusters/{name}
+ parts = [p for p in path.split("/") if p]
+ if "clusters" in parts:
+ ci = parts.index("clusters")
+ if ci + 1 < len(parts):
+ name = parts[ci + 1]
+ if name:
+ return f"arn:aws:eks:{region}:{account_id}:cluster/{name}"
+ return "*"
+
+ # --- Query-based services ---
+
+ if service == "acm":
+ arn = _query_param(query_params, "CertificateArn")
+ if arn:
+ return arn
+ return "*"
+
+ if service == "cloudformation":
+ name = _query_param(query_params, "StackName")
+ if name:
+ if name.startswith("arn:"):
+ return name
+ return f"arn:aws:cloudformation:{region}:{account_id}:stack/{name}/*"
+ return "*"
+
+ if service == "monitoring":
+ # CloudWatch alarms
+ name = _query_param(query_params, "AlarmName")
+ if name:
+ return f"arn:aws:cloudwatch:{region}:{account_id}:alarm:{name}"
+ ns = _query_param(query_params, "Namespace")
+ if ns:
+ return "*" # Metrics don't have individual ARNs
+ return "*"
+
+ if service == "autoscaling":
+ name = _query_param(query_params, "AutoScalingGroupName")
+ if name:
+ return f"arn:aws:autoscaling:{region}:{account_id}:autoScalingGroup:*:autoScalingGroupName/{name}"
+ return "*"
+
+ if service == "elasticache":
+ cid = _query_param(query_params, "CacheClusterId")
+ if cid:
+ return f"arn:aws:elasticache:{region}:{account_id}:cluster:{cid}"
+ rgid = _query_param(query_params, "ReplicationGroupId")
+ if rgid:
+ return f"arn:aws:elasticache:{region}:{account_id}:replicationgroup:{rgid}"
+ return "*"
+
+ if service == "elasticloadbalancing":
+ arn = _query_param(query_params, "LoadBalancerArn")
+ if arn:
+ return arn
+ arn = _query_param(query_params, "TargetGroupArn")
+ if arn:
+ return arn
+ arn = _query_param(query_params, "ListenerArn")
+ if arn:
+ return arn
+ return "*"
+
+ if service == "rds":
+ name = _query_param(query_params, "DBInstanceIdentifier")
+ if name:
+ return f"arn:aws:rds:{region}:{account_id}:db:{name}"
+ name = _query_param(query_params, "DBClusterIdentifier")
+ if name:
+ return f"arn:aws:rds:{region}:{account_id}:cluster:{name}"
+ return "*"
+
+ if service == "ses":
+ identity = _query_param(query_params, "Identity")
+ if identity:
+ return f"arn:aws:ses:{region}:{account_id}:identity/{identity}"
+ return "*"
+
+ if service == "ssm":
+ name = _query_param(query_params, "Name")
+ if name:
+ return f"arn:aws:ssm:{region}:{account_id}:parameter{name if name.startswith('/') else '/' + name}"
+ return "*"
+
+ if service == "route53":
+ zone_id = _query_param(query_params, "HostedZoneId")
+ if not zone_id:
+ # REST: /2013-04-01/hostedzone/{id}
+ parts = [p for p in path.split("/") if p]
+ if "hostedzone" in parts:
+ hi = parts.index("hostedzone")
+ if hi + 1 < len(parts):
+ zone_id = parts[hi + 1]
+ if zone_id:
+ return f"arn:aws:route53:::hostedzone/{zone_id}"
+ return "*"
+
+ if service == "cloudfront":
+ # REST: /2020-05-31/distribution/{id}
+ parts = [p for p in path.split("/") if p]
+ if "distribution" in parts:
+ di = parts.index("distribution")
+ if di + 1 < len(parts):
+ return f"arn:aws:cloudfront::{account_id}:distribution/{parts[di + 1]}"
+ return "*"
+
+ if service in ("cognito-idp", "cognito_idp"):
+ pool_id = _safe_json_field(body, "UserPoolId")
+ if pool_id:
+ return f"arn:aws:cognito-idp:{region}:{account_id}:userpool/{pool_id}"
+ return "*"
+
+ if service in ("cognito-identity", "cognito_identity"):
+ pool_id = _safe_json_field(body, "IdentityPoolId")
+ if pool_id:
+ return f"arn:aws:cognito-identity:{region}:{account_id}:identitypool/{pool_id}"
+ return "*"
+
+ # --- Simple REST path services ---
+
+ if service == "scheduler":
+ parts = [p for p in path.split("/") if p]
+ if "schedules" in parts:
+ si = parts.index("schedules")
+ if si + 1 < len(parts):
+ return f"arn:aws:scheduler:{region}:{account_id}:schedule/default/{parts[si + 1]}"
+ if "schedule-groups" in parts:
+ gi = parts.index("schedule-groups")
+ if gi + 1 < len(parts):
+ return f"arn:aws:scheduler:{region}:{account_id}:schedule-group/{parts[gi + 1]}"
+ return "*"
+
+ if service == "pipes":
+ parts = [p for p in path.split("/") if p]
+ if "pipes" in parts:
+ pi = parts.index("pipes")
+ if pi + 1 < len(parts):
+ return f"arn:aws:pipes:{region}:{account_id}:pipe/{parts[pi + 1]}"
+ return "*"
+
+ if service == "mq":
+ parts = [p for p in path.split("/") if p]
+ if "brokers" in parts:
+ bi = parts.index("brokers")
+ if bi + 1 < len(parts):
+ return f"arn:aws:mq:{region}:{account_id}:broker:{parts[bi + 1]}:*"
+ return "*"
+
+ if service == "kafka":
+ parts = [p for p in path.split("/") if p]
+ if "clusters" in parts:
+ ci = parts.index("clusters")
+ if ci + 1 < len(parts):
+ return f"arn:aws:kafka:{region}:{account_id}:cluster/{parts[ci + 1]}/*"
+ return "*"
+
+ if service == "dsql":
+ parts = [p for p in path.split("/") if p]
+ if "clusters" in parts:
+ ci = parts.index("clusters")
+ if ci + 1 < len(parts):
+ return f"arn:aws:dsql:{region}:{account_id}:cluster/{parts[ci + 1]}"
+ return "*"
+
+ if service == "mediaconnect":
+ parts = [p for p in path.split("/") if p]
+ if "flows" in parts:
+ fi = parts.index("flows")
+ if fi + 1 < len(parts):
+ return f"arn:aws:mediaconnect:{region}:{account_id}:flow:{parts[fi + 1]}:*"
+ return "*"
+
+ if service == "inspector2":
+ return "*" # Mostly account-level operations, no per-resource ARNs
+
+ if service == "elasticfilesystem":
+ parts = [p for p in path.split("/") if p]
+ if "file-systems" in parts:
+ fi = parts.index("file-systems")
+ if fi + 1 < len(parts):
+ return f"arn:aws:elasticfilesystem:{region}:{account_id}:file-system/{parts[fi + 1]}"
+ if "mount-targets" in parts:
+ mi = parts.index("mount-targets")
+ if mi + 1 < len(parts):
+ return f"arn:aws:elasticfilesystem:{region}:{account_id}:file-system/*"
+ if "access-points" in parts:
+ ai = parts.index("access-points")
+ if ai + 1 < len(parts):
+ return f"arn:aws:elasticfilesystem:{region}:{account_id}:access-point/{parts[ai + 1]}"
+ return "*"
+
+ if service == "cloudtrail":
+ name = _safe_json_field(body, "Name") or _safe_json_field(body, "TrailName")
+ if name:
+ if name.startswith("arn:"):
+ return name
+ return f"arn:aws:cloudtrail:{region}:{account_id}:trail/{name}"
+ return "*"
+
+ if service == "s3tables":
+ parts = [p for p in path.split("/") if p]
+ if "buckets" in parts:
+ bi = parts.index("buckets")
+ if bi + 1 < len(parts):
+ bucket = parts[bi + 1]
+ if "tables" in parts:
+ ti = parts.index("tables")
+ if ti + 1 < len(parts):
+ return f"arn:aws:s3tables:{region}:{account_id}:bucket/{bucket}/table/{parts[ti + 1]}"
+ return f"arn:aws:s3tables:{region}:{account_id}:bucket/{bucket}"
+ return "*"
+
+ if service == "s3files":
+ parts = [p for p in path.split("/") if p]
+ if "file-systems" in parts:
+ fi = parts.index("file-systems")
+ if fi + 1 < len(parts):
+ return f"arn:aws:s3:{region}:{account_id}:file-system/{parts[fi + 1]}"
+ return "*"
+
+ if service == "resource-groups":
+ parts = [p for p in path.split("/") if p]
+ if "groups" in parts:
+ gi = parts.index("groups")
+ if gi + 1 < len(parts):
+ return f"arn:aws:resource-groups:{region}:{account_id}:group/{parts[gi + 1]}"
+ return "*"
+
+ if service == "rds-data":
+ arn = _safe_json_field(body, "resourceArn")
+ if arn:
+ return arn
+ return "*"
+
+ if service == "appconfig":
+ parts = [p for p in path.split("/") if p]
+ if "applications" in parts:
+ ai = parts.index("applications")
+ if ai + 1 < len(parts):
+ app_id = parts[ai + 1]
+ if "environments" in parts:
+ ei = parts.index("environments")
+ if ei + 1 < len(parts):
+ return f"arn:aws:appconfig:{region}:{account_id}:application/{app_id}/environment/{parts[ei + 1]}"
+ if "configurationprofiles" in parts:
+ ci = parts.index("configurationprofiles")
+ if ci + 1 < len(parts):
+ return f"arn:aws:appconfig:{region}:{account_id}:application/{app_id}/configurationprofile/{parts[ci + 1]}"
+ return f"arn:aws:appconfig:{region}:{account_id}:application/{app_id}"
+ if "deploymentstrategies" in parts:
+ di = parts.index("deploymentstrategies")
+ if di + 1 < len(parts):
+ return f"arn:aws:appconfig:{region}:{account_id}:deploymentstrategy/{parts[di + 1]}"
+ return "*"
+
+ if service == "appconfigdata":
+ return "*" # Session-based, no per-resource ARN
+
+ # --- EC2 (query-based, many resource types) ---
+
+ if service == "ec2":
+ # EC2 uses query params. Try resource ID fields in priority order.
+ _EC2_RESOURCE_FIELDS = [
+ ("InstanceId.1", "instance"),
+ ("InstanceId", "instance"),
+ ("VpcId", "vpc"),
+ ("SubnetId", "subnet"),
+ ("SecurityGroupId.1", "security-group"),
+ ("GroupId", "security-group"),
+ ("GroupName", "security-group"),
+ ("VolumeId", "volume"),
+ ("KeyName", "key-pair"),
+ ("ImageId", "image"),
+ ("InternetGatewayId", "internet-gateway"),
+ ("RouteTableId", "route-table"),
+ ("NetworkInterfaceId", "network-interface"),
+ ("AllocationId", "elastic-ip"),
+ ("SnapshotId", "snapshot"),
+ ("VpcEndpointId.1", "vpc-endpoint"),
+ ]
+ for field, rtype in _EC2_RESOURCE_FIELDS:
+ val = _query_param(query_params, field)
+ if val:
+ return f"arn:aws:ec2:{region}:{account_id}:{rtype}/{val}"
+ return "*"
+
+ # --- IoT (REST path-based, multiple resource types) ---
+
+ if service == "iot":
+ parts = [p for p in path.split("/") if p]
+ _IOT_RESOURCES = {
+ "things": "thing",
+ "thing-types": "thingtype",
+ "thing-groups": "thinggroup",
+ "policies": "policy",
+ "certificates": "cert",
+ "rules": "rule",
+ }
+ for segment, rtype in _IOT_RESOURCES.items():
+ if segment in parts:
+ si = parts.index(segment)
+ if si + 1 < len(parts):
+ name = parts[si + 1]
+ if rtype == "cert":
+ return f"arn:aws:iot:{region}:{account_id}:{rtype}/{name}"
+ return f"arn:aws:iot:{region}:{account_id}:{rtype}/{name}"
+ return "*"
+
+ # --- API Gateway (REST path-based) ---
+
+ if service == "apigateway":
+ parts = [p for p in path.split("/") if p]
+ # v2: /v2/apis/{apiId}
+ if "apis" in parts:
+ ai = parts.index("apis")
+ if ai + 1 < len(parts):
+ api_id = parts[ai + 1]
+ return f"arn:aws:apigateway:{region}::/apis/{api_id}"
+ return f"arn:aws:apigateway:{region}::/apis/*"
+ # v1: /restapis/{restApiId}
+ if "restapis" in parts:
+ ri = parts.index("restapis")
+ if ri + 1 < len(parts):
+ api_id = parts[ri + 1]
+ return f"arn:aws:apigateway:{region}::/restapis/{api_id}"
+ return f"arn:aws:apigateway:{region}::/restapis/*"
+ return "*"
+
+ # --- Bedrock (REST path-based, multiple sub-services) ---
+
+ if service == "bedrock":
+ parts = [p for p in path.split("/") if p]
+ if "foundation-models" in parts:
+ fi = parts.index("foundation-models")
+ if fi + 1 < len(parts):
+ return f"arn:aws:bedrock:{region}::foundation-model/{parts[fi + 1]}"
+ if "custom-models" in parts:
+ ci = parts.index("custom-models")
+ if ci + 1 < len(parts):
+ return f"arn:aws:bedrock:{region}:{account_id}:custom-model/{parts[ci + 1]}"
+ if "guardrails" in parts:
+ gi = parts.index("guardrails")
+ if gi + 1 < len(parts):
+ return f"arn:aws:bedrock:{region}:{account_id}:guardrail/{parts[gi + 1]}"
+ if "inference-profiles" in parts:
+ ii = parts.index("inference-profiles")
+ if ii + 1 < len(parts):
+ return f"arn:aws:bedrock:{region}:{account_id}:inference-profile/{parts[ii + 1]}"
+ return "*"
+
+ if service == "bedrock-runtime":
+ parts = [p for p in path.split("/") if p]
+ if "model" in parts:
+ mi = parts.index("model")
+ if mi + 1 < len(parts):
+ model_id = parts[mi + 1]
+ return f"arn:aws:bedrock:{region}::foundation-model/{model_id}"
+ return "*"
+
+ if service == "bedrock-agent":
+ parts = [p for p in path.split("/") if p]
+ if "agents" in parts:
+ ai = parts.index("agents")
+ if ai + 1 < len(parts):
+ return f"arn:aws:bedrock:{region}:{account_id}:agent/{parts[ai + 1]}"
+ if "knowledgebases" in parts:
+ ki = parts.index("knowledgebases")
+ if ki + 1 < len(parts):
+ return f"arn:aws:bedrock:{region}:{account_id}:knowledge-base/{parts[ki + 1]}"
+ if "flows" in parts:
+ fi = parts.index("flows")
+ if fi + 1 < len(parts):
+ return f"arn:aws:bedrock:{region}:{account_id}:flow/{parts[fi + 1]}"
+ if "prompts" in parts:
+ pi = parts.index("prompts")
+ if pi + 1 < len(parts):
+ return f"arn:aws:bedrock:{region}:{account_id}:prompt/{parts[pi + 1]}"
+ return "*"
+
+ if service == "bedrock-agent-runtime":
+ parts = [p for p in path.split("/") if p]
+ if "knowledgebases" in parts:
+ ki = parts.index("knowledgebases")
+ if ki + 1 < len(parts):
+ return f"arn:aws:bedrock:{region}:{account_id}:knowledge-base/{parts[ki + 1]}"
+ if "agents" in parts:
+ ai = parts.index("agents")
+ if ai + 1 < len(parts):
+ return f"arn:aws:bedrock:{region}:{account_id}:agent/{parts[ai + 1]}"
+ return "*"
+
+ # --- AppSync (REST path-based) ---
+
+ if service == "appsync":
+ parts = [p for p in path.split("/") if p]
+ if "apis" in parts:
+ ai = parts.index("apis")
+ if ai + 1 < len(parts):
+ api_id = parts[ai + 1]
+ # Sub-resources
+ if "datasources" in parts:
+ di = parts.index("datasources")
+ if di + 1 < len(parts):
+ return f"arn:aws:appsync:{region}:{account_id}:apis/{api_id}/datasources/{parts[di + 1]}"
+ if "types" in parts:
+ ti = parts.index("types")
+ if ti + 1 < len(parts):
+ return f"arn:aws:appsync:{region}:{account_id}:apis/{api_id}/types/{parts[ti + 1]}"
+ return f"arn:aws:appsync:{region}:{account_id}:apis/{api_id}"
+ return "*"
+
+ return "*"
+
+
+def access_denied_response(service: str, action: str, principal_arn: str,
+ request_id: str, *, error_code: str = "",
+ message: str = "") -> tuple:
+ """Format a 403 error response matching the service's protocol."""
+ if not message:
+ message = (
+ f"User: {principal_arn} is not authorized to perform: {action} "
+ f"because no identity-based policy allows the {action} action"
+ )
+ code = error_code or "AccessDenied"
+ protocol = _SERVICE_PROTOCOL.get(service, "json")
+
+ _esc_code = _xml_escape(code)
+ _esc_rid = _xml_escape(request_id)
+ _esc_msg = _xml_escape(message)
+
+ if protocol == "rest-xml":
+ body = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ f"<Error><Code>{_esc_code}</Code>"
+ f"<Message>{_esc_msg}</Message>"
+ f"<RequestId>{_esc_rid}</RequestId></Error>"
+ )
+ return 403, {"Content-Type": "application/xml"}, body.encode()
+
+ if protocol == "ec2-xml":
+ ec2_code = "UnauthorizedOperation" if code == "AccessDenied" else _esc_code
+ body = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ f"<Response><Errors><Error>"
+ f"<Code>{ec2_code}</Code>"
+ f"<Message>{_esc_msg}</Message>"
+ f"</Error></Errors>"
+ f"<RequestID>{_esc_rid}</RequestID></Response>"
+ )
+ return 403, {"Content-Type": "application/xml"}, body.encode()
+
+ if protocol == "query-xml":
+ body = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<ErrorResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/">'
+ f"<Error><Type>Sender</Type><Code>{_esc_code}</Code>"
+ f"<Message>{_esc_msg}</Message></Error>"
+ f"<RequestId>{_esc_rid}</RequestId></ErrorResponse>"
+ )
+ return 403, {"Content-Type": "text/xml"}, body.encode()
+
+ # JSON protocol (DynamoDB, Lambda, KMS, Logs, Glue, etc.)
+ json_type = code if code != "AccessDenied" else "AccessDeniedException"
+ body = json.dumps({
+ "__type": json_type,
+ "message": message,
+ })
+ return (
+ 403,
+ {
+ "Content-Type": "application/x-amz-json-1.0",
+ "x-amzn-errortype": json_type,
+ },
+ body.encode(),
+ )
diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.py
new file mode 100644
index 00000000..9b6dde32
--- /dev/null
+++ b/ministack/core/iam_evaluator.py
@@ -0,0 +1,862 @@
+"""IAM policy evaluation engine.
+
+Implements the AWS IAM policy evaluation algorithm (single-account,
+no SCPs/permissions boundaries/session policies) behind the AUTH=true flag.
+
+Evaluation order:
+ 1. Explicit Deny in any applicable policy → DENY
+ 2. Explicit Allow in any applicable policy → ALLOW
+ 3. No matching Allow → implicit DENY
+"""
+
+import datetime as _dt
+import ipaddress
+import json
+import logging
+import re
+from dataclasses import dataclass, field
+from typing import Any
+
+logger = logging.getLogger("ministack")
+
+
+# ---------------------------------------------------------------------------
+# Data structures
+# ---------------------------------------------------------------------------
+
+@dataclass
+class ParsedStatement:
+ sid: str
+ effect: str # "Allow" or "Deny"
+ actions: list[str] = field(default_factory=list)
+ not_actions: list[str] = field(default_factory=list)
+ resources: list[str] = field(default_factory=list)
+ not_resources: list[str] = field(default_factory=list)
+ conditions: dict = field(default_factory=dict)
+
+
+@dataclass
+class EvalContext:
+ principal_arn: str
+ principal_type: str # "User", "AssumedRole", "Root"
+ principal_account: str
+ action: str # "s3:PutObject"
+ resource_arn: str # "*" until per-service resource ARN construction
+ region: str
+ source_ip: str = "127.0.0.1"
+ secure_transport: bool = False
+ request_tags: dict[str, str] = field(default_factory=dict)
+ tag_keys: list[str] = field(default_factory=list)
+
+
+@dataclass
+class EvalResult:
+ decision: str # "Allow", "Deny", "ImplicitDeny"
+ principal_arn: str = ""
+ matched_sid: str = ""
+ reason: str = ""
+
+
+@dataclass
+class PrincipalInfo:
+ arn: str
+ type: str # "User", "AssumedRole", "Root"
+ account: str
+ policies: list[list[ParsedStatement]] | None # None = root (allow-all)
+
+
+@dataclass
+class AuthError:
+ """Authentication failure (before policy evaluation)."""
+ code: str # "InvalidClientTokenId", "ExpiredTokenException", etc.
+ message: str
+
+
+# Default access keys that are always treated as root (backwards compat)
+_ROOT_ACCESS_KEYS = frozenset({"test", ""})
+
+
+# ---------------------------------------------------------------------------
+# Wildcard matching (IAM-style)
+# ---------------------------------------------------------------------------
+
+_FNMATCH_CACHE: dict[str, re.Pattern] = {}
+
+
+def fnmatch_iam(value: str, pattern: str) -> bool:
+ """Case-insensitive IAM wildcard match. ``*`` = any chars, ``?`` = one char."""
+ if pattern == "*":
+ return True
+ key = pattern.lower()
+ compiled = _FNMATCH_CACHE.get(key)
+ if compiled is None:
+ regex = ""
+ for ch in key:
+ if ch == "*":
+ regex += ".*"
+ elif ch == "?":
+ regex += "."
+ else:
+ regex += re.escape(ch)
+ compiled = re.compile(f"^{regex}$", re.IGNORECASE)
+ if len(_FNMATCH_CACHE) < 4096:
+ _FNMATCH_CACHE[key] = compiled
+ return compiled.match(value) is not None
+
+
+# ---------------------------------------------------------------------------
+# Statement matching
+# ---------------------------------------------------------------------------
+
+def _action_matches(request_action: str, actions: list[str],
+ not_actions: list[str]) -> bool:
+ if actions:
+ return any(fnmatch_iam(request_action, p) for p in actions)
+ if not_actions:
+ return not any(fnmatch_iam(request_action, p) for p in not_actions)
+ return True
+
+
+def _resource_matches(resource_arn: str, resources: list[str],
+ not_resources: list[str]) -> bool:
+ if resources:
+ return any(fnmatch_iam(resource_arn, p) for p in resources)
+ if not_resources:
+ return not any(fnmatch_iam(resource_arn, p) for p in not_resources)
+ return True
+
+
+# ---------------------------------------------------------------------------
+# Condition evaluation
+# ---------------------------------------------------------------------------
+
+def _resolve_condition_key(key: str, ctx: EvalContext) -> Any:
+ """Resolve a global condition context key to its value."""
+ k = key.lower()
+ if k == "aws:principalarn":
+ return ctx.principal_arn
+ if k == "aws:principalaccount":
+ return ctx.principal_account
+ if k == "aws:principaltype":
+ return ctx.principal_type
+ if k == "aws:currenttime":
+ return _dt.datetime.now(_dt.timezone.utc).isoformat()
+ if k == "aws:epochtime":
+ return str(int(_dt.datetime.now(_dt.timezone.utc).timestamp()))
+ if k == "aws:requestedregion":
+ return ctx.region
+ if k == "aws:securetransport":
+ return str(ctx.secure_transport).lower()
+ if k == "aws:sourceip":
+ return ctx.source_ip
+ if k == "aws:tagkeys":
+ return ctx.tag_keys
+ if k.startswith("aws:requesttag/"):
+ tag_key = key[len("aws:RequestTag/"):]
+ return ctx.request_tags.get(tag_key)
+ return None # key not present
+
+
+# -- Operator implementations --
+
+def _op_string_equals(actual: str, expected: str) -> bool:
+ return actual == expected
+
+
+def _op_string_not_equals(actual: str, expected: str) -> bool:
+ return actual != expected
+
+
+def _op_string_equals_ignore_case(actual: str, expected: str) -> bool:
+ return actual.lower() == expected.lower()
+
+
+def _op_string_not_equals_ignore_case(actual: str, expected: str) -> bool:
+ return actual.lower() != expected.lower()
+
+
+def _op_string_like(actual: str, expected: str) -> bool:
+ return fnmatch_iam(actual, expected)
+
+
+def _op_string_not_like(actual: str, expected: str) -> bool:
+ return not fnmatch_iam(actual, expected)
+
+
+def _op_numeric(actual: str, expected: str, cmp: str) -> bool:
+ try:
+ a, e = float(actual), float(expected)
+ except (TypeError, ValueError):
+ return False
+ if cmp == "eq":
+ return a == e
+ if cmp == "neq":
+ return a != e
+ if cmp == "lt":
+ return a < e
+ if cmp == "lte":
+ return a <= e
+ if cmp == "gt":
+ return a > e
+ if cmp == "gte":
+ return a >= e
+ return False
+
+
+def _parse_date(s: str) -> _dt.datetime | None:
+ if not s:
+ return None
+ try:
+ return _dt.datetime.fromisoformat(s.replace("Z", "+00:00"))
+ except (ValueError, AttributeError):
+ pass
+ try:
+ return _dt.datetime.fromtimestamp(float(s), tz=_dt.timezone.utc)
+ except (ValueError, TypeError, OSError):
+ pass
+ return None
+
+
+def _op_date(actual: str, expected: str, cmp: str) -> bool:
+ a = _parse_date(str(actual)) if actual else None
+ e = _parse_date(str(expected)) if expected else None
+ if a is None or e is None:
+ return False
+ if a.tzinfo is None:
+ a = a.replace(tzinfo=_dt.timezone.utc)
+ if e.tzinfo is None:
+ e = e.replace(tzinfo=_dt.timezone.utc)
+ if cmp == "eq":
+ return a == e
+ if cmp == "neq":
+ return a != e
+ if cmp == "lt":
+ return a < e
+ if cmp == "lte":
+ return a <= e
+ if cmp == "gt":
+ return a > e
+ if cmp == "gte":
+ return a >= e
+ return False
+
+
+def _op_bool(actual: str, expected: str) -> bool:
+ return str(actual).lower() == str(expected).lower()
+
+
+def _op_ip_address(actual: str, expected: str) -> bool:
+ try:
+ addr = ipaddress.ip_address(actual)
+ net = ipaddress.ip_network(expected, strict=False)
+ return addr in net
+ except (ValueError, TypeError):
+ return False
+
+
+def _op_not_ip_address(actual: str, expected: str) -> bool:
+ return not _op_ip_address(actual, expected)
+
+
+def _op_arn_like(actual: str, expected: str) -> bool:
+ return fnmatch_iam(actual, expected)
+
+
+def _op_arn_not_like(actual: str, expected: str) -> bool:
+ return not fnmatch_iam(actual, expected)
+
+
+# Operator dispatch table
+_CONDITION_OPS: dict[str, Any] = {
+ "stringequals": _op_string_equals,
+ "stringnotequals": _op_string_not_equals,
+ "stringequalsignorecase": _op_string_equals_ignore_case,
+ "stringnotequalsignorecase": _op_string_not_equals_ignore_case,
+ "stringlike": _op_string_like,
+ "stringnotlike": _op_string_not_like,
+ "numericequals": lambda a, e: _op_numeric(a, e, "eq"),
+ "numericnotequals": lambda a, e: _op_numeric(a, e, "neq"),
+ "numericlessthan": lambda a, e: _op_numeric(a, e, "lt"),
+ "numericlessthanequals": lambda a, e: _op_numeric(a, e, "lte"),
+ "numericgreaterthan": lambda a, e: _op_numeric(a, e, "gt"),
+ "numericgreaterthanequals": lambda a, e: _op_numeric(a, e, "gte"),
+ "dateequals": lambda a, e: _op_date(a, e, "eq"),
+ "datenotequals": lambda a, e: _op_date(a, e, "neq"),
+ "datelessthan": lambda a, e: _op_date(a, e, "lt"),
+ "datelessthanequals": lambda a, e: _op_date(a, e, "lte"),
+ "dategreaterthan": lambda a, e: _op_date(a, e, "gt"),
+ "dategreaterthanequals": lambda a, e: _op_date(a, e, "gte"),
+ "bool": _op_bool,
+ "ipaddress": _op_ip_address,
+ "notipaddress": _op_not_ip_address,
+ "arnequals": _op_arn_like,
+ "arnlike": _op_arn_like,
+ "arnnotequals": _op_arn_not_like,
+ "arnnotlike": _op_arn_not_like,
+ "binaryequals": _op_string_equals,
+}
+
+
+def _evaluate_single_condition(operator: str, actual: Any,
+ expected_values: list[str]) -> bool:
+ """One condition key vs its expected values. Values are OR'd."""
+ op_lower = operator.lower()
+
+ # Null check: tests key presence/absence
+ if op_lower == "null":
+ want_null = str(expected_values[0]).lower() == "true" if expected_values else True
+ return (actual is None) == want_null
+
+ # IfExists: if the key is absent, the condition is satisfied
+ if_exists = False
+ if op_lower.endswith("ifexists"):
+ if_exists = True
+ op_lower = op_lower[:-8] # strip "ifexists"
+
+ # ForAllValues / ForAnyValue set operators
+ for_all = False
+ for_any = False
+ if op_lower.startswith("forallvalues:"):
+ for_all = True
+ op_lower = op_lower[13:]
+ elif op_lower.startswith("foranyvalue:"):
+ for_any = True
+ op_lower = op_lower[12:]
+
+ op_func = _CONDITION_OPS.get(op_lower)
+ if op_func is None:
+ logger.debug("AUTH: unsupported condition operator %s — treating as no-match", operator)
+ return False
+
+ if actual is None:
+ return if_exists or for_all # ForAllValues on missing key = true (empty set)
+
+ # Multi-valued context key
+ if isinstance(actual, list):
+ actual_list = [str(v) for v in actual]
+ else:
+ actual_list = [str(actual)]
+
+ expected_str = [str(v) for v in expected_values]
+
+ if for_all:
+ # Every actual value must match at least one expected value
+ return all(
+ any(op_func(av, ev) for ev in expected_str)
+ for av in actual_list
+ )
+ if for_any:
+ # At least one actual value must match at least one expected value
+ return any(
+ any(op_func(av, ev) for ev in expected_str)
+ for av in actual_list
+ )
+
+ # Standard: any expected value matching any actual value satisfies the condition
+ return any(
+ op_func(str(actual), ev) for ev in expected_str
+ )
+
+
+def _conditions_met(conditions: dict, ctx: EvalContext) -> bool:
+ """All condition blocks must be satisfied (AND between operators).
+ Multiple values within a key are OR'd."""
+ if not conditions:
+ return True
+ for operator, key_values in conditions.items():
+ if not isinstance(key_values, dict):
+ continue
+ for key, expected in key_values.items():
+ actual = _resolve_condition_key(key, ctx)
+ if isinstance(expected, str):
+ expected = [expected]
+ elif not isinstance(expected, list):
+ expected = [str(expected)]
+ if not _evaluate_single_condition(operator, actual, expected):
+ return False
+ return True
+
+
+# ---------------------------------------------------------------------------
+# Policy parsing
+# ---------------------------------------------------------------------------
+
+def parse_policy_document(doc: str | dict) -> list[ParsedStatement]:
+ """Parse a JSON policy document into a list of ParsedStatements."""
+ if isinstance(doc, str):
+ try:
+ doc = json.loads(doc)
+ except (json.JSONDecodeError, TypeError):
+ return []
+ if not isinstance(doc, dict):
+ return []
+
+ statements = doc.get("Statement", [])
+ if isinstance(statements, dict):
+ statements = [statements]
+ if not isinstance(statements, list):
+ return []
+
+ result = []
+ for stmt in statements:
+ if not isinstance(stmt, dict):
+ continue
+ effect = stmt.get("Effect", "")
+ if effect not in ("Allow", "Deny"):
+ continue
+
+ def _as_list(val):
+ if val is None:
+ return []
+ if isinstance(val, str):
+ return [val]
+ if isinstance(val, list):
+ return [str(v) for v in val]
+ return []
+
+ result.append(ParsedStatement(
+ sid=stmt.get("Sid", ""),
+ effect=effect,
+ actions=_as_list(stmt.get("Action")),
+ not_actions=_as_list(stmt.get("NotAction")),
+ resources=_as_list(stmt.get("Resource")),
+ not_resources=_as_list(stmt.get("NotResource")),
+ conditions=stmt.get("Condition", {}),
+ ))
+ return result
+
+
+def validate_policy_document(doc: str | dict) -> str | None:
+ """Validate a policy document. Returns an error message or None."""
+ if isinstance(doc, str):
+ try:
+ doc = json.loads(doc)
+ except (json.JSONDecodeError, TypeError):
+ return "Policy document is not valid JSON"
+ if not isinstance(doc, dict):
+ return "Policy document must be a JSON object"
+
+ statements = doc.get("Statement")
+ if statements is None:
+ return "Policy document must contain a Statement element"
+ if isinstance(statements, dict):
+ statements = [statements]
+ if not isinstance(statements, list) or not statements:
+ return "Policy document must contain at least one Statement"
+
+ for i, stmt in enumerate(statements):
+ if not isinstance(stmt, dict):
+ return f"Statement {i} must be a JSON object"
+ effect = stmt.get("Effect")
+ if effect not in ("Allow", "Deny"):
+ return f"Statement {i} has invalid Effect: {effect}"
+ has_action = "Action" in stmt or "NotAction" in stmt
+ if not has_action:
+ return f"Statement {i} must contain an Action or NotAction element"
+ has_resource = "Resource" in stmt or "NotResource" in stmt
+ if not has_resource:
+ return f"Statement {i} must contain a Resource or NotResource element"
+ if "Action" in stmt and "NotAction" in stmt:
+ return f"Statement {i} cannot have both Action and NotAction"
+ if "Resource" in stmt and "NotResource" in stmt:
+ return f"Statement {i} cannot have both Resource and NotResource"
+
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Core evaluation
+# ---------------------------------------------------------------------------
+
+def evaluate(ctx: EvalContext,
+ policies: list[list[ParsedStatement]]) -> EvalResult:
+ """Evaluate all policies against a request context.
+
+ ``policies`` is a list of parsed-statement lists (one per policy document).
+ Returns Allow, Deny, or ImplicitDeny.
+ """
+ # Flatten all statements
+ all_stmts: list[ParsedStatement] = []
+ for stmts in policies:
+ all_stmts.extend(stmts)
+
+ # Step 1: explicit Deny
+ for stmt in all_stmts:
+ if stmt.effect != "Deny":
+ continue
+ if not _action_matches(ctx.action, stmt.actions, stmt.not_actions):
+ continue
+ if not _resource_matches(ctx.resource_arn, stmt.resources, stmt.not_resources):
+ continue
+ if not _conditions_met(stmt.conditions, ctx):
+ continue
+ return EvalResult("Deny", ctx.principal_arn, stmt.sid, "Explicit deny")
+
+ # Step 2: explicit Allow
+ for stmt in all_stmts:
+ if stmt.effect != "Allow":
+ continue
+ if not _action_matches(ctx.action, stmt.actions, stmt.not_actions):
+ continue
+ if not _resource_matches(ctx.resource_arn, stmt.resources, stmt.not_resources):
+ continue
+ if not _conditions_met(stmt.conditions, ctx):
+ continue
+ return EvalResult("Allow", ctx.principal_arn, stmt.sid, "Explicit allow")
+
+ # Step 3: implicit deny
+ return EvalResult("ImplicitDeny", ctx.principal_arn, "",
+ "No matching Allow statement")
+
+
+# ---------------------------------------------------------------------------
+# Principal resolution
+# ---------------------------------------------------------------------------
+
+def _role_name_from_assumed_arn(assumed_arn: str) -> str:
+ """Extract role name from ``arn:aws:sts::ACCT:assumed-role/RoleName/Session``."""
+ parts = assumed_arn.split(":")
+ if len(parts) >= 6:
+ resource = parts[5]
+ segs = resource.split("/")
+ if len(segs) >= 2:
+ return segs[1]
+ return ""
+
+
+def _gather_role_policies(role_name: str, account_id: str) -> list[list[ParsedStatement]]:
+ from ministack.services import iam as iam_svc
+ # get_scoped takes (account_id, region, key) — region is ignored for AccountScopedDict
+ role = iam_svc._roles.get_scoped(account_id, None, role_name)
+ if role is None:
+ return []
+ policies = []
+ for doc in (role.get("InlinePolicies") or {}).values():
+ stmts = parse_policy_document(doc)
+ if stmts:
+ policies.append(stmts)
+ for policy_arn in role.get("AttachedPolicies", []):
+ doc = _resolve_managed_policy_document(policy_arn, account_id)
+ if doc:
+ stmts = parse_policy_document(doc)
+ if stmts:
+ policies.append(stmts)
+ return policies
+
+
+def _gather_user_policies(user_name: str, account_id: str) -> list[list[ParsedStatement]]:
+ from ministack.services import iam as iam_svc
+ user = iam_svc._users.get_scoped(account_id, None, user_name)
+ if user is None:
+ return []
+ policies = []
+ # User inline policies live in a separate AccountScopedDict, not on the user object
+ for doc in (iam_svc._user_inline_policies.get(user_name) or {}).values():
+ stmts = parse_policy_document(doc)
+ if stmts:
+ policies.append(stmts)
+ for policy_arn in user.get("AttachedPolicies", []):
+ doc = _resolve_managed_policy_document(policy_arn, account_id)
+ if doc:
+ stmts = parse_policy_document(doc)
+ if stmts:
+ policies.append(stmts)
+ # Group policies — iterate all groups in this account, check if user is a member
+ for group_name, group in iam_svc._groups.items():
+ if user_name in group.get("Users", []):
+ # Group inline policies live in a separate AccountScopedDict
+ for doc in (iam_svc._group_inline_policies.get(group_name) or {}).values():
+ stmts = parse_policy_document(doc)
+ if stmts:
+ policies.append(stmts)
+ for policy_arn in group.get("AttachedPolicies", []):
+ doc = _resolve_managed_policy_document(policy_arn, account_id)
+ if doc:
+ stmts = parse_policy_document(doc)
+ if stmts:
+ policies.append(stmts)
+ return policies
+
+
+def _resolve_managed_policy_document(policy_arn: str,
+ account_id: str) -> dict | str | None:
+ """Resolve a managed policy ARN to its default version's document."""
+ from ministack.services import iam as iam_svc
+
+ # AWS-managed policy
+ if policy_arn.startswith("arn:aws:iam::aws:policy/"):
+ mp = iam_svc._aws_managed_policies.get(policy_arn)
+ if mp:
+ default_vid = mp.get("DefaultVersionId", "v1")
+ versions = mp.get("Versions", {})
+ ver = versions.get(default_vid, {})
+ return ver.get("Document")
+ return None
+
+ # Customer-managed policy — look up by ARN
+ # The _policies dict is keyed by policy name; .items() returns current account's
+ for _name, policy in iam_svc._policies.items():
+ if policy.get("Arn") == policy_arn:
+ default_vid = policy.get("DefaultVersionId", "v1")
+ versions = policy.get("Versions", {})
+ ver = versions.get(default_vid, {})
+ return ver.get("Document")
+ return None
+
+
+def _is_root_key(access_key_id: str) -> bool:
+ """Keys that are always treated as root: empty, 'test', 12-digit account IDs."""
+ if not access_key_id or access_key_id in _ROOT_ACCESS_KEYS:
+ return True
+ if re.match(r"^\d{12}$", access_key_id):
+ return True
+ return False
+
+
+def resolve_principal(access_key_id: str,
+ account_id: str) -> PrincipalInfo | AuthError:
+ """Resolve an access key to a principal and their policies.
+
+ Returns a ``PrincipalInfo`` on success or an ``AuthError`` when
+ authentication fails (unknown key, inactive key, expired session).
+ """
+ import time
+
+ from ministack.services import iam as iam_svc
+ from ministack.services import sts as sts_svc
+
+ # Root / default keys — allow-all, no checks
+ if _is_root_key(access_key_id):
+ return PrincipalInfo(
+ arn=f"arn:aws:iam::{account_id}:root",
+ type="Root",
+ account=account_id,
+ policies=None,
+ )
+
+ # Session credentials (AssumeRole) — ASIA prefix
+ if access_key_id in sts_svc._sessions:
+ session = sts_svc._sessions[access_key_id]
+ # Check expiry
+ expiration = session.get("Expiration")
+ if expiration is not None and time.time() > expiration:
+ return AuthError(
+ "ExpiredTokenException",
+ "The security token included in the request is expired",
+ )
+ assumed_arn = session.get("Arn", "")
+ role_name = _role_name_from_assumed_arn(assumed_arn)
+ policies = _gather_role_policies(role_name, account_id)
+ return PrincipalInfo(
+ arn=assumed_arn,
+ type="AssumedRole",
+ account=account_id,
+ policies=policies,
+ )
+
+ # IAM user access key — AKIA prefix
+ key_record = iam_svc._access_keys.get_scoped(account_id, None, access_key_id)
+ if key_record is not None:
+ # Check key status
+ if key_record.get("Status") == "Inactive":
+ return AuthError(
+ "InvalidClientTokenId",
+ "The security token included in the request is invalid.",
+ )
+ user_name = key_record.get("UserName", "")
+ policies = _gather_user_policies(user_name, account_id)
+ return PrincipalInfo(
+ arn=f"arn:aws:iam::{account_id}:user/{user_name}",
+ type="User",
+ account=account_id,
+ policies=policies,
+ )
+
+ # Unknown access key — reject
+ return AuthError(
+ "UnrecognizedClientException",
+ "The security token included in the request is invalid.",
+ )
+
+
+# ---------------------------------------------------------------------------
+# Top-level enforcement entry point
+# ---------------------------------------------------------------------------
+
+# Actions that AWS always allows regardless of IAM policies.
+# https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html
+_ALWAYS_ALLOWED_ACTIONS = frozenset({
+ "sts:GetCallerIdentity",
+ "sts:GetSessionToken",
+ "sts:GetAccessKeyInfo",
+})
+
+
+def enforce(access_key_id: str, iam_action: str, service: str,
+ region: str, resource_arn: str = "*") -> EvalResult | AuthError | None:
+ """Check whether the request should be allowed.
+
+ Returns ``None`` if allowed, an ``AuthError`` for authentication failures,
+ or an ``EvalResult`` for authorization denials.
+ """
+ # Actions that AWS never denies, regardless of policies
+ if iam_action in _ALWAYS_ALLOWED_ACTIONS:
+ return None
+
+ from ministack.core.responses import get_account_id
+
+ account_id = get_account_id()
+ principal = resolve_principal(access_key_id or "", account_id)
+
+ # Authentication failure
+ if isinstance(principal, AuthError):
+ return principal
+
+ # Root principal: allow everything
+ if principal.policies is None:
+ return None
+
+ ctx = EvalContext(
+ principal_arn=principal.arn,
+ principal_type=principal.type,
+ principal_account=principal.account,
+ action=iam_action,
+ resource_arn=resource_arn,
+ region=region,
+ )
+
+ result = evaluate(ctx, principal.policies)
+
+ if result.decision == "Allow":
+ return None
+
+ # Deny or ImplicitDeny
+ result.principal_arn = principal.arn
+ return result
+
+
+# ---------------------------------------------------------------------------
+# Role ARN existence validation (cross-service)
+# ---------------------------------------------------------------------------
+
+def validate_role_arn(role_arn: str) -> str | None:
+ """Validate that a role ARN points to an existing IAM role.
+
+ Returns an error message if the role doesn't exist, or None if it does.
+ Only validates when AUTH=true; returns None (no error) otherwise.
+ """
+ from ministack.app import AUTH
+ if not AUTH:
+ return None
+
+ if not role_arn:
+ return None
+
+ from ministack.services import iam as iam_svc
+
+ # Extract role name from ARN: arn:aws:iam::ACCT:role[/path]/NAME
+ parts = role_arn.split(":")
+ if len(parts) < 6:
+ return f"Invalid role ARN: {role_arn}"
+ resource = parts[5]
+ if not resource.startswith("role/"):
+ return f"Invalid role ARN: {role_arn}"
+ # The role name is everything after "role/" (may include a path like /path/name)
+ role_path_name = resource[5:] # strip "role/"
+ # The actual role name is the last segment
+ role_name = role_path_name.rsplit("/", 1)[-1]
+
+ if iam_svc._roles.get(role_name) is None:
+ return (f"The role with name {role_name} cannot be found. "
+ f"(Service: IAM, Status Code: 404)")
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Trust policy evaluation
+# ---------------------------------------------------------------------------
+
+def evaluate_trust_policy(trust_doc: str | dict,
+ caller_arn: str) -> bool:
+ """Check if a role's trust policy allows the given caller to assume it.
+
+ Supports Principal forms:
+ - ``"*"`` — anyone
+ - ``{"AWS": "arn:aws:iam::ACCT:root"}`` — account root
+ - ``{"AWS": "arn:aws:iam::ACCT:user/NAME"}`` — specific user
+ - ``{"AWS": "ACCT"}`` — account ID shorthand
+ - ``{"Service": "lambda.amazonaws.com"}`` — service principal
+ - ``{"AWS": ["arn1", "arn2"]}`` — list of principals
+ """
+ if isinstance(trust_doc, str):
+ try:
+ trust_doc = json.loads(trust_doc)
+ except (json.JSONDecodeError, TypeError):
+ return False
+ if not isinstance(trust_doc, dict):
+ return False
+
+ statements = trust_doc.get("Statement", [])
+ if isinstance(statements, dict):
+ statements = [statements]
+
+ for stmt in statements:
+ if not isinstance(stmt, dict):
+ continue
+ if stmt.get("Effect") != "Allow":
+ continue
+ # Check Action includes sts:AssumeRole (or *)
+ actions = stmt.get("Action", [])
+ if isinstance(actions, str):
+ actions = [actions]
+ if not any(fnmatch_iam("sts:AssumeRole", a) for a in actions):
+ continue
+ # Check Principal
+ principal = stmt.get("Principal", {})
+ if _principal_matches(principal, caller_arn):
+ return True
+
+ return False
+
+
+def _principal_matches(principal: Any, caller_arn: str) -> bool:
+ """Check if a trust policy Principal matches the caller."""
+ if principal == "*":
+ return True
+ if isinstance(principal, str):
+ return fnmatch_iam(caller_arn, principal)
+ if isinstance(principal, dict):
+ # Check AWS principals
+ aws_principals = principal.get("AWS", [])
+ if isinstance(aws_principals, str):
+ aws_principals = [aws_principals]
+ for p in aws_principals:
+ if p == "*":
+ return True
+ # Account ID shorthand
+ if re.match(r"^\d{12}$", p):
+ if f":{p}:" in caller_arn:
+ return True
+ continue
+ if fnmatch_iam(caller_arn, p):
+ return True
+ # Also match account root against any principal in that account
+ if p.endswith(":root") and f":{p.split(':')[4]}:" in caller_arn:
+ return True
+ # Service principals — match if the caller ARN looks like it came from
+ # that service (e.g., lambda.amazonaws.com allows Lambda-invoked assumes).
+ # In local dev, service principals are typically used by MiniStack's own
+ # service dispatch (Lambda, ECS, etc.), so we also allow if the caller
+ # is root (service-to-service calls use root credentials internally).
+ svc_principals = principal.get("Service", [])
+ if isinstance(svc_principals, str):
+ svc_principals = [svc_principals]
+ if svc_principals:
+ if ":root" in caller_arn:
+ return True
+ for svc in svc_principals:
+ # Extract service prefix: "lambda.amazonaws.com" → "lambda"
+ svc_prefix = svc.split(".")[0] if "." in svc else svc
+ if svc_prefix in caller_arn:
+ return True
+ return False
diff --git a/ministack/core/persistence.py b/ministack/core/persistence.py
index 5b589805..4d85ea9f 100644
--- a/ministack/core/persistence.py
+++ b/ministack/core/persistence.py
@@ -8,7 +8,6 @@ import ast
import json
import logging
import os
-import tempfile
from ministack.core.responses import AccountRegionScopedDict, AccountScopedDict
diff --git a/ministack/services/acm.py b/ministack/services/acm.py
index bef5ae66..cf3efb91 100644
--- a/ministack/services/acm.py
+++ b/ministack/services/acm.py
@@ -15,7 +15,7 @@ import os
import time
from ministack.core.arn import ArnParseError, parse_arn
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
from ministack.core.responses import (
AccountRegionScopedDict,
AccountScopedDict,
diff --git a/ministack/services/appconfig.py b/ministack/services/appconfig.py
index b17182eb..9987e050 100644
--- a/ministack/services/appconfig.py
+++ b/ministack/services/appconfig.py
@@ -34,7 +34,7 @@ import time
import uuid
from ministack.core.arn import ArnParseError, parse_arn
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
from ministack.core.responses import AccountRegionScopedDict, get_account_id, get_region
logger = logging.getLogger("appconfig")
diff --git a/ministack/services/athena.py b/ministack/services/athena.py
index 29f8cc90..efdf0838 100644
--- a/ministack/services/athena.py
+++ b/ministack/services/athena.py
@@ -20,14 +20,12 @@ import json
import logging
import os
import re
-import threading
import time
import xml.etree.ElementTree as ET
-from datetime import date
from urllib.parse import urlparse
from ministack.core.arn import ArnParseError, parse_arn
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
from ministack.core.responses import (
AccountRegionScopedDict,
AccountScopedDict,
diff --git a/ministack/services/autoscaling.py b/ministack/services/autoscaling.py
index b7a1e497..bfbb0cdc 100644
--- a/ministack/services/autoscaling.py
+++ b/ministack/services/autoscaling.py
@@ -19,8 +19,6 @@ Supports:
import copy
import logging
import os
-import time
-from collections import defaultdict
from ministack.core.persistence import load_state
from ministack.core.responses import (
diff --git a/ministack/services/batch.py b/ministack/services/batch.py
index 458fe6ab..9c8bdf80 100644
--- a/ministack/services/batch.py
+++ b/ministack/services/batch.py
@@ -173,6 +173,12 @@ def _create_compute_environment(p):
if name in _compute_envs:
return error_response_json("ClientException",
f"Object already exists: {name}", 400)
+ _batch_role = p.get("serviceRole", "")
+ if _batch_role:
+ from ministack.core.iam_evaluator import validate_role_arn
+ _batch_role_err = validate_role_arn(_batch_role)
+ if _batch_role_err:
+ return error_response_json("ClientException", _batch_role_err, 400)
rec = {
"computeEnvironmentName": name,
"computeEnvironmentArn": _ce_arn(name),
diff --git a/ministack/services/bedrock_runtime.py b/ministack/services/bedrock_runtime.py
index e2477aff..a07f8b57 100644
--- a/ministack/services/bedrock_runtime.py
+++ b/ministack/services/bedrock_runtime.py
@@ -38,7 +38,6 @@ import json
import logging
import os
import re
-import struct
import time
import urllib.error
import urllib.request
diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.py
index 113475ad..f92d7522 100644
--- a/ministack/services/cloudformation/changesets.py
+++ b/ministack/services/cloudformation/changesets.py
@@ -3,20 +3,18 @@ CloudFormation change set handlers — Create, Describe, Execute, Delete, List c
"""
import copy
-import json
import logging
from ministack.core.responses import get_account_id, get_region, new_uuid, now_iso
from .engine import (
- _NO_VALUE,
_apply_sam_transform_if_applicable,
_evaluate_conditions,
_parse_template,
_resolve_parameters,
_resolve_refs,
)
-from .helpers import CFN_NS, _error, _esc, _extract_members, _p, _resolve_template, _xml
+from .helpers import _error, _esc, _extract_members, _p, _resolve_template, _xml
from .stacks import (
_add_event,
_create_stack_task_in_region,
@@ -403,7 +401,7 @@ def _delete_change_set(params):
# --- ListChangeSets ---
def _list_change_sets(params):
- from ministack.services.cloudformation import _change_sets, _stacks
+ from ministack.services.cloudformation import _change_sets
stack_name = _p(params, "StackName")
if not stack_name:
return _error("ValidationError", "StackName is required")
diff --git a/ministack/services/cloudformation/engine.py b/ministack/services/cloudformation/engine.py
index cc4af767..3807cb43 100644
--- a/ministack/services/cloudformation/engine.py
+++ b/ministack/services/cloudformation/engine.py
@@ -10,12 +10,11 @@ import json
import logging
import os
import re
-from collections import defaultdict
from types import SimpleNamespace
import yaml
-from ministack.core.responses import get_account_id, get_region, new_uuid
+from ministack.core.responses import get_account_id, get_region
# Sentinel for AWS::NoValue
_NO_VALUE = object()
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index ec99d425..77def747 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -16,21 +16,17 @@ from .changesets import (
_list_change_sets,
)
from .engine import (
- _NO_VALUE,
_apply_sam_transform_if_applicable,
_evaluate_conditions,
_parse_template,
_resolve_parameters,
- _resolve_refs,
)
-from .helpers import CFN_NS, _error, _esc, _extract_members, _extract_stack_status_filters, _p, _resolve_template, _xml
-from .provisioners import _provision_resource
+from .helpers import _error, _esc, _extract_members, _extract_stack_status_filters, _p, _resolve_template, _xml
from .stacks import (
_add_event,
_create_stack_task_in_region,
_delete_stack_async,
_deploy_stack_async,
- _diff_resources,
_stack_region_context,
)
@@ -40,7 +36,7 @@ logger = logging.getLogger("cloudformation")
# --- CreateStack ---
def _create_stack(params):
- from ministack.services.cloudformation import _change_sets, _exports, _stack_events, _stacks
+ from ministack.services.cloudformation import _stack_events, _stacks
stack_name = _p(params, "StackName")
if not stack_name:
return _error("ValidationError", "StackName is required")
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 35513efc..45bc2436 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -3869,8 +3869,6 @@ def _ec2_vpc_endpoint_delete(physical_id, props):
def _ec2_subnet_create(logical_id, props, stack_name):
- import random
- import string
vpc_id = props.get("VpcId", "")
cidr = props.get("CidrBlock", "10.0.1.0/24")
az = props.get("AvailabilityZone", f"{get_region()}a")
diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.py
index d5959dce..c9368242 100644
--- a/ministack/services/cloudfront.py
+++ b/ministack/services/cloudfront.py
@@ -43,7 +43,6 @@ Supports:
import base64
import copy
import logging
-import os
import random
import re
import string
@@ -54,7 +53,7 @@ from xml.etree.ElementTree import Element, SubElement, tostring
from defusedxml.ElementTree import fromstring
from ministack.core.arn import ArnParseError, parse_arn
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid
logger = logging.getLogger("cloudfront")
diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.py
index 146eeab5..cd525760 100644
--- a/ministack/services/cloudwatch.py
+++ b/ministack/services/cloudwatch.py
@@ -21,7 +21,7 @@ from datetime import datetime, timezone
from urllib.parse import parse_qs
from ministack.core.arn import ArnParseError, parse_arn
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
from ministack.core.responses import AccountRegionScopedDict, AccountScopedDict, get_account_id, get_region, new_uuid
logger = logging.getLogger("cloudwatch")
diff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.py
index 5760708c..8cd4edb6 100644
--- a/ministack/services/cloudwatch_logs.py
+++ b/ministack/services/cloudwatch_logs.py
@@ -46,7 +46,7 @@ logger = logging.getLogger("logs")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
_log_groups = AccountRegionScopedDict()
# group_name -> {
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index d30d37db..81dc6d81 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -3802,12 +3802,19 @@ def _create_group(data):
return error_response_json("InvalidParameterException", "GroupName is required.", 400)
if name in pool["_groups"]:
return error_response_json("GroupExistsException", f"Group {name} already exists.", 400)
+ _cog_role_arn = data.get("RoleArn", "")
+ if _cog_role_arn:
+ from ministack.core.iam_evaluator import validate_role_arn
+ _cog_role_err = validate_role_arn(_cog_role_arn)
+ if _cog_role_err:
+ return error_response_json("InvalidParameterException", _cog_role_err, 400)
+
now = _now_epoch()
group = {
"GroupName": name,
"UserPoolId": pid,
"Description": data.get("Description", ""),
- "RoleArn": data.get("RoleArn", ""),
+ "RoleArn": _cog_role_arn,
"Precedence": data.get("Precedence", 0),
"CreationDate": now,
"LastModifiedDate": now,
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index 76d2cebe..ee0e679a 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -69,7 +69,7 @@ _DDB_ACCOUNT_RE = re.compile(r"^[0-9]{12}$")
_EXPORT_COMPLETE_AFTER_SEC = float(os.environ.get("MINISTACK_DDB_EXPORT_COMPLETE_AFTER_SEC", "1"))
_IMPORT_COMPLETE_AFTER_SEC = float(os.environ.get("MINISTACK_DDB_IMPORT_COMPLETE_AFTER_SEC", "1"))
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
# Region-scoped: DynamoDB tables are region-specific in AWS. Account-only
# keying made name lookups find cross-region tables while ARN ops (which
@@ -3168,7 +3168,6 @@ def _parse_partiql_conditions(where_str, parameters, param_idx):
def _split_top_level_by_and(s):
"""Split a WHERE string on AND at the top level (respecting parens/quotes)."""
- import re
# Use the existing _split_top_level approach but with AND as delimiter
parts = []
depth = 0
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index 4dedcb9a..6264cb6e 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -73,7 +73,7 @@ from xml.sax.saxutils import escape as _esc
from ministack.core import container_reaper
from ministack.core.concurrency import resource_lock, run_offloop
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
from ministack.core.responses import (
AccountRegionScopedDict,
AccountScopedDict,
diff --git a/ministack/services/ecr.py b/ministack/services/ecr.py
index bf3640cd..73beafa5 100644
--- a/ministack/services/ecr.py
+++ b/ministack/services/ecr.py
@@ -13,7 +13,7 @@ import re
import time
from ministack.core.arn import ArnParseError, parse_arn
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
from ministack.core.responses import (
AccountRegionScopedDict,
AccountScopedDict,
diff --git a/ministack/services/ecs.py b/ministack/services/ecs.py
index 209691fc..066489b0 100644
--- a/ministack/services/ecs.py
+++ b/ministack/services/ecs.py
@@ -545,6 +545,14 @@ def _register_task_definition(data):
compat = data.get("requiresCompatibilities", ["EC2"])
network_mode = data.get("networkMode", "awsvpc" if "FARGATE" in compat else "bridge")
+ from ministack.core.iam_evaluator import validate_role_arn
+ for _role_field in ("executionRoleArn", "taskRoleArn"):
+ _rv = data.get(_role_field, "")
+ if _rv:
+ _role_err = validate_role_arn(_rv)
+ if _role_err:
+ return error_response_json("ClientException", _role_err, 400)
+
td = {
"taskDefinitionArn": arn,
"family": family,
diff --git a/ministack/services/efs.py b/ministack/services/efs.py
index 0b5efffb..17244197 100644
--- a/ministack/services/efs.py
+++ b/ministack/services/efs.py
@@ -25,7 +25,7 @@ import string
import time
from ministack.core.arn import ArnParseError, parse_arn
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
from ministack.core.responses import (
AccountRegionScopedDict,
AccountScopedDict,
diff --git a/ministack/services/eks.py b/ministack/services/eks.py
index 90583428..d56ddfa3 100644
--- a/ministack/services/eks.py
+++ b/ministack/services/eks.py
@@ -566,6 +566,10 @@ def _create_cluster(body):
now = _now()
version = body.get("version", "1.30")
role_arn = body.get("roleArn", f"arn:aws:iam::{get_account_id()}:role/eks-role")
+ from ministack.core.iam_evaluator import validate_role_arn
+ role_err = validate_role_arn(role_arn)
+ if role_err:
+ return _error(400, "InvalidParameterException", role_err)
vpc_config = body.get("resourcesVpcConfig", {})
# Spawn k3s container
diff --git a/ministack/services/emr.py b/ministack/services/emr.py
index fe26bc25..f8f67941 100644
--- a/ministack/services/emr.py
+++ b/ministack/services/emr.py
@@ -22,7 +22,7 @@ import random
import string
import time
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
from ministack.core.responses import (
AccountRegionScopedDict,
AccountScopedDict,
@@ -30,7 +30,6 @@ from ministack.core.responses import (
get_account_id,
get_region,
json_response,
- new_uuid,
)
logger = logging.getLogger("emr")
diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.py
index 5c0c9447..c446222d 100644
--- a/ministack/services/eventbridge.py
+++ b/ministack/services/eventbridge.py
@@ -97,7 +97,7 @@ def _coerce_timestamp(value):
return value
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
# Per-account and per-region registries. The "default" bus is lazily created
# per account/region on first access so every tenant has its own default bus
diff --git a/ministack/services/firehose.py b/ministack/services/firehose.py
index 00299b05..41149415 100644
--- a/ministack/services/firehose.py
+++ b/ministack/services/firehose.py
@@ -656,9 +656,15 @@ def _create_delivery_stream(data: dict):
# Capture Kinesis source config for Source block in DescribeDeliveryStream
if stream_type == "KinesisStreamAsSource":
ks_cfg = data.get("KinesisStreamSourceConfiguration", {})
+ _fh_role = ks_cfg.get("RoleARN", "")
+ if _fh_role:
+ from ministack.core.iam_evaluator import validate_role_arn
+ _fh_role_err = validate_role_arn(_fh_role)
+ if _fh_role_err:
+ return _invalid(_fh_role_err)
stream["kinesis_source"] = {
"KinesisStreamARN": ks_cfg.get("KinesisStreamARN", ""),
- "RoleARN": ks_cfg.get("RoleARN", ""),
+ "RoleARN": _fh_role,
"DeliveryStartTimestamp": now,
}
diff --git a/ministack/services/glue.py b/ministack/services/glue.py
index a62402f7..fecf4b43 100644
--- a/ministack/services/glue.py
+++ b/ministack/services/glue.py
@@ -1098,11 +1098,18 @@ def _create_crawler(data):
name = data.get("Name")
if name in _crawlers:
return error_response_json("AlreadyExistsException", f"Crawler {name} already exists", 400)
+ _glue_role = data.get("Role", "")
+ if _glue_role:
+ from ministack.core.iam_evaluator import validate_role_arn
+ _glue_role_err = validate_role_arn(_glue_role)
+ if _glue_role_err:
+ return error_response_json("InvalidInputException", _glue_role_err, 400)
+
schedule = data.get("Schedule", "")
schedule_struct = {"ScheduleExpression": schedule} if schedule else {}
_crawlers[name] = {
"Name": name,
- "Role": data.get("Role", ""),
+ "Role": _glue_role,
"DatabaseName": data.get("DatabaseName", ""),
"Description": data.get("Description", ""),
"Targets": data.get("Targets", {}),
diff --git a/ministack/services/iam.py b/ministack/services/iam.py
index 491646ee..3c8ca8cf 100644
--- a/ministack/services/iam.py
+++ b/ministack/services/iam.py
@@ -42,7 +42,7 @@ from urllib.parse import parse_qs
from urllib.parse import quote as _url_quote
from xml.sax.saxutils import escape as _xml_escape
-from ministack.core.responses import AccountScopedDict, get_account_id, get_region, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, get_region, new_uuid
logger = logging.getLogger("iam")
@@ -51,7 +51,7 @@ REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# ---------------------------------------------------------------------------
# Module-level state
# ---------------------------------------------------------------------------
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
_users = AccountScopedDict()
_roles = AccountScopedDict()
@@ -634,6 +634,10 @@ def _create_policy(p):
return _error(409, "EntityAlreadyExists",
f"A policy called {name} already exists.", ns="iam")
doc = _p(p, "PolicyDocument")
+ from ministack.core.iam_evaluator import validate_policy_document
+ validation_err = validate_policy_document(doc)
+ if validation_err:
+ return _error(400, "MalformedPolicyDocument", validation_err, ns="iam")
description = _p(p, "Description", "")
# #445 (follow-up): CreatePolicy accepts Tags — honour them on create.
create_tags = _extract_tags(p)
@@ -727,6 +731,10 @@ def _create_policy_version(p):
return _error(409, "LimitExceeded",
"A managed policy can have at most 5 versions.", ns="iam")
doc = _p(p, "PolicyDocument")
+ from ministack.core.iam_evaluator import validate_policy_document
+ validation_err = validate_policy_document(doc)
+ if validation_err:
+ return _error(400, "MalformedPolicyDocument", validation_err, ns="iam")
set_default = _p(p, "SetAsDefault").lower() in ("true", "1") if _p(p, "SetAsDefault") else False
next_v = max((int(v.lstrip("v")) for v in pol["Versions"]), default=0) + 1
vid = f"v{next_v}"
@@ -919,6 +927,10 @@ def _put_role_policy(p):
role_name = _p(p, "RoleName")
policy_name = _p(p, "PolicyName")
policy_doc = _p(p, "PolicyDocument")
+ from ministack.core.iam_evaluator import validate_policy_document
+ validation_err = validate_policy_document(policy_doc)
+ if validation_err:
+ return _error(400, "MalformedPolicyDocument", validation_err, ns="iam")
role = _roles.get(role_name)
if not role:
return _error(404, "NoSuchEntity",
@@ -1399,10 +1411,30 @@ def _list_user_tags(p):
ns="iam")
-# -------------------- Simulate (stubs) --------------------
+# -------------------- Simulate --------------------
def _simulate_principal_policy(p):
- results = _build_simulate_results(p)
+ from ministack.core.responses import get_account_id
+ principal_arn = _p(p, "PolicySourceArn")
+ if not principal_arn:
+ return _error(400, "ValidationError",
+ "PolicySourceArn is required.", ns="iam")
+ actions, resource_arn = _extract_simulate_params(p)
+ account_id = get_account_id()
+ # Resolve the principal's policies
+ # Extract entity type and name from ARN
+ parts = principal_arn.split(":")
+ policies = []
+ if len(parts) >= 6:
+ resource = parts[5]
+ if resource.startswith("user/"):
+ from ministack.core.iam_evaluator import _gather_user_policies
+ policies = _gather_user_policies(resource.split("/", 1)[1], account_id)
+ elif resource.startswith("role/"):
+ from ministack.core.iam_evaluator import _gather_role_policies
+ policies = _gather_role_policies(resource.split("/", 1)[1], account_id)
+ results = _build_simulate_results_real(actions, resource_arn, principal_arn,
+ account_id, policies)
return _xml(200, "SimulatePrincipalPolicyResponse",
f"<SimulatePrincipalPolicyResult>"
f"<EvaluationResults>{results}</EvaluationResults>"
@@ -1412,7 +1444,24 @@ def _simulate_principal_policy(p):
def _simulate_custom_policy(p):
- results = _build_simulate_results(p)
+ from ministack.core.iam_evaluator import parse_policy_document
+ from ministack.core.responses import get_account_id
+ actions, resource_arn = _extract_simulate_params(p)
+ account_id = get_account_id()
+ # Parse the caller-supplied policy documents
+ policies = []
+ idx = 1
+ while True:
+ doc = _p(p, f"PolicyInputList.member.{idx}")
+ if not doc:
+ break
+ stmts = parse_policy_document(doc)
+ if stmts:
+ policies.append(stmts)
+ idx += 1
+ results = _build_simulate_results_real(
+ actions, resource_arn,
+ f"arn:aws:iam::{account_id}:root", account_id, policies)
return _xml(200, "SimulateCustomPolicyResponse",
f"<SimulateCustomPolicyResult>"
f"<EvaluationResults>{results}</EvaluationResults>"
@@ -1421,7 +1470,7 @@ def _simulate_custom_policy(p):
ns="iam")
-def _build_simulate_results(p):
+def _extract_simulate_params(p):
actions = []
idx = 1
while True:
@@ -1433,12 +1482,37 @@ def _build_simulate_results(p):
if not actions:
actions = ["sts:AssumeRole"]
resource_arn = _p(p, "ResourceArns.member.1") or "*"
+ return actions, resource_arn
+
+
+def _build_simulate_results_real(actions, resource_arn, principal_arn,
+ account_id, policies):
+ from ministack.core.iam_evaluator import EvalContext, evaluate
members = ""
for action in actions:
+ if policies:
+ ctx = EvalContext(
+ principal_arn=principal_arn,
+ principal_type="User",
+ principal_account=account_id,
+ action=action,
+ resource_arn=resource_arn,
+ region=get_region(),
+ )
+ result = evaluate(ctx, policies)
+ raw = result.decision
+ if raw == "Allow":
+ decision = "allowed"
+ elif raw == "Deny":
+ decision = "explicitDeny"
+ else:
+ decision = "implicitDeny"
+ else:
+ decision = "implicitDeny"
members += (f"<member>"
f"<EvalActionName>{action}</EvalActionName>"
f"<EvalResourceName>{resource_arn}</EvalResourceName>"
- f"<EvalDecision>allowed</EvalDecision>"
+ f"<EvalDecision>{decision}</EvalDecision>"
f"<MatchedStatements></MatchedStatements>"
f"<MissingContextValues></MissingContextValues>"
f"</member>")
@@ -1692,6 +1766,10 @@ def _put_user_policy(p):
user_name = _p(p, "UserName")
policy_name = _p(p, "PolicyName")
policy_doc = _p(p, "PolicyDocument")
+ from ministack.core.iam_evaluator import validate_policy_document
+ validation_err = validate_policy_document(policy_doc)
+ if validation_err:
+ return _error(400, "MalformedPolicyDocument", validation_err, ns="iam")
if user_name not in _users:
return _error(404, "NoSuchEntity",
f"The user with name {user_name} cannot be found.", ns="iam")
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index ae2eab3a..efba76b6 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -3288,6 +3288,18 @@ def put_topic_rule(name: str, payload: dict, *, created_at: float | None = None)
name,
func,
)
+ # Validate role ARNs in actions (AUTH=true only)
+ from ministack.core.iam_evaluator import validate_role_arn
+ for _iot_action in (payload.get("actions") or []):
+ if isinstance(_iot_action, dict):
+ for _act_cfg in _iot_action.values():
+ if isinstance(_act_cfg, dict) and "roleArn" in _act_cfg:
+ _iot_role_err = validate_role_arn(_act_cfg["roleArn"])
+ if _iot_role_err:
+ return error_response_json(
+ "InvalidRequestException",
+ f"Unable to assume role: {_act_cfg['roleArn']}", 400)
+
rule = {
"ruleName": name,
"sql": sql,
diff --git a/ministack/services/kinesis.py b/ministack/services/kinesis.py
index cd40edab..1dbd3a98 100644
--- a/ministack/services/kinesis.py
+++ b/ministack/services/kinesis.py
@@ -38,7 +38,7 @@ REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
MAX_HASH_KEY = (2**128) - 1
ITERATOR_EXPIRY_SECONDS = 300
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
_streams = AccountRegionScopedDict()
_shard_iterators = AccountRegionScopedDict()
diff --git a/ministack/services/kms.py b/ministack/services/kms.py
index e768d530..17ece896 100644
--- a/ministack/services/kms.py
+++ b/ministack/services/kms.py
@@ -45,7 +45,7 @@ except ImportError:
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
_keys = AccountRegionScopedDict()
# key_id -> {
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 1f3eea0a..193ddd3f 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -1297,11 +1297,17 @@ def _build_config(name: str, data: dict, code_zip: bytes | None = None) -> dict:
if env is not None and "Variables" not in env:
env["Variables"] = {}
+ role_arn = data.get("Role", f"arn:aws:iam::{get_account_id()}:role/lambda-role")
+ from ministack.core.iam_evaluator import validate_role_arn
+ role_err = validate_role_arn(role_arn)
+ if role_err:
+ return error_response_json("InvalidParameterValueException", role_err, 400)
+
config = {
"FunctionName": name,
"FunctionArn": _func_arn(name),
"Runtime": data.get("Runtime", "" if is_image else "python3.12"),
- "Role": data.get("Role", f"arn:aws:iam::{get_account_id()}:role/lambda-role"),
+ "Role": role_arn,
"Handler": data.get("Handler", "" if is_image else "index.handler"),
"CodeSize": code_size,
"CodeSha256": code_sha,
diff --git a/ministack/services/route53.py b/ministack/services/route53.py
index bb582310..785bbf63 100644
--- a/ministack/services/route53.py
+++ b/ministack/services/route53.py
@@ -29,7 +29,7 @@ from xml.etree.ElementTree import Element, SubElement, tostring
from defusedxml.ElementTree import fromstring
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
from ministack.core.responses import AccountScopedDict, new_uuid
logger = logging.getLogger("route53")
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 8ca78e47..a6220a43 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -47,7 +47,7 @@ from xml.sax.saxutils import escape as _esc
from defusedxml.ElementTree import fromstring
from ministack.core.arn import ArnParseError, parse_arn
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
from ministack.core.responses import (
AccountScopedDict,
get_account_id,
@@ -57,7 +57,6 @@ from ministack.core.responses import (
new_uuid,
now_iso,
set_request_region,
- sha256_hash,
)
logger = logging.getLogger("s3")
diff --git a/ministack/services/secretsmanager.py b/ministack/services/secretsmanager.py
index 0805723b..75fefa70 100644
--- a/ministack/services/secretsmanager.py
+++ b/ministack/services/secretsmanager.py
@@ -33,7 +33,7 @@ logger = logging.getLogger("secretsmanager")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
_secrets = AccountRegionScopedDict()
_resource_policies = AccountRegionScopedDict()
diff --git a/ministack/services/ses.py b/ministack/services/ses.py
index c8330d8e..52617dc8 100644
--- a/ministack/services/ses.py
+++ b/ministack/services/ses.py
@@ -28,7 +28,6 @@ import hashlib
import json
import logging
import os
-import re
import smtplib
import time
from datetime import datetime, timezone
@@ -38,11 +37,10 @@ from email.mime.text import MIMEText
from email.policy import default as default_policy
from urllib.parse import parse_qs, unquote
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
from ministack.core.responses import (
AccountRegionScopedDict,
AccountScopedDict,
- get_account_id,
get_region,
new_uuid,
)
diff --git a/ministack/services/ses_v2.py b/ministack/services/ses_v2.py
index ee8069d3..945c3a79 100644
--- a/ministack/services/ses_v2.py
+++ b/ministack/services/ses_v2.py
@@ -20,7 +20,7 @@ import re
import time
from ministack.core.arn import ArnParseError, parse_arn
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
from ministack.core.responses import (
AccountRegionScopedDict,
AccountScopedDict,
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index 9086074e..ee780725 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -118,7 +118,7 @@ def _resolve_topic_tag_arn(arn: str):
return arn, None, _error("ResourceNotFoundException", "Resource not found", 404)
return arn, topic, None
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
_topics = AccountRegionScopedDict()
_sub_arn_to_topic = AccountRegionScopedDict()
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index 4716b5aa..973b6f59 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -37,8 +37,8 @@ from urllib.parse import parse_qs, urlparse
from xml.sax.saxutils import escape as _esc
from ministack.core.arn import ArnParseError, parse_arn
-from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import AccountRegionScopedDict, get_account_id, get_region, md5_hash, new_uuid, now_iso
+from ministack.core.persistence import load_state
+from ministack.core.responses import AccountRegionScopedDict, get_account_id, get_region, new_uuid
logger = logging.getLogger("sqs")
diff --git a/ministack/services/ssm.py b/ministack/services/ssm.py
index b04ab637..ba6b3159 100644
--- a/ministack/services/ssm.py
+++ b/ministack/services/ssm.py
@@ -14,7 +14,6 @@ import copy
import json
import logging
import os
-import time
from datetime import datetime, timezone
from ministack.core.arn import ArnParseError, parse_arn
@@ -34,7 +33,7 @@ logger = logging.getLogger("ssm")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
DEFAULT_PAGE_SIZE = 10
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
_parameters = AccountRegionScopedDict()
_parameter_history = AccountRegionScopedDict()
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index da11e1d7..e41ea94b 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -320,13 +320,19 @@ def _create_state_machine(data):
"StateMachineAlreadyExists",
f"State machine {name} already exists", 400)
+ role_arn = data.get("roleArn",
+ f"arn:aws:iam::{get_account_id()}:role/StepFunctionsRole")
+ from ministack.core.iam_evaluator import validate_role_arn
+ role_err = validate_role_arn(role_arn)
+ if role_err:
+ return error_response_json("ValidationException", role_err, 400)
+
ts = now_iso()
_state_machines[arn] = {
"stateMachineArn": arn,
"name": name,
"definition": data.get("definition", "{}"),
- "roleArn": data.get("roleArn",
- f"arn:aws:iam::{get_account_id()}:role/StepFunctionsRole"),
+ "roleArn": role_arn,
"type": data.get("type", "STANDARD"),
"creationDate": ts,
"status": "ACTIVE",
diff --git a/ministack/services/sts.py b/ministack/services/sts.py
index 165f7489..e963d005 100644
--- a/ministack/services/sts.py
+++ b/ministack/services/sts.py
@@ -15,6 +15,7 @@ from urllib.parse import parse_qs
from ministack.core.arn import ArnParseError, parse_arn
from ministack.core.responses import get_account_id, json_response, new_uuid
+from ministack.core.router import extract_access_key_id
# Shared helpers — IAM and STS are a natural pair; STS is stateless
# and reuses IAM's XML builders and credential generators.
@@ -105,14 +106,46 @@ async def handle_request(method, path, headers, body, query_params):
assumed_arn, validation_error = _assumed_role_arn(role_arn, session_name)
if validation_error:
return validation_error
+
+ # When AUTH=true, validate role exists and trust policy permits the caller
+ from ministack.app import AUTH
+ if AUTH:
+ from ministack.core.iam_evaluator import evaluate_trust_policy
+ from ministack.services import iam as iam_svc
+ # Extract role name from ARN
+ role_name = role_arn.split("/")[-1] if "/" in role_arn else ""
+ role = iam_svc._roles.get(role_name)
+ if role is None:
+ return _error(403, "AccessDenied",
+ f"User: is not authorized to perform: sts:AssumeRole on resource: {role_arn}",
+ ns="sts")
+ # Evaluate trust policy
+ trust_doc = role.get("AssumeRolePolicyDocument", "{}")
+ caller_key = extract_access_key_id(headers)
+ caller_arn = f"arn:aws:iam::{get_account_id()}:root"
+ if caller_key in _sessions:
+ caller_arn = _sessions[caller_key].get("Arn", caller_arn)
+ else:
+ key_record = iam_svc._access_keys.get(caller_key)
+ if key_record:
+ caller_arn = f"arn:aws:iam::{get_account_id()}:user/{key_record['UserName']}"
+ if not evaluate_trust_policy(trust_doc, caller_arn):
+ return _error(403, "AccessDenied",
+ f"User: {caller_arn} is not authorized to perform: "
+ f"sts:AssumeRole on resource: {role_arn}", ns="sts")
+
duration = int(_p(params, "DurationSeconds") or 3600)
expiration = _future(duration)
access_key = _gen_session_access_key()
secret_key = _gen_secret()
session_token = _gen_session_token()
role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()
- _sessions[access_key] = {"Arn": assumed_arn, "UserId": f"{role_id}:{session_name}"}
- _sessions[access_key]["SecretAccessKey"] = secret_key
+ _sessions[access_key] = {
+ "Arn": assumed_arn,
+ "UserId": f"{role_id}:{session_name}",
+ "SecretAccessKey": secret_key,
+ "Expiration": time.time() + duration,
+ }
if use_json:
return json_response({
"Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": int(time.time() + duration)},
@@ -146,8 +179,12 @@ async def handle_request(method, path, headers, body, query_params):
secret_key = _gen_secret()
session_token = _gen_session_token()
role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()
- _sessions[access_key] = {"Arn": assumed_arn, "UserId": f"{role_id}:{session}"}
- _sessions[access_key]["SecretAccessKey"] = secret_key
+ _sessions[access_key] = {
+ "Arn": assumed_arn,
+ "UserId": f"{role_id}:{session}",
+ "SecretAccessKey": secret_key,
+ "Expiration": time.time() + duration,
+ }
provider = _p(params, "ProviderId") or "sts.amazonaws.com"
if use_json:
return json_response({
diff --git a/ministack/services/waf.py b/ministack/services/waf.py
index 29dc731a..924fdc87 100644
--- a/ministack/services/waf.py
+++ b/ministack/services/waf.py
@@ -15,7 +15,7 @@ import logging
import os
from ministack.core.arn import ArnParseError, parse_arn
-from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.persistence import load_state
from ministack.core.responses import (
AccountRegionScopedDict,
AccountScopedDict,
@@ -24,7 +24,6 @@ from ministack.core.responses import (
get_region,
json_response,
new_uuid,
- now_iso,
)
logger = logging.getLogger("wafv2")
diff --git a/pyproject.toml b/pyproject.toml
index c0438e59..cc5c59fc 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -26,6 +26,12 @@ dependencies = [
"hypercorn>=0.18.0",
"pyyaml>=6.0",
"defusedxml>=0.7",
+ # IAM enforcement reads request/response shapes out of botocore's service
+ # models to map a wire request to its IAM action. Without it that lookup
+ # finds nothing and AUTH=true would allow what it cannot classify, so this
+ # is a runtime dependency rather than a dev one. Pinned to the version the
+ # images already carry: awscli==1.45.63 requires botocore==1.43.63.
+ "botocore==1.43.63",
]
[project.optional-dependencies]
diff --git a/requirements.txt b/requirements.txt
index 4d745365..48fed913 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,3 +1,6 @@
hypercorn==0.18.0
docker>=7.0.0
cbor2>=5.4.0
+# Pinned to the version the images carry (awscli==1.45.63 requires it), so a
+# pip install and a Docker run classify requests against identical service models.
+botocore==1.43.63
diff --git a/tests/test_acm.py b/tests/test_acm.py
index c0c871c6..4854217d 100644
--- a/tests/test_acm.py
+++ b/tests/test_acm.py
@@ -1,13 +1,7 @@
-import io
import json
import os
-import time
-import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import pytest
-from botocore.exceptions import ClientError
def test_acm_request_certificate(acm_client):
diff --git a/tests/test_alb.py b/tests/test_alb.py
index dc5fdcb1..07175ebc 100644
--- a/tests/test_alb.py
+++ b/tests/test_alb.py
@@ -531,7 +531,6 @@ def test_elbv2_dataplane_lambda_target_emits_metrics(elbv2, lam, cw):
def test_elbv2_dataplane_event_shape(elbv2, lam):
"""ALB event passed to Lambda contains all required fields."""
- import urllib.parse as _parse
import urllib.request as _req
fn_code = (
@@ -560,7 +559,6 @@ def test_elbv2_dataplane_event_shape(elbv2, lam):
def test_elbv2_dataplane_fixed_response(elbv2, lam):
"""ALB fixed-response action returns configured status/body without invoking Lambda."""
- import urllib.error as _err
import urllib.request as _req
fn_code = "def handler(event, context):\n return {'statusCode': 200, 'body': 'should-not-reach'}\n"
diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.py
index d3d20464..0ca9721c 100644
--- a/tests/test_apigatewayv2.py
+++ b/tests/test_apigatewayv2.py
@@ -607,7 +607,6 @@ def test_apigw_http_protocol_type(apigw):
def test_apigw_execute_lambda_proxy(apigw, lam):
"""API Gateway execute-api routes a request through Lambda proxy integration."""
- import urllib.error as _urlerr
import urllib.request as _urlreq
import uuid as _uuid
@@ -2935,7 +2934,6 @@ def test_apigwv2_path_based_websocket(apigw, lam):
def test_ws_connect_jwt_authorizer_rejects_missing_token(apigw, lam, cognito_idp):
"""$connect with a JWT authorizer rejects connections that lack a valid token (#1074)."""
- from ministack.services import cognito as _cognito
pool_id = cognito_idp.create_user_pool(PoolName=f"ws-jwt-{_uuid_mod.uuid4().hex[:8]}")["UserPool"]["Id"]
issuer = f"https://cognito-idp.us-east-1.amazonaws.com/{pool_id}"
diff --git a/tests/test_appsync.py b/tests/test_appsync.py
index d8acc4cc..7009c61c 100644
--- a/tests/test_appsync.py
+++ b/tests/test_appsync.py
@@ -1,7 +1,6 @@
import io
import json
import os
-import time
import urllib.request
import uuid as _uuid_mod
import zipfile
diff --git a/tests/test_athena.py b/tests/test_athena.py
index 606287d8..03db2ec2 100644
--- a/tests/test_athena.py
+++ b/tests/test_athena.py
@@ -1,10 +1,7 @@
-import io
import json
import os
import time
import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import boto3
import pytest
diff --git a/tests/test_bedrock.py b/tests/test_bedrock.py
index 9730825f..67efff1e 100644
--- a/tests/test_bedrock.py
+++ b/tests/test_bedrock.py
@@ -736,7 +736,6 @@ def test_bedrock_invoke_model_rejects_empty_body():
def test_bedrock_invoke_model_with_response_stream_anthropic_envelope():
- import base64
client = make_client("bedrock-runtime")
resp = client.invoke_model_with_response_stream(
diff --git a/tests/test_cloudfront.py b/tests/test_cloudfront.py
index 563cc239..e6766fcf 100644
--- a/tests/test_cloudfront.py
+++ b/tests/test_cloudfront.py
@@ -1,5 +1,4 @@
import copy
-import io
import json
import os
import time
@@ -7,8 +6,6 @@ import urllib.error
import urllib.parse
import urllib.request
import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import pytest
from botocore.exceptions import ClientError
diff --git a/tests/test_cloudtrail.py b/tests/test_cloudtrail.py
index 170e436b..7408b469 100644
--- a/tests/test_cloudtrail.py
+++ b/tests/test_cloudtrail.py
@@ -13,7 +13,6 @@ Tests are split into two sections:
import json
import os
-import time
from datetime import datetime, timedelta, timezone
import boto3
diff --git a/tests/test_cloudwatch.py b/tests/test_cloudwatch.py
index 86e3bf08..c650b9a9 100644
--- a/tests/test_cloudwatch.py
+++ b/tests/test_cloudwatch.py
@@ -1,10 +1,6 @@
-import io
import json
-import os
import time
import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import pytest
from botocore.exceptions import ClientError
diff --git a/tests/test_cloudwatch_logs.py b/tests/test_cloudwatch_logs.py
index 96f7bcd0..ba1932c1 100644
--- a/tests/test_cloudwatch_logs.py
+++ b/tests/test_cloudwatch_logs.py
@@ -1,10 +1,7 @@
-import io
import json
import os
import time
import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import boto3
import pytest
diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.py
index 835cfec0..bf1e920c 100644
--- a/tests/test_dynamodb.py
+++ b/tests/test_dynamodb.py
@@ -4,7 +4,6 @@ import os
import time
import uuid as _uuid_mod
import zipfile
-from urllib.parse import urlparse
import boto3
import pytest
diff --git a/tests/test_ec2.py b/tests/test_ec2.py
index 83548fc1..4110dfb9 100644
--- a/tests/test_ec2.py
+++ b/tests/test_ec2.py
@@ -1,4 +1,3 @@
-import io
import ipaddress
import json
import os
@@ -6,8 +5,7 @@ import time
import urllib.error
import urllib.request
import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlencode, urlparse
+from urllib.parse import urlencode
import boto3
import pytest
diff --git a/tests/test_ecr.py b/tests/test_ecr.py
index 1da913a6..fb998556 100644
--- a/tests/test_ecr.py
+++ b/tests/test_ecr.py
@@ -1,11 +1,7 @@
import hashlib
-import io
import json
import os
-import time
import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import boto3
import pytest
diff --git a/tests/test_efs.py b/tests/test_efs.py
index d5b03468..b8398174 100644
--- a/tests/test_efs.py
+++ b/tests/test_efs.py
@@ -1,10 +1,5 @@
-import io
-import json
import os
-import time
import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import boto3
import pytest
diff --git a/tests/test_elasticache.py b/tests/test_elasticache.py
index a27cb590..2afff868 100644
--- a/tests/test_elasticache.py
+++ b/tests/test_elasticache.py
@@ -4,7 +4,6 @@ import os
import time
import uuid as _uuid_mod
import zipfile
-from urllib.parse import urlparse
import boto3
import pytest
diff --git a/tests/test_emr.py b/tests/test_emr.py
index e99adcb3..ce3bfc4c 100644
--- a/tests/test_emr.py
+++ b/tests/test_emr.py
@@ -1,15 +1,7 @@
-import io
-import json
import os
-import time
-import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import boto3
-import pytest
from botocore.config import Config
-from botocore.exceptions import ClientError
def _emr_client(region):
diff --git a/tests/test_eventbridge.py b/tests/test_eventbridge.py
index cf0e091b..ef4127f1 100644
--- a/tests/test_eventbridge.py
+++ b/tests/test_eventbridge.py
@@ -4,7 +4,6 @@ import os
import time
import uuid as _uuid_mod
import zipfile
-from urllib.parse import urlparse
import boto3
import pytest
@@ -2255,7 +2254,6 @@ def _seed_rule(schedule="rate(1 minute)", state="ENABLED", region=_REGION):
return state_key
-from unittest.mock import patch as _patch
def test_scheduler_first_sight_initializes_countdown(isolated_scheduler):
diff --git a/tests/test_firehose.py b/tests/test_firehose.py
index 7f2c18b7..267e7b73 100644
--- a/tests/test_firehose.py
+++ b/tests/test_firehose.py
@@ -380,7 +380,6 @@ def test_firehose_update_destination_rejects_invalid_s3_bucket_arn(fh):
def test_firehose_s3_destination_writes(s3, fh):
"""PutRecord with S3 destination actually writes data to the S3 bucket."""
- import base64
import time as _time
bucket = "fh-s3-dest-v39"
s3.create_bucket(Bucket=bucket)
@@ -543,7 +542,6 @@ def _create_firehose_with_processor(fh, name: str, bucket: str, lambda_arn: str,
def test_firehose_lambda_processor_transforms_record(fh, s3, lam):
"""Lambda processor returns transformed data → S3 object contains the
transform output, not the original record."""
- import base64 as _b64
suffix = _uuid_mod.uuid4().hex[:8]
bucket = f"fh-proc-{suffix}"
fn = f"fh-proc-fn-{suffix}"
diff --git a/tests/test_glue.py b/tests/test_glue.py
index f57f2915..44bb4e23 100644
--- a/tests/test_glue.py
+++ b/tests/test_glue.py
@@ -1,13 +1,9 @@
import asyncio
import importlib
-import io
import json
import os
import threading
import time
-import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import boto3
import pytest
diff --git a/tests/test_health.py b/tests/test_health.py
index e4f2c713..ab65145b 100644
--- a/tests/test_health.py
+++ b/tests/test_health.py
@@ -1,13 +1,6 @@
-import io
import json
import os
-import time
-import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
-import pytest
-from botocore.exceptions import ClientError
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
diff --git a/tests/test_iam.py b/tests/test_iam.py
index 17b59221..a1866453 100644
--- a/tests/test_iam.py
+++ b/tests/test_iam.py
@@ -1,10 +1,5 @@
-import io
import json
-import os
-import time
import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import pytest
from botocore.exceptions import ClientError
@@ -638,7 +633,7 @@ def test_iam_instance_profile_tags_serialized_in_get(iam):
def test_iam_attach_detach_user_policy(iam):
"""AttachUserPolicy / DetachUserPolicy / ListAttachedUserPolicies."""
iam.create_user(UserName="qa-iam-attach-user")
- doc = json.dumps({"Version": "2012-10-17", "Statement": []})
+ doc = json.dumps({"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]})
policy_arn = iam.create_policy(PolicyName="qa-iam-attach-pol", PolicyDocument=doc)["Policy"]["Arn"]
iam.attach_user_policy(UserName="qa-iam-attach-user", PolicyArn=policy_arn)
attached = iam.list_attached_user_policies(UserName="qa-iam-attach-user")["AttachedPolicies"]
@@ -649,7 +644,7 @@ def test_iam_attach_detach_user_policy(iam):
def test_iam_list_entities_for_policy(iam):
"""ListEntitiesForPolicy returns users and roles attached to a policy."""
- doc = json.dumps({"Version": "2012-10-17", "Statement": []})
+ doc = json.dumps({"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]})
assume = json.dumps({"Version": "2012-10-17", "Statement": []})
policy_arn = iam.create_policy(PolicyName="qa-entities-pol", PolicyDocument=doc)["Policy"]["Arn"]
iam.create_user(UserName="qa-entities-user")
@@ -976,7 +971,7 @@ def test_iam_list_oidc_providers(iam):
def test_iam_account_authorization_details_all(iam):
- policy_doc = json.dumps({"Version": "2012-10-17", "Statement": []})
+ policy_doc = json.dumps({"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]})
assume_doc = json.dumps({"Version": "2012-10-17", "Statement": []})
pol = iam.create_policy(PolicyName="aad-test-policy", PolicyDocument=policy_doc)
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
new file mode 100644
index 00000000..fe67053d
--- /dev/null
+++ b/tests/test_iam_auth.py
@@ -0,0 +1,1124 @@
+"""Tests for the IAM authentication and authorization engine.
+
+Unit tests verify the policy evaluator against AWS-documented behavior:
+ - AWS IAM policy evaluation logic (deny overrides allow, implicit deny)
+ - AWS condition operator semantics (per IAM JSON policy elements reference)
+ - AWS trust policy Principal matching
+ - AWS error codes (per STS/IAM Common Errors reference)
+
+Integration tests (SimulateCustomPolicy, policy validation) run against
+the MiniStack server and work with AUTH=false.
+"""
+
+import json
+import time
+
+import pytest
+from botocore.exceptions import ClientError
+
+from ministack.core.iam_evaluator import (
+ AuthError,
+ EvalContext,
+ EvalResult,
+ PrincipalInfo,
+ evaluate,
+ evaluate_trust_policy,
+ enforce,
+ fnmatch_iam,
+ parse_policy_document,
+ resolve_principal,
+ validate_policy_document,
+)
+
+
+# ---------------------------------------------------------------------------
+# Wildcard matching (IAM spec: case-insensitive, * = any, ? = single char)
+# ---------------------------------------------------------------------------
+
+class TestFnmatchIam:
+ def test_star_matches_everything(self):
+ assert fnmatch_iam("s3:PutObject", "*")
+
+ def test_service_wildcard(self):
+ assert fnmatch_iam("s3:PutObject", "s3:*")
+
+ def test_prefix_wildcard(self):
+ assert fnmatch_iam("s3:PutObject", "s3:Put*")
+
+ def test_no_match(self):
+ assert not fnmatch_iam("s3:PutObject", "s3:Get*")
+
+ def test_exact_match(self):
+ assert fnmatch_iam("s3:PutObject", "s3:PutObject")
+
+ def test_case_insensitive(self):
+ # AWS IAM: action matching is case-insensitive
+ assert fnmatch_iam("s3:PutObject", "s3:putobject")
+ assert fnmatch_iam("S3:PUTOBJECT", "s3:PutObject")
+
+ def test_question_mark_single_char(self):
+ assert fnmatch_iam("s3:GetObject", "s3:Get?bject")
+ assert not fnmatch_iam("s3:GetObject", "s3:Get?ject")
+
+ def test_arn_wildcard(self):
+ assert fnmatch_iam("arn:aws:s3:::mybucket/mykey", "arn:aws:s3:::mybucket/*")
+ assert not fnmatch_iam("arn:aws:s3:::otherbucket/mykey", "arn:aws:s3:::mybucket/*")
+
+ def test_empty_pattern_matches_empty(self):
+ assert fnmatch_iam("", "")
+ assert not fnmatch_iam("something", "")
+
+
+# ---------------------------------------------------------------------------
+# Policy parsing
+# ---------------------------------------------------------------------------
+
+class TestParsePolicyDocument:
+ def test_basic_allow(self):
+ doc = {"Version": "2012-10-17",
+ "Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]}
+ stmts = parse_policy_document(doc)
+ assert len(stmts) == 1
+ assert stmts[0].effect == "Allow"
+ assert stmts[0].actions == ["s3:*"]
+
+ def test_multiple_actions_as_list(self):
+ doc = {"Statement": [{"Effect": "Allow",
+ "Action": ["s3:Get*", "s3:List*"], "Resource": "*"}]}
+ stmts = parse_policy_document(doc)
+ assert stmts[0].actions == ["s3:Get*", "s3:List*"]
+
+ def test_not_action(self):
+ doc = {"Statement": [{"Effect": "Allow", "NotAction": "iam:*", "Resource": "*"}]}
+ stmts = parse_policy_document(doc)
+ assert stmts[0].not_actions == ["iam:*"]
+ assert stmts[0].actions == []
+
+ def test_string_json_input(self):
+ stmts = parse_policy_document(
+ json.dumps({"Statement": [{"Effect": "Allow", "Action": "*", "Resource": "*"}]}))
+ assert len(stmts) == 1
+
+ def test_invalid_json_returns_empty(self):
+ assert parse_policy_document("not json") == []
+
+ def test_invalid_effect_skipped(self):
+ doc = {"Statement": [{"Effect": "Maybe", "Action": "*", "Resource": "*"}]}
+ assert parse_policy_document(doc) == []
+
+ def test_single_statement_dict_not_list(self):
+ doc = {"Statement": {"Effect": "Allow", "Action": "*", "Resource": "*"}}
+ assert len(parse_policy_document(doc)) == 1
+
+
+# ---------------------------------------------------------------------------
+# Policy validation (matches AWS MalformedPolicyDocument errors)
+# ---------------------------------------------------------------------------
+
+class TestValidatePolicyDocument:
+ def test_valid_policy(self):
+ assert validate_policy_document(
+ {"Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]}) is None
+
+ def test_missing_statement(self):
+ assert validate_policy_document({}) is not None
+
+ def test_empty_statement_list(self):
+ assert validate_policy_document({"Statement": []}) is not None
+
+ def test_invalid_effect(self):
+ assert validate_policy_document(
+ {"Statement": [{"Effect": "Maybe", "Action": "s3:*", "Resource": "*"}]}) is not None
+
+ def test_missing_action(self):
+ assert validate_policy_document(
+ {"Statement": [{"Effect": "Allow", "Resource": "*"}]}) is not None
+
+ def test_missing_resource(self):
+ assert validate_policy_document(
+ {"Statement": [{"Effect": "Allow", "Action": "s3:*"}]}) is not None
+
+ def test_both_action_and_not_action(self):
+ assert validate_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "s3:*", "NotAction": "iam:*", "Resource": "*"
+ }]}) is not None
+
+ def test_both_resource_and_not_resource(self):
+ assert validate_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "*", "Resource": "*", "NotResource": "arn:aws:s3:::x"
+ }]}) is not None
+
+
+# ---------------------------------------------------------------------------
+# Policy evaluation (per AWS evaluation logic documentation)
+# ---------------------------------------------------------------------------
+
+def _ctx(action="s3:PutObject", resource="*", region="us-east-1"):
+ return EvalContext(
+ principal_arn="arn:aws:iam::000000000000:user/testuser",
+ principal_type="User",
+ principal_account="000000000000",
+ action=action, resource_arn=resource, region=region,
+ )
+
+
+class TestEvaluate:
+ def test_explicit_allow(self):
+ stmts = parse_policy_document(
+ {"Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]})
+ assert evaluate(_ctx(), [stmts]).decision == "Allow"
+
+ def test_implicit_deny_no_matching_allow(self):
+ """AWS: by default all requests are implicitly denied."""
+ stmts = parse_policy_document(
+ {"Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]})
+ assert evaluate(_ctx(action="ec2:RunInstances"), [stmts]).decision == "ImplicitDeny"
+
+ def test_explicit_deny_overrides_allow(self):
+ """AWS: an explicit deny always overrides an explicit allow."""
+ stmts = parse_policy_document({"Statement": [
+ {"Effect": "Allow", "Action": "s3:*", "Resource": "*"},
+ {"Effect": "Deny", "Action": "s3:DeleteBucket", "Resource": "*"},
+ ]})
+ assert evaluate(_ctx(action="s3:DeleteBucket"), [stmts]).decision == "Deny"
+ assert evaluate(_ctx(action="s3:PutObject"), [stmts]).decision == "Allow"
+
+ def test_not_action_excludes_specified(self):
+ stmts = parse_policy_document(
+ {"Statement": [{"Effect": "Allow", "NotAction": "iam:*", "Resource": "*"}]})
+ assert evaluate(_ctx(action="s3:PutObject"), [stmts]).decision == "Allow"
+ assert evaluate(_ctx(action="iam:CreateUser"), [stmts]).decision == "ImplicitDeny"
+
+ def test_not_resource_excludes_specified(self):
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "s3:*",
+ "NotResource": "arn:aws:s3:::secret-bucket/*"
+ }]})
+ assert evaluate(_ctx(resource="arn:aws:s3:::public/key"), [stmts]).decision == "Allow"
+ assert evaluate(_ctx(resource="arn:aws:s3:::secret-bucket/key"), [stmts]).decision == "ImplicitDeny"
+
+ def test_multiple_policies_union(self):
+ """AWS: identity-based policies are unioned."""
+ p1 = parse_policy_document(
+ {"Statement": [{"Effect": "Allow", "Action": "s3:Get*", "Resource": "*"}]})
+ p2 = parse_policy_document(
+ {"Statement": [{"Effect": "Allow", "Action": "s3:Put*", "Resource": "*"}]})
+ assert evaluate(_ctx(action="s3:PutObject"), [p1, p2]).decision == "Allow"
+ assert evaluate(_ctx(action="s3:GetObject"), [p1, p2]).decision == "Allow"
+ assert evaluate(_ctx(action="s3:DeleteObject"), [p1, p2]).decision == "ImplicitDeny"
+
+ def test_empty_policies_implicit_deny(self):
+ assert evaluate(_ctx(), []).decision == "ImplicitDeny"
+
+ def test_admin_policy_allows_everything(self):
+ stmts = parse_policy_document(
+ {"Statement": [{"Effect": "Allow", "Action": "*", "Resource": "*"}]})
+ assert evaluate(_ctx(action="iam:CreateUser"), [stmts]).decision == "Allow"
+ assert evaluate(_ctx(action="ec2:RunInstances"), [stmts]).decision == "Allow"
+
+ def test_deny_in_one_policy_overrides_allow_in_another(self):
+ """AWS: explicit deny in ANY policy overrides allow in ANY other."""
+ allow = parse_policy_document(
+ {"Statement": [{"Effect": "Allow", "Action": "*", "Resource": "*"}]})
+ deny = parse_policy_document(
+ {"Statement": [{"Effect": "Deny", "Action": "s3:Delete*", "Resource": "*"}]})
+ assert evaluate(_ctx(action="s3:DeleteBucket"), [allow, deny]).decision == "Deny"
+ assert evaluate(_ctx(action="s3:PutObject"), [allow, deny]).decision == "Allow"
+
+
+# ---------------------------------------------------------------------------
+# Condition operators (per IAM condition operators reference)
+# ---------------------------------------------------------------------------
+
+class TestConditions:
+ def test_string_equals(self):
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "s3:*", "Resource": "*",
+ "Condition": {"StringEquals": {"aws:RequestedRegion": "us-east-1"}}
+ }]})
+ assert evaluate(_ctx(region="us-east-1"), [stmts]).decision == "Allow"
+ assert evaluate(_ctx(region="eu-west-1"), [stmts]).decision == "ImplicitDeny"
+
+ def test_string_like_with_wildcard(self):
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "s3:*", "Resource": "*",
+ "Condition": {"StringLike": {"aws:RequestedRegion": "us-*"}}
+ }]})
+ assert evaluate(_ctx(region="us-east-1"), [stmts]).decision == "Allow"
+ assert evaluate(_ctx(region="us-west-2"), [stmts]).decision == "Allow"
+ assert evaluate(_ctx(region="eu-west-1"), [stmts]).decision == "ImplicitDeny"
+
+ def test_string_not_equals_on_deny(self):
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Deny", "Action": "s3:*", "Resource": "*",
+ "Condition": {"StringNotEquals": {"aws:RequestedRegion": "us-east-1"}}
+ }]})
+ assert evaluate(_ctx(region="eu-west-1"), [stmts]).decision == "Deny"
+ assert evaluate(_ctx(region="us-east-1"), [stmts]).decision == "ImplicitDeny"
+
+ def test_string_equals_ignore_case(self):
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "*", "Resource": "*",
+ "Condition": {"StringEqualsIgnoreCase": {"aws:RequestedRegion": "US-EAST-1"}}
+ }]})
+ assert evaluate(_ctx(region="us-east-1"), [stmts]).decision == "Allow"
+
+ def test_ip_address_cidr(self):
+ """AWS: IpAddress checks if IP is in CIDR range."""
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "*", "Resource": "*",
+ "Condition": {"IpAddress": {"aws:SourceIp": "127.0.0.0/8"}}
+ }]})
+ assert evaluate(_ctx(), [stmts]).decision == "Allow"
+
+ def test_not_ip_address(self):
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Deny", "Action": "*", "Resource": "*",
+ "Condition": {"NotIpAddress": {"aws:SourceIp": "127.0.0.0/8"}}
+ }]})
+ # Default source_ip is 127.0.0.1, which IS in 127.0.0.0/8
+ # So NotIpAddress is false → condition not met → deny not applied
+ assert evaluate(_ctx(), [stmts]).decision == "ImplicitDeny"
+
+ def test_bool_condition(self):
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Deny", "Action": "*", "Resource": "*",
+ "Condition": {"Bool": {"aws:SecureTransport": "true"}}
+ }]})
+ # secure_transport defaults to false → condition not met
+ assert evaluate(_ctx(), [stmts]).decision == "ImplicitDeny"
+
+ def test_null_key_present(self):
+ """AWS: Null:false = key must exist. PrincipalArn always exists."""
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Deny", "Action": "*", "Resource": "*",
+ "Condition": {"Null": {"aws:PrincipalArn": "false"}}
+ }]})
+ assert evaluate(_ctx(), [stmts]).decision == "Deny"
+
+ def test_null_key_absent(self):
+ """AWS: Null:true = key must NOT exist."""
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "*", "Resource": "*",
+ "Condition": {"Null": {"aws:SourceVpc": "true"}}
+ }]})
+ # SourceVpc not in our context → absent → Null:true matches
+ assert evaluate(_ctx(), [stmts]).decision == "Allow"
+
+ def test_arn_like(self):
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "*", "Resource": "*",
+ "Condition": {"ArnLike": {
+ "aws:PrincipalArn": "arn:aws:iam::000000000000:user/*"
+ }}
+ }]})
+ assert evaluate(_ctx(), [stmts]).decision == "Allow"
+
+ def test_multiple_values_are_ored(self):
+ """AWS: multiple values for a condition key are OR'd."""
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "s3:*", "Resource": "*",
+ "Condition": {"StringEquals": {
+ "aws:RequestedRegion": ["us-east-1", "us-west-2"]
+ }}
+ }]})
+ assert evaluate(_ctx(region="us-east-1"), [stmts]).decision == "Allow"
+ assert evaluate(_ctx(region="us-west-2"), [stmts]).decision == "Allow"
+ assert evaluate(_ctx(region="eu-west-1"), [stmts]).decision == "ImplicitDeny"
+
+ def test_multiple_operators_are_anded(self):
+ """AWS: multiple condition blocks are AND'd."""
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "s3:*", "Resource": "*",
+ "Condition": {
+ "StringEquals": {"aws:RequestedRegion": "us-east-1"},
+ "IpAddress": {"aws:SourceIp": "127.0.0.0/8"},
+ }
+ }]})
+ assert evaluate(_ctx(region="us-east-1"), [stmts]).decision == "Allow"
+ # Region doesn't match → AND fails
+ assert evaluate(_ctx(region="eu-west-1"), [stmts]).decision == "ImplicitDeny"
+
+ def test_if_exists_key_absent(self):
+ """AWS: *IfExists = if key is absent, condition is satisfied."""
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "*", "Resource": "*",
+ "Condition": {"StringEqualsIfExists": {
+ "aws:SourceVpc": "vpc-12345" # key not in context
+ }}
+ }]})
+ assert evaluate(_ctx(), [stmts]).decision == "Allow"
+
+ def test_if_exists_key_present_must_match(self):
+ """AWS: *IfExists with key present = normal check."""
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "*", "Resource": "*",
+ "Condition": {"StringEqualsIfExists": {
+ "aws:RequestedRegion": "eu-west-1"
+ }}
+ }]})
+ # RequestedRegion IS present and is "us-east-1", not "eu-west-1"
+ assert evaluate(_ctx(region="us-east-1"), [stmts]).decision == "ImplicitDeny"
+
+ def test_for_all_values_multivalued_key(self):
+ """AWS: ForAllValues = all request values must match at least one policy value."""
+ ctx = _ctx()
+ ctx.tag_keys = ["env", "team"]
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "*", "Resource": "*",
+ "Condition": {"ForAllValues:StringEquals": {
+ "aws:TagKeys": ["env", "team", "project"]
+ }}
+ }]})
+ assert evaluate(ctx, [stmts]).decision == "Allow"
+
+ def test_for_any_value_multivalued_key(self):
+ """AWS: ForAnyValue = at least one request value must match."""
+ ctx = _ctx()
+ ctx.tag_keys = ["env", "cost-center"]
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "*", "Resource": "*",
+ "Condition": {"ForAnyValue:StringEquals": {
+ "aws:TagKeys": ["env", "team"]
+ }}
+ }]})
+ # "env" matches → ForAnyValue satisfied
+ assert evaluate(ctx, [stmts]).decision == "Allow"
+
+ def test_for_any_value_no_match(self):
+ ctx = _ctx()
+ ctx.tag_keys = ["cost-center", "department"]
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "*", "Resource": "*",
+ "Condition": {"ForAnyValue:StringEquals": {
+ "aws:TagKeys": ["env", "team"]
+ }}
+ }]})
+ assert evaluate(ctx, [stmts]).decision == "ImplicitDeny"
+
+
+# ---------------------------------------------------------------------------
+# Trust policy evaluation (per AWS AssumeRole documentation)
+# ---------------------------------------------------------------------------
+
+class TestTrustPolicy:
+ def test_wildcard_principal(self):
+ trust = {"Statement": [{"Effect": "Allow", "Principal": "*",
+ "Action": "sts:AssumeRole"}]}
+ assert evaluate_trust_policy(trust, "arn:aws:iam::999:user/anyone")
+
+ def test_account_root_allows_all_in_account(self):
+ """AWS: arn:aws:iam::ACCT:root trusts all principals in that account."""
+ trust = {"Statement": [{"Effect": "Allow",
+ "Principal": {"AWS": "arn:aws:iam::123456789012:root"},
+ "Action": "sts:AssumeRole"}]}
+ assert evaluate_trust_policy(trust, "arn:aws:iam::123456789012:user/alice")
+ assert not evaluate_trust_policy(trust, "arn:aws:iam::999999999999:user/bob")
+
+ def test_specific_user_principal(self):
+ trust = {"Statement": [{"Effect": "Allow",
+ "Principal": {"AWS": "arn:aws:iam::123456789012:user/alice"},
+ "Action": "sts:AssumeRole"}]}
+ assert evaluate_trust_policy(trust, "arn:aws:iam::123456789012:user/alice")
+ assert not evaluate_trust_policy(trust, "arn:aws:iam::123456789012:user/bob")
+
+ def test_service_principal_allows_root(self):
+ """Service principals allow root (MiniStack's internal service calls use root)."""
+ trust = {"Statement": [{"Effect": "Allow",
+ "Principal": {"Service": "lambda.amazonaws.com"},
+ "Action": "sts:AssumeRole"}]}
+ assert evaluate_trust_policy(trust, "arn:aws:iam::123456789012:root")
+
+ def test_service_principal_allows_matching_service(self):
+ """Service principal matches callers containing the service name."""
+ trust = {"Statement": [{"Effect": "Allow",
+ "Principal": {"Service": "lambda.amazonaws.com"},
+ "Action": "sts:AssumeRole"}]}
+ assert evaluate_trust_policy(trust, "arn:aws:lambda:us-east-1:123:function:test")
+
+ def test_service_principal_denies_unrelated_user(self):
+ """A service principal does NOT allow arbitrary IAM users."""
+ trust = {"Statement": [{"Effect": "Allow",
+ "Principal": {"Service": "lambda.amazonaws.com"},
+ "Action": "sts:AssumeRole"}]}
+ assert not evaluate_trust_policy(trust, "arn:aws:iam::123:user/anyone")
+
+ def test_account_id_shorthand(self):
+ """AWS: account ID alone = arn:aws:iam::ACCT:root."""
+ trust = {"Statement": [{"Effect": "Allow",
+ "Principal": {"AWS": "123456789012"},
+ "Action": "sts:AssumeRole"}]}
+ assert evaluate_trust_policy(trust, "arn:aws:iam::123456789012:user/alice")
+ assert not evaluate_trust_policy(trust, "arn:aws:iam::999999999999:user/bob")
+
+ def test_multiple_principals_list(self):
+ trust = {"Statement": [{"Effect": "Allow",
+ "Principal": {"AWS": [
+ "arn:aws:iam::111111111111:root",
+ "arn:aws:iam::222222222222:root"]},
+ "Action": "sts:AssumeRole"}]}
+ assert evaluate_trust_policy(trust, "arn:aws:iam::111111111111:user/a")
+ assert evaluate_trust_policy(trust, "arn:aws:iam::222222222222:user/b")
+ assert not evaluate_trust_policy(trust, "arn:aws:iam::333333333333:user/c")
+
+ def test_wrong_action_not_matched(self):
+ trust = {"Statement": [{"Effect": "Allow", "Principal": "*",
+ "Action": "s3:GetObject"}]}
+ assert not evaluate_trust_policy(trust, "arn:aws:iam::123:user/a")
+
+ def test_deny_effect_not_matched(self):
+ trust = {"Statement": [{"Effect": "Deny", "Principal": "*",
+ "Action": "sts:AssumeRole"}]}
+ assert not evaluate_trust_policy(trust, "arn:aws:iam::123:user/a")
+
+ def test_string_json_input(self):
+ trust_str = json.dumps({"Statement": [{"Effect": "Allow", "Principal": "*",
+ "Action": "sts:AssumeRole"}]})
+ assert evaluate_trust_policy(trust_str, "arn:aws:iam::123:user/a")
+
+ def test_invalid_json_returns_false(self):
+ assert not evaluate_trust_policy("not json", "arn:aws:iam::123:user/a")
+
+
+# ---------------------------------------------------------------------------
+# Principal resolution — AWS error codes
+# (per AWS STS/IAM Common Errors reference)
+# ---------------------------------------------------------------------------
+
+class TestResolvePrincipal:
+ def test_empty_key_is_root(self):
+ result = resolve_principal("", "000000000000")
+ assert isinstance(result, PrincipalInfo)
+ assert result.type == "Root"
+ assert result.policies is None
+
+ def test_test_key_is_root(self):
+ """Default boto3 key 'test' should work as root."""
+ result = resolve_principal("test", "000000000000")
+ assert isinstance(result, PrincipalInfo)
+ assert result.type == "Root"
+
+ def test_twelve_digit_account_id_is_root(self):
+ result = resolve_principal("123456789012", "123456789012")
+ assert isinstance(result, PrincipalInfo)
+ assert result.type == "Root"
+
+ def test_unknown_key_returns_unrecognized_client(self):
+ """AWS: unknown access key → UnrecognizedClientException (HTTP 403)."""
+ result = resolve_principal("AKIAFAKEKEY1234567", "000000000000")
+ assert isinstance(result, AuthError)
+ assert result.code == "UnrecognizedClientException"
+
+ def test_inactive_key_returns_invalid_client_token(self):
+ """AWS: inactive access key → InvalidClientTokenId (HTTP 403)."""
+ from ministack.services import iam as iam_svc
+ fake_key = "AKIATESTIACTV00001"
+ iam_svc._access_keys[fake_key] = {
+ "UserName": "inactive-user", "AccessKeyId": fake_key,
+ "SecretAccessKey": "s", "Status": "Inactive", "CreateDate": "2024-01-01",
+ }
+ try:
+ result = resolve_principal(fake_key, "000000000000")
+ assert isinstance(result, AuthError)
+ assert result.code == "InvalidClientTokenId"
+ finally:
+ iam_svc._access_keys.pop(fake_key, None)
+
+ def test_expired_session_returns_expired_token(self):
+ """AWS: expired session token → ExpiredTokenException (HTTP 403)."""
+ from ministack.services import sts as sts_svc
+ fake_key = "ASIATESTEXPIRED001"
+ sts_svc._sessions[fake_key] = {
+ "Arn": "arn:aws:sts::000000000000:assumed-role/r/s",
+ "UserId": "AROA123:s", "SecretAccessKey": "secret",
+ "Expiration": time.time() - 3600,
+ }
+ try:
+ result = resolve_principal(fake_key, "000000000000")
+ assert isinstance(result, AuthError)
+ assert result.code == "ExpiredTokenException"
+ finally:
+ sts_svc._sessions.pop(fake_key, None)
+
+ def test_valid_session_resolves_to_assumed_role(self):
+ from ministack.services import sts as sts_svc
+ fake_key = "ASIATESTVALID00001"
+ sts_svc._sessions[fake_key] = {
+ "Arn": "arn:aws:sts::000000000000:assumed-role/testrole/sess",
+ "UserId": "AROA123:sess", "SecretAccessKey": "secret",
+ "Expiration": time.time() + 3600,
+ }
+ try:
+ result = resolve_principal(fake_key, "000000000000")
+ assert isinstance(result, PrincipalInfo)
+ assert result.type == "AssumedRole"
+ assert "assumed-role/testrole" in result.arn
+ finally:
+ sts_svc._sessions.pop(fake_key, None)
+
+ def test_active_access_key_resolves_to_user(self):
+ from ministack.services import iam as iam_svc
+ fake_key = "AKIATESTACTIVE0001"
+ iam_svc._access_keys[fake_key] = {
+ "UserName": "active-user", "AccessKeyId": fake_key,
+ "SecretAccessKey": "s", "Status": "Active", "CreateDate": "2024-01-01",
+ }
+ try:
+ result = resolve_principal(fake_key, "000000000000")
+ assert isinstance(result, PrincipalInfo)
+ assert result.type == "User"
+ assert "active-user" in result.arn
+ finally:
+ iam_svc._access_keys.pop(fake_key, None)
+
+
+# ---------------------------------------------------------------------------
+# End-to-end enforce() flow
+# ---------------------------------------------------------------------------
+
+class TestEnforce:
+ def test_root_key_always_allowed(self):
+ assert enforce("test", "s3:DeleteBucket", "s3", "us-east-1") is None
+
+ def test_unknown_key_returns_auth_error(self):
+ result = enforce("AKIAFAKEUNKNOWN123", "s3:ListBuckets", "s3", "us-east-1")
+ assert isinstance(result, AuthError)
+ assert result.code == "UnrecognizedClientException"
+
+ def test_user_with_matching_policy_allowed(self):
+ from ministack.services import iam as iam_svc
+ fake_key = "AKIATESTENFRC00001"
+ iam_svc._access_keys[fake_key] = {
+ "UserName": "enforce-user", "AccessKeyId": fake_key,
+ "SecretAccessKey": "s", "Status": "Active", "CreateDate": "2024-01-01",
+ }
+ iam_svc._users["enforce-user"] = {
+ "UserName": "enforce-user",
+ "Arn": "arn:aws:iam::000000000000:user/enforce-user",
+ "UserId": "AIDA123", "CreateDate": "2024-01-01", "Path": "/",
+ "AttachedPolicies": [], "Tags": [],
+ }
+ # User inline policies live in the separate _user_inline_policies dict
+ iam_svc._user_inline_policies["enforce-user"] = {
+ "p": json.dumps({
+ "Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]
+ })
+ }
+ try:
+ assert enforce(fake_key, "s3:PutObject", "s3", "us-east-1") is None
+ result = enforce(fake_key, "ec2:RunInstances", "ec2", "us-east-1")
+ assert isinstance(result, EvalResult)
+ assert result.decision == "ImplicitDeny"
+ finally:
+ iam_svc._access_keys.pop(fake_key, None)
+ iam_svc._users.pop("enforce-user", None)
+ iam_svc._user_inline_policies.pop("enforce-user", None)
+
+ def test_explicit_deny_in_policy_blocks(self):
+ from ministack.services import iam as iam_svc
+ fake_key = "AKIATESTDENY000001"
+ iam_svc._access_keys[fake_key] = {
+ "UserName": "deny-user", "AccessKeyId": fake_key,
+ "SecretAccessKey": "s", "Status": "Active", "CreateDate": "2024-01-01",
+ }
+ iam_svc._users["deny-user"] = {
+ "UserName": "deny-user",
+ "Arn": "arn:aws:iam::000000000000:user/deny-user",
+ "UserId": "AIDA456", "CreateDate": "2024-01-01", "Path": "/",
+ "AttachedPolicies": [], "Tags": [],
+ }
+ iam_svc._user_inline_policies["deny-user"] = {
+ "p": json.dumps({"Statement": [
+ {"Effect": "Allow", "Action": "*", "Resource": "*"},
+ {"Effect": "Deny", "Action": "s3:DeleteBucket", "Resource": "*"},
+ ]})
+ }
+ try:
+ assert enforce(fake_key, "s3:PutObject", "s3", "us-east-1") is None
+ result = enforce(fake_key, "s3:DeleteBucket", "s3", "us-east-1")
+ assert isinstance(result, EvalResult)
+ assert result.decision == "Deny"
+ finally:
+ iam_svc._access_keys.pop(fake_key, None)
+ iam_svc._users.pop("deny-user", None)
+ iam_svc._user_inline_policies.pop("deny-user", None)
+
+ def test_user_inherits_group_inline_policy(self):
+ """User policies include inline policies from their groups."""
+ from ministack.services import iam as iam_svc
+ fake_key = "AKIATESTGROUP00001"
+ iam_svc._access_keys[fake_key] = {
+ "UserName": "group-user", "AccessKeyId": fake_key,
+ "SecretAccessKey": "s", "Status": "Active", "CreateDate": "2024-01-01",
+ }
+ iam_svc._users["group-user"] = {
+ "UserName": "group-user",
+ "Arn": "arn:aws:iam::000000000000:user/group-user",
+ "UserId": "AIDA789", "CreateDate": "2024-01-01", "Path": "/",
+ "AttachedPolicies": [], "Tags": [],
+ }
+ iam_svc._groups["dev-team"] = {
+ "GroupName": "dev-team", "GroupId": "AGPA123",
+ "Arn": "arn:aws:iam::000000000000:group/dev-team",
+ "Users": ["group-user"], "AttachedPolicies": [],
+ }
+ iam_svc._group_inline_policies["dev-team"] = {
+ "s3-access": json.dumps({
+ "Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]
+ })
+ }
+ try:
+ # s3 allowed via group policy
+ assert enforce(fake_key, "s3:PutObject", "s3", "us-east-1") is None
+ # ec2 not in any policy
+ result = enforce(fake_key, "ec2:RunInstances", "ec2", "us-east-1")
+ assert isinstance(result, EvalResult)
+ assert result.decision == "ImplicitDeny"
+ finally:
+ iam_svc._access_keys.pop(fake_key, None)
+ iam_svc._users.pop("group-user", None)
+ iam_svc._groups.pop("dev-team", None)
+ iam_svc._group_inline_policies.pop("dev-team", None)
+
+ def test_user_inherits_user_inline_policy(self):
+ """User inline policies are stored in _user_inline_policies, not on the user object."""
+ from ministack.services import iam as iam_svc
+ fake_key = "AKIATESTUSRPOL0001"
+ iam_svc._access_keys[fake_key] = {
+ "UserName": "inline-user", "AccessKeyId": fake_key,
+ "SecretAccessKey": "s", "Status": "Active", "CreateDate": "2024-01-01",
+ }
+ iam_svc._users["inline-user"] = {
+ "UserName": "inline-user",
+ "Arn": "arn:aws:iam::000000000000:user/inline-user",
+ "UserId": "AIDA012", "CreateDate": "2024-01-01", "Path": "/",
+ "AttachedPolicies": [], "Tags": [],
+ }
+ iam_svc._user_inline_policies["inline-user"] = {
+ "my-policy": json.dumps({
+ "Statement": [{"Effect": "Allow", "Action": "dynamodb:*", "Resource": "*"}]
+ })
+ }
+ try:
+ assert enforce(fake_key, "dynamodb:PutItem", "dynamodb", "us-east-1") is None
+ result = enforce(fake_key, "s3:GetObject", "s3", "us-east-1")
+ assert isinstance(result, EvalResult)
+ assert result.decision == "ImplicitDeny"
+ finally:
+ iam_svc._access_keys.pop(fake_key, None)
+ iam_svc._users.pop("inline-user", None)
+ iam_svc._user_inline_policies.pop("inline-user", None)
+
+
+# ---------------------------------------------------------------------------
+# Action extraction
+# ---------------------------------------------------------------------------
+
+# ---------------------------------------------------------------------------
+# Resource ARN construction
+# ---------------------------------------------------------------------------
+
+class TestResourceArn:
+ def test_s3_bucket(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("s3", "PUT", "/mybucket", {}, b"", {}, "us-east-1", "123") == "arn:aws:s3:::mybucket"
+
+ def test_s3_object(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("s3", "GET", "/mybucket/path/to/key", {}, b"", {}, "us-east-1", "123") == "arn:aws:s3:::mybucket/path/to/key"
+
+ def test_s3_list_buckets(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("s3", "GET", "/", {}, b"", {}, "us-east-1", "123") == "*"
+
+ def test_dynamodb_table(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ body = json.dumps({"TableName": "users"}).encode()
+ assert extract_resource_arn("dynamodb", "POST", "/", {}, body, {}, "us-east-1", "123") == "arn:aws:dynamodb:us-east-1:123:table/users"
+
+ def test_dynamodb_no_table(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("dynamodb", "POST", "/", {}, b"{}", {}, "us-east-1", "123") == "*"
+
+ def test_lambda_function(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("lambda", "GET", "/2015-03-31/functions/my-func", {}, b"", {}, "us-east-1", "123") == "arn:aws:lambda:us-east-1:123:function:my-func"
+
+ def test_lambda_invoke(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("lambda", "POST", "/2015-03-31/functions/my-func/invocations", {}, b"", {}, "us-east-1", "123") == "arn:aws:lambda:us-east-1:123:function:my-func"
+
+ def test_sqs_queue_url(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("sqs", "POST", "/", {}, b"", {"QueueUrl": ["http://localhost:4566/000000000000/my-queue"]}, "us-east-1", "123") == "arn:aws:sqs:us-east-1:123:my-queue"
+
+ def test_sqs_create_queue(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("sqs", "POST", "/", {}, b"", {"QueueName": ["my-queue"]}, "us-east-1", "123") == "arn:aws:sqs:us-east-1:123:my-queue"
+
+ def test_sns_topic_arn(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ topic = "arn:aws:sns:us-east-1:123:my-topic"
+ assert extract_resource_arn("sns", "POST", "/", {}, b"", {"TopicArn": [topic]}, "us-east-1", "123") == topic
+
+ def test_kms_key_id(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ body = json.dumps({"KeyId": "abc-123"}).encode()
+ assert extract_resource_arn("kms", "POST", "/", {}, body, {}, "us-east-1", "123") == "arn:aws:kms:us-east-1:123:key/abc-123"
+
+ def test_kms_alias(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ body = json.dumps({"KeyId": "alias/my-key"}).encode()
+ assert extract_resource_arn("kms", "POST", "/", {}, body, {}, "us-east-1", "123") == "arn:aws:kms:us-east-1:123:alias/my-key"
+
+ def test_secretsmanager(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ body = json.dumps({"SecretId": "my-secret"}).encode()
+ assert extract_resource_arn("secretsmanager", "POST", "/", {}, body, {}, "us-east-1", "123") == "arn:aws:secretsmanager:us-east-1:123:secret:my-secret"
+
+ def test_iam_role(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("iam", "POST", "/", {}, b"", {"RoleName": ["my-role"]}, "us-east-1", "123") == "arn:aws:iam::123:role/my-role"
+
+ def test_iam_user(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("iam", "POST", "/", {}, b"", {"UserName": ["alice"]}, "us-east-1", "123") == "arn:aws:iam::123:user/alice"
+
+ def test_unknown_service(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("unknown", "GET", "/", {}, b"", {}, "us-east-1", "123") == "*"
+
+ def test_events_rule(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ body = json.dumps({"Name": "my-rule"}).encode()
+ arn = extract_resource_arn("events", "POST", "/", {}, body, {}, "us-east-1", "123")
+ assert "events" in arn and "my-rule" in arn
+
+ def test_kinesis_stream(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ body = json.dumps({"StreamName": "my-stream"}).encode()
+ assert extract_resource_arn("kinesis", "POST", "/", {}, body, {}, "us-east-1", "123") == "arn:aws:kinesis:us-east-1:123:stream/my-stream"
+
+ def test_logs_group(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ body = json.dumps({"logGroupName": "/app/logs"}).encode()
+ assert extract_resource_arn("logs", "POST", "/", {}, body, {}, "us-east-1", "123") == "arn:aws:logs:us-east-1:123:log-group:/app/logs"
+
+ def test_states_machine(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ body = json.dumps({"stateMachineArn": "arn:aws:states:us-east-1:123:stateMachine:my-sm"}).encode()
+ assert extract_resource_arn("states", "POST", "/", {}, body, {}, "us-east-1", "123") == "arn:aws:states:us-east-1:123:stateMachine:my-sm"
+
+ def test_ecs_cluster(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ body = json.dumps({"cluster": "my-cluster"}).encode()
+ assert extract_resource_arn("ecs", "POST", "/", {}, body, {}, "us-east-1", "123") == "arn:aws:ecs:us-east-1:123:cluster/my-cluster"
+
+ def test_eks_cluster_from_path(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("eks", "GET", "/clusters/prod", {}, b"", {}, "us-east-1", "123") == "arn:aws:eks:us-east-1:123:cluster/prod"
+
+ def test_rds_instance(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("rds", "POST", "/", {}, b"", {"DBInstanceIdentifier": ["mydb"]}, "us-east-1", "123") == "arn:aws:rds:us-east-1:123:db:mydb"
+
+ def test_cloudformation_stack(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("cloudformation", "POST", "/", {}, b"", {"StackName": ["my-stack"]}, "us-east-1", "123") == "arn:aws:cloudformation:us-east-1:123:stack/my-stack/*"
+
+ def test_ssm_parameter(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("ssm", "POST", "/", {}, b"", {"Name": ["/app/config"]}, "us-east-1", "123") == "arn:aws:ssm:us-east-1:123:parameter/app/config"
+
+ def test_elb_passthrough_arn(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ lb_arn = "arn:aws:elasticloadbalancing:us-east-1:123:loadbalancer/app/my-lb/abc"
+ assert extract_resource_arn("elasticloadbalancing", "POST", "/", {}, b"", {"LoadBalancerArn": [lb_arn]}, "us-east-1", "123") == lb_arn
+
+ def test_cloudfront_distribution(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("cloudfront", "GET", "/2020-05-31/distribution/E123ABC", {}, b"", {}, "us-east-1", "123") == "arn:aws:cloudfront::123:distribution/E123ABC"
+
+ def test_route53_hostedzone(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("route53", "GET", "/2013-04-01/hostedzone/Z123", {}, b"", {}, "us-east-1", "123") == "arn:aws:route53:::hostedzone/Z123"
+
+ def test_cognito_userpool(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ body = json.dumps({"UserPoolId": "us-east-1_abc123"}).encode()
+ assert extract_resource_arn("cognito-idp", "POST", "/", {}, body, {}, "us-east-1", "123") == "arn:aws:cognito-idp:us-east-1:123:userpool/us-east-1_abc123"
+
+ def test_scheduler(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("scheduler", "GET", "/schedules/my-sched", {}, b"", {}, "us-east-1", "123") == "arn:aws:scheduler:us-east-1:123:schedule/default/my-sched"
+
+ def test_pipes(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("pipes", "GET", "/v1/pipes/my-pipe", {}, b"", {}, "us-east-1", "123") == "arn:aws:pipes:us-east-1:123:pipe/my-pipe"
+
+ def test_mq_broker(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert "mq" in extract_resource_arn("mq", "GET", "/v1/brokers/my-broker", {}, b"", {}, "us-east-1", "123")
+ assert "my-broker" in extract_resource_arn("mq", "GET", "/v1/brokers/my-broker", {}, b"", {}, "us-east-1", "123")
+
+ def test_kafka_cluster(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert "kafka" in extract_resource_arn("kafka", "GET", "/v1/clusters/my-cluster", {}, b"", {}, "us-east-1", "123")
+
+ def test_dsql_cluster(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("dsql", "GET", "/clusters/cl-123", {}, b"", {}, "us-east-1", "123") == "arn:aws:dsql:us-east-1:123:cluster/cl-123"
+
+ def test_efs_filesystem(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("elasticfilesystem", "GET", "/2015-02-01/file-systems/fs-123", {}, b"", {}, "us-east-1", "123") == "arn:aws:elasticfilesystem:us-east-1:123:file-system/fs-123"
+
+ def test_cloudtrail(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ body = json.dumps({"Name": "my-trail"}).encode()
+ assert extract_resource_arn("cloudtrail", "POST", "/", {}, body, {}, "us-east-1", "123") == "arn:aws:cloudtrail:us-east-1:123:trail/my-trail"
+
+ def test_appconfig_application(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("appconfig", "GET", "/applications/app-123", {}, b"", {}, "us-east-1", "123") == "arn:aws:appconfig:us-east-1:123:application/app-123"
+
+ def test_appconfig_environment(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("appconfig", "GET", "/applications/app-1/environments/env-1", {}, b"", {}, "us-east-1", "123") == "arn:aws:appconfig:us-east-1:123:application/app-1/environment/env-1"
+
+ def test_resource_groups(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("resource-groups", "GET", "/groups/my-group", {}, b"", {}, "us-east-1", "123") == "arn:aws:resource-groups:us-east-1:123:group/my-group"
+
+ def test_rds_data_passthrough(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ body = json.dumps({"resourceArn": "arn:aws:rds:us-east-1:123:cluster:my-db"}).encode()
+ assert extract_resource_arn("rds-data", "POST", "/", {}, body, {}, "us-east-1", "123") == "arn:aws:rds:us-east-1:123:cluster:my-db"
+
+ def test_s3tables(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("s3tables", "GET", "/buckets/my-tb", {}, b"", {}, "us-east-1", "123") == "arn:aws:s3tables:us-east-1:123:bucket/my-tb"
+
+ def test_mediaconnect(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert "mediaconnect" in extract_resource_arn("mediaconnect", "GET", "/v1/flows/flow-123", {}, b"", {}, "us-east-1", "123")
+
+ # --- EC2 ---
+ def test_ec2_instance(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("ec2", "POST", "/", {}, b"", {"InstanceId.1": ["i-abc123"]}, "us-east-1", "123") == "arn:aws:ec2:us-east-1:123:instance/i-abc123"
+
+ def test_ec2_vpc(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("ec2", "POST", "/", {}, b"", {"VpcId": ["vpc-123"]}, "us-east-1", "123") == "arn:aws:ec2:us-east-1:123:vpc/vpc-123"
+
+ def test_ec2_security_group(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("ec2", "POST", "/", {}, b"", {"GroupId": ["sg-123"]}, "us-east-1", "123") == "arn:aws:ec2:us-east-1:123:security-group/sg-123"
+
+ def test_ec2_no_resource(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("ec2", "POST", "/", {}, b"", {"Action": ["DescribeInstances"]}, "us-east-1", "123") == "*"
+
+ # --- IoT ---
+ def test_iot_thing(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("iot", "GET", "/things/my-thing", {}, b"", {}, "us-east-1", "123") == "arn:aws:iot:us-east-1:123:thing/my-thing"
+
+ def test_iot_policy(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("iot", "GET", "/policies/my-policy", {}, b"", {}, "us-east-1", "123") == "arn:aws:iot:us-east-1:123:policy/my-policy"
+
+ def test_iot_rule(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("iot", "GET", "/rules/my-rule", {}, b"", {}, "us-east-1", "123") == "arn:aws:iot:us-east-1:123:rule/my-rule"
+
+ # --- API Gateway ---
+ def test_apigateway_v2(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("apigateway", "GET", "/v2/apis/abc123", {}, b"", {}, "us-east-1", "123") == "arn:aws:apigateway:us-east-1::/apis/abc123"
+
+ def test_apigateway_v1(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("apigateway", "GET", "/restapis/xyz789", {}, b"", {}, "us-east-1", "123") == "arn:aws:apigateway:us-east-1::/restapis/xyz789"
+
+ # --- Bedrock ---
+ def test_bedrock_model(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("bedrock-runtime", "POST", "/model/anthropic.claude-v2/invoke", {}, b"", {}, "us-east-1", "123") == "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-v2"
+
+ def test_bedrock_agent(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("bedrock-agent", "GET", "/agents/AGENT123", {}, b"", {}, "us-east-1", "123") == "arn:aws:bedrock:us-east-1:123:agent/AGENT123"
+
+ def test_bedrock_knowledge_base(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("bedrock-agent", "GET", "/knowledgebases/KB123", {}, b"", {}, "us-east-1", "123") == "arn:aws:bedrock:us-east-1:123:knowledge-base/KB123"
+
+ # --- AppSync ---
+ def test_appsync_api(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("appsync", "GET", "/v1/apis/abc123", {}, b"", {}, "us-east-1", "123") == "arn:aws:appsync:us-east-1:123:apis/abc123"
+
+ def test_appsync_datasource(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("appsync", "GET", "/v1/apis/abc/datasources/myds", {}, b"", {}, "us-east-1", "123") == "arn:aws:appsync:us-east-1:123:apis/abc/datasources/myds"
+
+ def test_resource_scoped_policy_enforcement(self):
+ """A policy allowing s3:GetObject only on mybucket/* should deny access to otherbucket."""
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "s3:GetObject",
+ "Resource": "arn:aws:s3:::mybucket/*"
+ }]})
+ ctx_allowed = _ctx(action="s3:GetObject", resource="arn:aws:s3:::mybucket/key")
+ assert evaluate(ctx_allowed, [stmts]).decision == "Allow"
+ ctx_denied = _ctx(action="s3:GetObject", resource="arn:aws:s3:::otherbucket/key")
+ assert evaluate(ctx_denied, [stmts]).decision == "ImplicitDeny"
+
+ def test_resource_wildcard_in_arn(self):
+ """Wildcards in resource ARNs work."""
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "dynamodb:*",
+ "Resource": "arn:aws:dynamodb:*:*:table/users*"
+ }]})
+ ctx = _ctx(action="dynamodb:PutItem",
+ resource="arn:aws:dynamodb:us-east-1:123:table/users")
+ assert evaluate(ctx, [stmts]).decision == "Allow"
+ ctx2 = _ctx(action="dynamodb:PutItem",
+ resource="arn:aws:dynamodb:us-east-1:123:table/orders")
+ assert evaluate(ctx2, [stmts]).decision == "ImplicitDeny"
+
+
+class TestActionExtraction:
+ def test_query_protocol(self):
+ from ministack.core.iam_actions import extract_iam_action
+ assert extract_iam_action("sqs", "POST", "/", {}, b"", {"Action": ["CreateQueue"]}) == "sqs:CreateQueue"
+ assert extract_iam_action("monitoring", "POST", "/", {}, b"", {"Action": ["PutMetricData"]}) == "cloudwatch:PutMetricData"
+
+ def test_target_protocol(self):
+ from ministack.core.iam_actions import extract_iam_action
+ assert extract_iam_action("dynamodb", "POST", "/", {"x-amz-target": "DynamoDB_20120810.PutItem"}, b"", {}) == "dynamodb:PutItem"
+ assert extract_iam_action("kms", "POST", "/", {"x-amz-target": "TrentService.Encrypt"}, b"", {}) == "kms:Encrypt"
+
+ def test_s3_rest(self):
+ from ministack.core.iam_actions import extract_iam_action
+ assert extract_iam_action("s3", "GET", "/", {}, b"", {}) == "s3:ListAllMyBuckets"
+ assert extract_iam_action("s3", "PUT", "/bucket/key", {}, b"", {}) == "s3:PutObject"
+ assert extract_iam_action("s3", "GET", "/bucket", {}, b"", {"versioning": [""]}) == "s3:GetBucketVersioning"
+
+ def test_lambda_rest(self):
+ from ministack.core.iam_actions import extract_iam_action
+ assert extract_iam_action("lambda", "POST", "/2015-03-31/functions", {}, b"", {}) == "lambda:CreateFunction"
+ assert extract_iam_action("lambda", "POST", "/2015-03-31/functions/f/invocations", {}, b"", {}) == "lambda:InvokeFunction"
+
+ def test_unknown_service_returns_none(self):
+ from ministack.core.iam_actions import extract_iam_action
+ assert extract_iam_action("unknown_svc", "GET", "/", {}, b"", {}) is None
+
+
+# ---------------------------------------------------------------------------
+# AccessDenied response formatting
+# ---------------------------------------------------------------------------
+
+class TestAccessDeniedResponse:
+ def test_s3_rest_xml(self):
+ from ministack.core.iam_actions import access_denied_response
+ s, h, b = access_denied_response("s3", "s3:PutObject", "arn:aws:iam::123:user/a", "r1")
+ assert s == 403
+ assert b"<Error>" in b
+ assert b"AccessDenied" in b
+
+ def test_ec2_unauthorized_operation(self):
+ from ministack.core.iam_actions import access_denied_response
+ s, h, b = access_denied_response("ec2", "ec2:RunInstances", "arn:aws:iam::123:user/a", "r1")
+ assert s == 403
+ assert b"UnauthorizedOperation" in b
+
+ def test_json_protocol(self):
+ from ministack.core.iam_actions import access_denied_response
+ s, h, b = access_denied_response("dynamodb", "dynamodb:PutItem", "arn:aws:iam::123:user/a", "r1")
+ assert s == 403
+ body = json.loads(b)
+ assert body["__type"] == "AccessDeniedException"
+
+ def test_query_xml_protocol(self):
+ from ministack.core.iam_actions import access_denied_response
+ s, h, b = access_denied_response("iam", "iam:CreateRole", "arn:aws:iam::123:user/a", "r1")
+ assert s == 403
+ assert b"<ErrorResponse" in b
+
+ def test_custom_error_code_preserved(self):
+ from ministack.core.iam_actions import access_denied_response
+ s, h, b = access_denied_response("s3", "s3:PutObject", "", "r1",
+ error_code="ExpiredTokenException",
+ message="Token expired")
+ assert b"ExpiredTokenException" in b
+
+
+# ---------------------------------------------------------------------------
+# Integration: SimulateCustomPolicy (runs against server, AUTH=false OK)
+# ---------------------------------------------------------------------------
+
+def test_simulate_custom_policy_allow(iam):
+ policy = json.dumps({"Version": "2012-10-17",
+ "Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]})
+ resp = iam.simulate_custom_policy(PolicyInputList=[policy],
+ ActionNames=["s3:GetObject", "s3:PutObject"])
+ results = resp["EvaluationResults"]
+ assert len(results) == 2
+ for r in results:
+ assert r["EvalDecision"] == "allowed"
+
+
+def test_simulate_custom_policy_implicit_deny(iam):
+ policy = json.dumps({"Version": "2012-10-17",
+ "Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]})
+ resp = iam.simulate_custom_policy(PolicyInputList=[policy],
+ ActionNames=["ec2:RunInstances"])
+ assert resp["EvaluationResults"][0]["EvalDecision"] == "implicitDeny"
+
+
+def test_simulate_custom_policy_explicit_deny(iam):
+ policy = json.dumps({"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "*", "Resource": "*"},
+ {"Effect": "Deny", "Action": "s3:DeleteBucket", "Resource": "*"},
+ ]})
+ resp = iam.simulate_custom_policy(PolicyInputList=[policy],
+ ActionNames=["s3:PutObject", "s3:DeleteBucket"])
+ results = {r["EvalActionName"]: r["EvalDecision"] for r in resp["EvaluationResults"]}
+ assert results["s3:PutObject"] == "allowed"
+ assert results["s3:DeleteBucket"] == "explicitDeny"
+
+
+# ---------------------------------------------------------------------------
+# Integration: Policy document validation (runs against server)
+# ---------------------------------------------------------------------------
+
+def test_create_policy_rejects_malformed_json(iam):
+ with pytest.raises(ClientError) as exc:
+ iam.create_policy(PolicyName="bad-policy-json", PolicyDocument="not valid json")
+ assert exc.value.response["Error"]["Code"] == "MalformedPolicyDocument"
+
+
+def test_create_policy_rejects_missing_action(iam):
+ with pytest.raises(ClientError) as exc:
+ iam.create_policy(PolicyName="bad-policy-no-action",
+ PolicyDocument=json.dumps({"Statement": [{"Effect": "Allow", "Resource": "*"}]}))
+ assert exc.value.response["Error"]["Code"] == "MalformedPolicyDocument"
+
+
+def test_put_role_policy_rejects_malformed_document(iam):
+ iam.create_role(
+ RoleName="validation-test-role-2",
+ AssumeRolePolicyDocument=json.dumps({
+ "Version": "2012-10-17",
+ "Statement": [{"Effect": "Allow", "Principal": "*", "Action": "sts:AssumeRole"}]
+ }),
+ )
+ try:
+ with pytest.raises(ClientError) as exc:
+ iam.put_role_policy(RoleName="validation-test-role-2",
+ PolicyName="bad", PolicyDocument="not json")
+ assert exc.value.response["Error"]["Code"] == "MalformedPolicyDocument"
+ finally:
+ iam.delete_role(RoleName="validation-test-role-2")
diff --git a/tests/test_imds.py b/tests/test_imds.py
index 843b8b0c..b91cd377 100644
--- a/tests/test_imds.py
+++ b/tests/test_imds.py
@@ -1,4 +1,3 @@
-import json
import os
import pytest
diff --git a/tests/test_inspector2.py b/tests/test_inspector2.py
index 0c020d2a..db7c790e 100644
--- a/tests/test_inspector2.py
+++ b/tests/test_inspector2.py
@@ -2,7 +2,6 @@
Integration tests for the Inspector2 emulator.
"""
-import json
import boto3
import pytest
diff --git a/tests/test_iot.py b/tests/test_iot.py
index 6f0df79f..9db92a3e 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -1436,8 +1436,6 @@ from ministack.services.iot import (
_encode_remaining_length,
_encode_string,
_InFlightMessage,
- _make_puback,
- _make_suback,
_persistent_sessions,
_property_value,
_read_string,
diff --git a/tests/test_kinesis.py b/tests/test_kinesis.py
index 77d6230a..7c15fc5d 100644
--- a/tests/test_kinesis.py
+++ b/tests/test_kinesis.py
@@ -1,10 +1,8 @@
import io
-import json
import os
import time
import uuid as _uuid_mod
import zipfile
-from urllib.parse import urlparse
import boto3
import pytest
diff --git a/tests/test_kms.py b/tests/test_kms.py
index 033447f7..e169a3f1 100644
--- a/tests/test_kms.py
+++ b/tests/test_kms.py
@@ -1,11 +1,8 @@
import base64
-import io
import json
import os
import time
import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import boto3
import pytest
diff --git a/tests/test_ministack.py b/tests/test_ministack.py
index 8cc6fabe..f610a6b0 100644
--- a/tests/test_ministack.py
+++ b/tests/test_ministack.py
@@ -1,15 +1,10 @@
"""Ministack admin/core tests — health, config, persistence, hypercorn compat."""
-import io
import json
import os
-import time
-import uuid as _uuid_mod
-import zipfile
from urllib.parse import urlparse
import pytest
-from botocore.exceptions import ClientError
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
@@ -111,9 +106,8 @@ def test_localstack_health_still_returns_200():
def test_ministack_package_core_importable():
"""ministack.core modules must all be importable."""
from ministack.core.lambda_runtime import get_or_create_worker
- from ministack.core.lambda_runtime import reset as lr_reset
- from ministack.core.persistence import load_state, save_all
- from ministack.core.responses import error_response_json, json_response, new_uuid
+ from ministack.core.persistence import save_all
+ from ministack.core.responses import json_response
from ministack.core.router import detect_service
assert callable(json_response)
@@ -126,7 +120,6 @@ def test_ministack_package_services_importable():
"""All core ministack.services modules must be importable and expose handle_request."""
from ministack.services import (
apigateway,
- apigateway_v1,
appsync_events,
athena,
cloudwatch,
diff --git a/tests/test_msk.py b/tests/test_msk.py
index 21e25fa5..61430de1 100644
--- a/tests/test_msk.py
+++ b/tests/test_msk.py
@@ -6,11 +6,8 @@ Covers cluster CRUD, configuration CRUD with revisions, SCRAM, tags, and
GetBootstrapBrokers including the MINISTACK_MSK_BOOTSTRAP proxy passthrough.
"""
-import base64
-import os
import botocore.exceptions
-import pytest
from conftest import make_client
# ---------------------------------------------------------------------------
diff --git a/tests/test_multitenancy.py b/tests/test_multitenancy.py
index 9e4afb59..70c74f7b 100644
--- a/tests/test_multitenancy.py
+++ b/tests/test_multitenancy.py
@@ -9,7 +9,6 @@ in all ARN generation. Non-numeric keys (like "test") fall back to the default
import os
import boto3
-import pytest
from botocore.config import Config
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
diff --git a/tests/test_package.py b/tests/test_package.py
index ae8f3390..274f167a 100644
--- a/tests/test_package.py
+++ b/tests/test_package.py
@@ -1,13 +1,5 @@
-import io
-import json
-import os
-import time
-import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import pytest
-from botocore.exceptions import ClientError
_ministack_installed = True
@@ -20,9 +12,8 @@ _requires_package = pytest.mark.skipif(
def test_package_core_importable():
"""ministack.core modules must all be importable."""
from ministack.core.lambda_runtime import get_or_create_worker
- from ministack.core.lambda_runtime import reset as lr_reset
- from ministack.core.persistence import load_state, save_all
- from ministack.core.responses import error_response_json, json_response, new_uuid
+ from ministack.core.persistence import save_all
+ from ministack.core.responses import json_response
from ministack.core.router import detect_service
assert callable(json_response)
@@ -35,7 +26,6 @@ def test_package_services_importable():
"""All 25 ministack.services modules must be importable and expose handle_request."""
from ministack.services import (
apigateway,
- apigateway_v1,
athena,
cloudwatch,
cloudwatch_logs,
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
index 925c6c9e..9f3bcaca 100644
--- a/tests/test_persistence.py
+++ b/tests/test_persistence.py
@@ -553,9 +553,8 @@ def test_save_dict_skips_modules_never_imported():
were never imported at all — there's no state to capture and any
`get_state()` call on a non-imported module would attribute-error.
Defensive guard: ensure the fallback path's `hasattr` check works."""
- import sys as _sys
- from ministack.app import _build_persistence_save_dict, _loaded_modules, _state_map
+ from ministack.app import _build_persistence_save_dict, _state_map
# Pick any persisted module and ensure it's truly absent from both
# `_loaded_modules` and `sys.modules`. `cur` is an obscure one that
diff --git a/tests/test_rds.py b/tests/test_rds.py
index fb138db8..93f313b7 100644
--- a/tests/test_rds.py
+++ b/tests/test_rds.py
@@ -10,7 +10,6 @@ import types
import uuid
import uuid as _uuid_mod
import zipfile
-from urllib.parse import urlparse
import boto3
import pytest
diff --git a/tests/test_route53.py b/tests/test_route53.py
index 9ab5c188..52a3ef1c 100644
--- a/tests/test_route53.py
+++ b/tests/test_route53.py
@@ -1,10 +1,4 @@
-import io
-import json
-import os
import time
-import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import pytest
from botocore.exceptions import ClientError
diff --git a/tests/test_s3.py b/tests/test_s3.py
index b7792d83..be089446 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -8,7 +8,7 @@ from urllib.parse import urlparse
import pytest
from botocore.exceptions import ClientError
-from conftest import ENDPOINT_HOST, make_client, patch_endpoint_dns
+from conftest import make_client, patch_endpoint_dns
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
diff --git a/tests/test_secretsmanager.py b/tests/test_secretsmanager.py
index 9cfd45db..ea60df53 100644
--- a/tests/test_secretsmanager.py
+++ b/tests/test_secretsmanager.py
@@ -1,10 +1,7 @@
-import io
import json
import os
import time
import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import boto3
import pytest
diff --git a/tests/test_servicediscovery.py b/tests/test_servicediscovery.py
index 6063cd89..62b7c5e6 100644
--- a/tests/test_servicediscovery.py
+++ b/tests/test_servicediscovery.py
@@ -1,14 +1,7 @@
import asyncio
-import io
import json
-import os
-import time
-import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import pytest
-from botocore.exceptions import ClientError
import ministack.services.servicediscovery as sd_svc
diff --git a/tests/test_ses.py b/tests/test_ses.py
index dd718a2b..de352024 100644
--- a/tests/test_ses.py
+++ b/tests/test_ses.py
@@ -1,14 +1,9 @@
"""SES tests — API operations + SMTP relay integration."""
-import base64
-import io
import json
import os
-import time
import uuid as _uuid_mod
-import zipfile
from unittest.mock import MagicMock, patch
-from urllib.parse import urlparse
import pytest
from botocore.exceptions import ClientError
diff --git a/tests/test_sns.py b/tests/test_sns.py
index 69033ed1..187d8e46 100644
--- a/tests/test_sns.py
+++ b/tests/test_sns.py
@@ -5,7 +5,7 @@ import time
import urllib.request
import uuid as _uuid_mod
import zipfile
-from urllib.parse import urlencode, urlparse
+from urllib.parse import urlencode
import boto3
import pytest
@@ -549,10 +549,7 @@ def test_sns_to_lambda_event_subscription_arn(lam, sns):
sns.publish(TopicArn=topic_arn, Message="test-sub-arn")
# Invoke the function directly and check what event it last received
- import base64
- import io
import json
- import zipfile
result = lam.invoke(FunctionName=fn, Payload=json.dumps({"ping": True}).encode())
# The subscription ARN should be a real ARN, not "{topic}:subscription"
diff --git a/tests/test_ssm.py b/tests/test_ssm.py
index 21040ac8..36d1a6fb 100644
--- a/tests/test_ssm.py
+++ b/tests/test_ssm.py
@@ -1,10 +1,7 @@
-import io
import json
import os
import time
import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import boto3
import pytest
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index 8a62e817..7ee33c84 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -5,7 +5,6 @@ import os
import time
import uuid as _uuid_mod
import zipfile
-from urllib.parse import urlparse
import boto3
import pytest
diff --git a/tests/test_sts.py b/tests/test_sts.py
index 20a36b7f..a8876828 100644
--- a/tests/test_sts.py
+++ b/tests/test_sts.py
@@ -1,10 +1,5 @@
-import io
import json
import os
-import time
-import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import pytest
from botocore.exceptions import ClientError
diff --git a/tests/test_unicode.py b/tests/test_unicode.py
index d037298a..4319d1e3 100644
--- a/tests/test_unicode.py
+++ b/tests/test_unicode.py
@@ -1,13 +1,4 @@
-import io
-import json
-import os
-import time
-import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
-import pytest
-from botocore.exceptions import ClientError
def test_unicode_s3_object_key(s3):
diff --git a/tests/test_waf.py b/tests/test_waf.py
index 3ea8f5f2..71698a4f 100644
--- a/tests/test_waf.py
+++ b/tests/test_waf.py
@@ -1,13 +1,7 @@
-import io
import json
-import os
-import time
import uuid as _uuid_mod
-import zipfile
-from urllib.parse import urlparse
import pytest
-from botocore.exceptions import ClientError
from ministack.core.responses import (
AccountScopedDict,