Skip to content

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

fix(aws parity): validate vs aws (#1774)

Nahuel Nuceraf1623e54b2dd
diff --git a/README.md b/README.md
index a0210860..a5d8337f 100644
--- a/README.md
+++ b/README.md
@@ -415,7 +415,7 @@ subnet = ec2.create_subnet(
| Service | Operations | Notes |
|---------|-----------|-------|
| **SSM Parameter Store** | PutParameter, GetParameter, GetParameters, GetParametersByPath, DeleteParameter, DeleteParameters, DescribeParameters, GetParameterHistory, LabelParameterVersion, AddTagsToResource, RemoveTagsFromResource, ListTagsForResource | Supports String, SecureString, StringList |
-| **EventBridge** | CreateEventBus, UpdateEventBus, DeleteEventBus, ListEventBuses, DescribeEventBus, PutRule, DeleteRule, ListRules, DescribeRule, EnableRule, DisableRule, PutTargets, RemoveTargets, ListTargetsByRule, ListRuleNamesByTarget, PutEvents, TestEventPattern, TagResource, UntagResource, ListTagsForResource, CreateArchive, DeleteArchive, DescribeArchive, UpdateArchive, ListArchives, PutPermission, RemovePermission, CreateConnection, DescribeConnection, DeleteConnection, UpdateConnection, DeauthorizeConnection, ListConnections, CreateApiDestination, DescribeApiDestination, DeleteApiDestination, UpdateApiDestination, ListApiDestinations, StartReplay, DescribeReplay, ListReplays, CancelReplay, CreateEndpoint, DeleteEndpoint, DescribeEndpoint, ListEndpoints, UpdateEndpoint, ActivateEventSource, DeactivateEventSource, DescribeEventSource, CreatePartnerEventSource, DeletePartnerEventSource, DescribePartnerEventSource, ListPartnerEventSources, ListPartnerEventSourceAccounts, ListEventSources, PutPartnerEvents | Lambda target dispatch on PutEvents; S3 EventBridge notifications; archives capture matching events and `StartReplay` re-dispatches them to the destination bus in a background thread; API destination targets are **invoked over HTTP** on PutEvents — connection auth (Basic, API Key, OAuth client-credentials with token caching and 401/407 refresh), connection/target header/query/body parameter merging with connection precedence, `*` path parameters, dynamic JSON-path values for target HTTP paths/headers/query strings resolved from the original event before body transformation, and the AWS default headers (`User-Agent: Amazon/EventBridge/ApiDestinations`, default `Content-Type: application/json; charset=utf-8`), which connection and target parameters cannot override; redirects are not followed (a `3xx` is a non-retryable delivery failure), only `http(s)` invocation and OAuth authorization endpoints are accepted, `HttpMethod` and `AuthorizationType` are validated against their enums, and a connection that is not `AUTHORIZED` is not invoked (`DeauthorizeConnection` clears its stored credentials) — the 24h retry pipeline, rate limiting, and DLQs are not modeled; SaaS/partner APIs are otherwise control-plane stubs. Event patterns are **validated** — `PutRule`, `TestEventPattern`, `CreateArchive` and `UpdateArchive` reject a malformed pattern with `InvalidEventPatternException` carrying AWS's own reason text — and evaluate `prefix`/`suffix` (plain or case-insensitive via a nested `equals-ignore-case`), `wildcard` (AWS semantics — only `*` is special, `\` escapes — with catastrophic backtracking ruled out), `equals-ignore-case` (AWS's per-character case alternation), `exactly`, `cidr` (IPv4/IPv6, host bits floored, `/32` and `/128` refused as AWS refuses them), `numeric` (as the grammar it is: one comparison or a lower-then-upper bound), `exists` (leaf nodes only, so an object or an empty array does not exist), `anything-but` (a literal, a list, or a nested `prefix`/`suffix`/`wildcard`/`equals-ignore-case`, singly or as a list), and `$or` at any field position — expanded into flat alternatives at rule creation, so AWS's per-leaf last-write-wins collision rule and its 1000-combination cap both hold. All ten envelope fields are filterable, an unmodelled key is a path the event lacks rather than an error, `resources` is an intersection, array values are matched per element (with AWS's array-consistency rule), and values compare as JSON so a string never equals a number. An operand or key the matcher cannot evaluate never matches, rather than raising or matching everything. Not modeled: the 4096-character pattern limit, the wildcard-complexity refusal, and the 256-leaf rule-size cap |
+| **EventBridge** | CreateEventBus, UpdateEventBus, DeleteEventBus, ListEventBuses, DescribeEventBus, PutRule, DeleteRule, ListRules, DescribeRule, EnableRule, DisableRule, PutTargets, RemoveTargets, ListTargetsByRule, ListRuleNamesByTarget, PutEvents, TestEventPattern, TagResource, UntagResource, ListTagsForResource, CreateArchive, DeleteArchive, DescribeArchive, UpdateArchive, ListArchives, PutPermission, RemovePermission, CreateConnection, DescribeConnection, DeleteConnection, UpdateConnection, DeauthorizeConnection, ListConnections, CreateApiDestination, DescribeApiDestination, DeleteApiDestination, UpdateApiDestination, ListApiDestinations, StartReplay, DescribeReplay, ListReplays, CancelReplay, CreateEndpoint, DeleteEndpoint, DescribeEndpoint, ListEndpoints, UpdateEndpoint, ActivateEventSource, DeactivateEventSource, DescribeEventSource, CreatePartnerEventSource, DeletePartnerEventSource, DescribePartnerEventSource, ListPartnerEventSources, ListPartnerEventSourceAccounts, ListEventSources, PutPartnerEvents | Lambda target dispatch on PutEvents; S3 EventBridge notifications; archives capture matching events and `StartReplay` re-dispatches them to the destination bus in a background thread; API destination targets are **invoked over HTTP** on PutEvents — connection auth (Basic, API Key, OAuth client-credentials with token caching and 401/407 refresh), connection/target header/query/body parameter merging with connection precedence, `*` path parameters, dynamic JSON-path parameter values resolved from the untransformed event, and the AWS default headers (`User-Agent: Amazon/EventBridge/ApiDestinations`, default `Content-Type: application/json; charset=utf-8`), which connection and target parameters cannot override; redirects are not followed (a `3xx` is a non-retryable delivery failure), only `http(s)` invocation and OAuth authorization endpoints are accepted, `HttpMethod` and `AuthorizationType` are validated against their enums, and a connection that is not `AUTHORIZED` is not invoked (`DeauthorizeConnection` clears its stored credentials) — the 24h retry pipeline, rate limiting, and DLQs are not modeled; SaaS/partner APIs are otherwise control-plane stubs. Event patterns are **validated** — `PutRule`, `TestEventPattern`, `CreateArchive` and `UpdateArchive` reject a malformed pattern with `InvalidEventPatternException` carrying AWS's own reason text — and evaluate `prefix`/`suffix` (plain or case-insensitive via a nested `equals-ignore-case`), `wildcard` (AWS semantics — only `*` is special, `\` escapes — with catastrophic backtracking ruled out), `equals-ignore-case` (AWS's per-character case alternation), `exactly`, `cidr` (IPv4/IPv6, host bits floored, `/32` and `/128` refused as AWS refuses them), `numeric` (as the grammar it is: one comparison or a lower-then-upper bound), `exists` (leaf nodes only, so an object or an empty array does not exist), `anything-but` (a literal, a list, or a nested `prefix`/`suffix`/`wildcard`/`equals-ignore-case`, singly or as a list), and `$or` at any field position — expanded into flat alternatives at rule creation, so AWS's per-leaf last-write-wins collision rule and its 1000-combination cap both hold. All ten envelope fields are filterable, an unmodelled key is a path the event lacks rather than an error, `resources` is an intersection, array values are matched per element (with AWS's array-consistency rule), and values compare as JSON so a string never equals a number. An operand or key the matcher cannot evaluate never matches, rather than raising or matching everything. Not modeled: the 4096-character pattern limit, the wildcard-complexity refusal, and the 256-leaf rule-size cap |
| **Kinesis** | CreateStream, DeleteStream, DescribeStream, DescribeStreamSummary, ListStreams, ListShards, PutRecord, PutRecords, GetShardIterator, GetRecords, IncreaseStreamRetentionPeriod, DecreaseStreamRetentionPeriod, MergeShards, SplitShard, UpdateShardCount, StartStreamEncryption, StopStreamEncryption, EnableEnhancedMonitoring, DisableEnhancedMonitoring, RegisterStreamConsumer, DeregisterStreamConsumer, ListStreamConsumers, DescribeStreamConsumer, AddTagsToStream, RemoveTagsFromStream, ListTagsForStream | Partition key → shard routing; AWS limits enforced (1 MB/record, 500 records/batch, 5 MB payload, 256-char partition key) |
| **CloudWatch Metrics** | PutMetricData, GetMetricStatistics, GetMetricData, ListMetrics, PutMetricAlarm, PutCompositeAlarm, DescribeAlarms, DescribeAlarmsForMetric, DescribeAlarmHistory, DeleteAlarms, SetAlarmState, EnableAlarmActions, DisableAlarmActions, TagResource, UntagResource, ListTagsForResource, PutDashboard, GetDashboard, DeleteDashboards, ListDashboards | CBOR and JSON protocol |
| **SES** | SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail, VerifyEmailIdentity, VerifyEmailAddress, VerifyDomainIdentity, VerifyDomainDkim, ListIdentities, ListVerifiedEmailAddresses, GetIdentityVerificationAttributes, GetIdentityDkimAttributes, DeleteIdentity, GetSendQuota, GetSendStatistics, SetIdentityNotificationTopic, SetIdentityFeedbackForwardingEnabled, CreateConfigurationSet, DeleteConfigurationSet, DescribeConfigurationSet, ListConfigurationSets, CreateTemplate, GetTemplate, UpdateTemplate, DeleteTemplate, ListTemplates | Emails stored in-memory, not sent |
@@ -427,7 +427,7 @@ subnet = ec2.create_subnet(
| **Bedrock Agent** | 72 operations — agents (versions, aliases, action groups, collaborators, agent knowledge bases, PrepareAgent), knowledge bases (data sources, ingestion jobs — `StartIngestionJob` reads the S3 data source and reports real statistics, `FAILED` with `failureReasons` when the source is unreadable — documents), flows (aliases, versions, ValidateFlowDefinition, PrepareFlow), prompts with versions, tagging | All 72 operations verified against botocore `bedrock-agent-2023-06-05` |
| **Bedrock Agent Runtime** | InvokeAgent, InvokeInlineAgent, GetAgentMemory, DeleteAgentMemory, Retrieve, RetrieveAndGenerate, RetrieveAndGenerateStream, Rerank, CreateSession, GetSession, UpdateSession, DeleteSession, EndSession, ListSessions, CreateInvocation, ListInvocations, PutInvocationStep, GetInvocationStep, ListInvocationSteps, InvokeFlow, StartFlowExecution, StopFlowExecution, GetFlowExecution, ListFlowExecutions, ListFlowExecutionEvents, GetExecutionFlowSnapshot, OptimizePrompt | All 31 operations verified against botocore `bedrock-agent-runtime-2023-07-26`; eventstream responses on streaming operations; `Retrieve` searches the documents Knowledge Base ingestion stored (lexical scoring — no embeddings) and returns content, `s3Location` and score; `InvokeAgent` answers a canned reply without orchestration and emits no trace events — it never fabricates an `ORCHESTRATE` trace |
| **Bedrock AgentCore** | Control plane (`bedrock-agentcore-control`): CreateAgentRuntime, GetAgentRuntime, ListAgentRuntimes, UpdateAgentRuntime, DeleteAgentRuntime, ListAgentRuntimeVersions, CreateAgentRuntimeEndpoint, GetAgentRuntimeEndpoint, ListAgentRuntimeEndpoints, UpdateAgentRuntimeEndpoint, DeleteAgentRuntimeEndpoint. Data plane (`bedrock-agentcore`): InvokeAgentRuntime | Agent-runtime lifecycle with `CREATING`/`UPDATING`→`READY` transitions, versioned ARNs (`agent/{uuid}:{version}`, `agentEndpoint/{uuid}`); request/response shapes verified against botocore `bedrock-agentcore-control` / `bedrock-agentcore`; account- and region-scoped state; `InvokeAgentRuntime` is a deterministic echo (no model inference), matching the requested emulation scope |
-| **Transcribe** | StartTranscriptionJob, GetTranscriptionJob, ListTranscriptionJobs, DeleteTranscriptionJob | Batch transcription jobs only; streaming is a separate endpoint (`transcribestreaming`). All four operations verified against botocore `transcribe-2017-10-26`. A job starts `IN_PROGRESS` with `StartTime` set, as on AWS, and reaches `COMPLETED` over `TRANSCRIBE_JOB_RUN_SECONDS` (default 2, `0` completes immediately); `QUEUED`, which AWS reaches only for a request that opted into job queueing (`JobExecutionSettings.AllowDeferredExecution`) while the account is at its concurrent job limit, is not modelled; the media object is read from MiniStack S3 via an `s3://`, path-style or virtual-hosted HTTPS URI, and an unreadable URI fails the job with a `FailureReason` rather than erroring at `Start`, as on AWS; the transcript is written back to S3 in the real result format (`results.transcripts`, word-level `results.items`, `results.audio_segments`, plus `results.segments` and `results.speaker_labels` when the matching `Settings` are set) at `OutputBucketName`/`OutputKey`, or to an auto-created `ministack-transcribe-output` bucket. `IdentifyLanguage` and `IdentifyMultipleLanguages` resolve a language on completion, `ContentRedaction` controls whether a `redacted-` copy replaces or accompanies the transcript, and `Subtitles` writes WebVTT and SubRip files, redacted alongside the transcript when redaction is on. Reaching a terminal state publishes a `Transcribe Job State Change` event, so EventBridge rules downstream of a job fire. There is no speech recognition, so the transcript is deterministic canned text keyed on a digest of the media URI |
+| **Transcribe** | StartTranscriptionJob, GetTranscriptionJob, ListTranscriptionJobs, DeleteTranscriptionJob | Batch transcription jobs only; streaming is a separate endpoint (`transcribestreaming`). All four operations verified against botocore `transcribe-2017-10-26`. A job starts `IN_PROGRESS` with `StartTime` set, as on AWS, and reaches `COMPLETED` over two seconds; `QUEUED`, which AWS reaches only for a request that opted into job queueing (`JobExecutionSettings.AllowDeferredExecution`) while the account is at its concurrent job limit, is not modelled; the media object is read from MiniStack S3 via an `s3://`, path-style or virtual-hosted HTTPS URI, and an unreadable URI fails the job with a `FailureReason` rather than erroring at `Start`, as on AWS; the transcript is written back to S3 in the real result format (`results.transcripts`, word-level `results.items`, `results.audio_segments`, plus `results.segments` and `results.speaker_labels` when the matching `Settings` are set) at `OutputBucketName`/`OutputKey`, or to an auto-created `ministack-transcribe-output` bucket. `IdentifyLanguage` and `IdentifyMultipleLanguages` resolve a language on completion, `ContentRedaction` controls whether a `redacted-` copy replaces or accompanies the transcript, and `Subtitles` writes WebVTT and SubRip files, redacted alongside the transcript when redaction is on. Reaching a terminal state publishes a `Transcribe Job State Change` event, so EventBridge rules downstream of a job fire. There is no speech recognition, so the transcript is deterministic canned text keyed on a digest of the media URI |
| **Translate** | StartTextTranslationJob, DescribeTextTranslationJob, ListTextTranslationJobs, StopTextTranslationJob | Batch text translation jobs only; the synchronous `TranslateText` / `TranslateDocument` pair and the custom terminology / parallel data families are not implemented. All four operations verified against botocore `translate-2017-07-01`. Jobs walk `SUBMITTED` → `IN_PROGRESS` → `COMPLETED` over `TRANSLATE_JOB_RUN_SECONDS` (default 2, `0` completes immediately); every document under `InputDataConfig.S3Uri` is read from MiniStack S3 and written back to the rewritten output location AWS uses — `OutputDataConfig.S3Uri` is reported as `s3://<bucket>/<prefix><account-id>-TranslateText-<JobId>/` — as `<target-code>.<input name>`, with a `details/<code>.auxiliary-translation-details.json` summary per target language. `text/plain` is translated line by line, `text/html` keeps its markup and translates only text nodes, `application/x-xliff+xml` gets a populated `<target>` in every `<trans-unit>` plus `target-language` on every `<file>`, and the three Office ZIP types are copied through. A document that can't be read as its content type is counted in `JobDetails` and the job ends `COMPLETED_WITH_ERROR`; an empty or unreadable input location fails the job with a `Message` rather than erroring at `Start`. `ClientToken` is idempotent, `StopTextTranslationJob` reaches a running worker, and reaching a terminal state publishes a `Translate TextTranslationJob State Change` event, so EventBridge rules downstream of a job fire. There is no machine translation, so the output is deterministic canned text derived from the source |
| **MSK** | CreateCluster, ListClusters, DescribeCluster, DeleteCluster, GetBootstrapBrokers, ListNodes, CreateConfiguration, ListConfigurations, DescribeConfiguration, ListConfigurationRevisions, DescribeConfigurationRevision, BatchAssociateScramSecret, BatchDisassociateScramSecret, ListScramSecrets, TagResource, UntagResource, ListTagsForResource | Kafka control plane; `GetBootstrapBrokers` honors `MINISTACK_MSK_BOOTSTRAP` so clients route to a real broker you bring (Redpanda, Kafka, KRaft) — the Kafka wire protocol itself is not emulated |
| **WAF v2** | CreateWebACL, GetWebACL, UpdateWebACL, DeleteWebACL, ListWebACLs, AssociateWebACL, DisassociateWebACL, GetWebACLForResource, ListResourcesForWebACL, CreateIPSet, GetIPSet, UpdateIPSet, DeleteIPSet, ListIPSets, CreateRuleGroup, GetRuleGroup, UpdateRuleGroup, DeleteRuleGroup, ListRuleGroups, TagResource, UntagResource, ListTagsForResource, CheckCapacity, DescribeManagedRuleGroup | LockToken enforced on Update/Delete; resource associations tracked |
@@ -863,7 +863,6 @@ end-to-end without any client config.
| `MINISTACK_MSK_BOOTSTRAP_TLS` | _(unset)_ | TLS bootstrap string (`BootstrapBrokerStringTls`) |
| `MINISTACK_MSK_BOOTSTRAP_SASL_SCRAM` | _(unset)_ | SASL/SCRAM bootstrap string (`BootstrapBrokerStringSaslScram`) |
| `MINISTACK_MSK_BOOTSTRAP_SASL_IAM` | _(unset)_ | SASL/IAM bootstrap string (`BootstrapBrokerStringSaslIam`) |
-| `TRANSCRIBE_JOB_RUN_SECONDS` | `2` | Wall-clock time a Transcribe job spends between `IN_PROGRESS` and `COMPLETED`. Set `0` to complete immediately, or raise it when a test needs to observe `IN_PROGRESS`. Also settable without a restart by posting `{"transcribe._JOB_RUN_SECONDS": 10}` to `/_ministack/config` |
| `TRANSLATE_JOB_RUN_SECONDS` | `2` | Wall-clock time a Translate batch job spends between `SUBMITTED` and `COMPLETED`. Set `0` to complete immediately, or raise it when a test needs to observe `IN_PROGRESS` or stop a running job. Also settable without a restart by posting `{"translate._JOB_RUN_SECONDS": 10}` to `/_ministack/config` |
### API Gateway HTTP proxy execution model
diff --git a/ministack/app.py b/ministack/app.py
index 18207549..95334689 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -30,14 +30,20 @@ _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":
- try:
- from importlib.metadata import version as _pkg_version
+_VERSION = os.environ.get("MINISTACK_VERSION") or ""
- _VERSION = _pkg_version("ministack")
- except Exception:
- pass
+
+def _version() -> str:
+ """The reported version, resolved on first ask and cached."""
+ global _VERSION
+ if not _VERSION:
+ try:
+ from importlib.metadata import version as _pkg_version
+
+ _VERSION = _pkg_version("ministack")
+ except Exception:
+ _VERSION = "dev"
+ return _VERSION
# Matches host headers like "{apiId}.execute-api.<host>" or "{apiId}.execute-api.<host>:4566"
_EXECUTE_API_RE = re.compile(r"^([a-f0-9]{8})\.execute-api\." + re.escape(_MINISTACK_HOST) + r"(?::\d+)?$")
@@ -773,7 +779,8 @@ def _handle_health_request(path: str, request_id: str):
{
"services": {s: "available" for s in SERVICE_HANDLERS},
"edition": os.environ.get("MINISTACK_EDITION", "light"),
- "version": _VERSION,
+ "version": _version(),
+ "iot_mtls": _iot_mtls_state,
"ready_scripts": dict(_ready_scripts_state),
}
).encode(),
@@ -784,15 +791,20 @@ def _handle_ready_request(path: str, request_id: str):
"""Return readiness state once ready.d scripts have completed."""
if path != "/_ministack/ready":
return None
- ready = _ready_scripts_state["status"] == "completed"
+ # The mTLS listener binds after the HTTP port, so readiness covers it: a
+ # consumer polling one endpoint does not race the MQTT port.
+ ready = (_ready_scripts_state["status"] == "completed"
+ and _iot_mtls_state != "starting")
status = 200 if ready else 503
+ body = dict(_ready_scripts_state)
+ body["iot_mtls"] = _iot_mtls_state
return (
status,
{
"Content-Type": "application/json",
"x-amzn-requestid": request_id,
},
- json.dumps(dict(_ready_scripts_state)).encode(),
+ json.dumps(body).encode(),
)
@@ -870,7 +882,9 @@ async def _handle_cognito_get_request(method: str, path: str, headers: dict, que
if cognito._get_pool_unscoped(pool_id) is not None:
region = extract_region(headers) or "us-east-1"
host = headers.get("host") or headers.get("Host")
- return cognito.well_known_openid_configuration(pool_id, region, host)
+ scheme = headers.get("x-forwarded-proto") or "http"
+ return cognito.well_known_openid_configuration(
+ pool_id, region, host, scheme)
if path == "/oauth2/authorize" and method == "GET":
return _get_module("cognito").handle_oauth2_authorize(method, path, headers, query_params)
@@ -1114,9 +1128,35 @@ async def _handle_pre_body_request(method: str, path: str, headers: dict, query_
if response is not None:
return response
+ response = _handle_rds_ca_request(method, path)
+ if response is not None:
+ return response
+
return await _handle_admin_reset(path, method, query_params)
+def _handle_rds_ca_request(method: str, path: str):
+ """`GET /_ministack/rds/ca.pem` returns the CA that signs DB server
+ certificates, the local stand-in for AWS's certificate bundle."""
+ if path != "/_ministack/rds/ca.pem" or method != "GET":
+ return None
+ try:
+ from ministack.services import rds
+
+ cert_pem = rds.pg_ca_cert_pem()
+ except Exception as e:
+ return (
+ 503,
+ {"Content-Type": "application/json"},
+ json.dumps({"message": str(e)}).encode(),
+ )
+ return (
+ 200,
+ {"Content-Type": "application/x-pem-file"},
+ cert_pem.encode(),
+ )
+
+
def _handle_iot_ca_request(method: str, path: str):
"""`GET /_ministack/iot/ca.pem` returns the Local CA root certificate.
@@ -1389,13 +1429,29 @@ async def _handle_s3_control_request(path: str, method: str, body: bytes, query_
b"{}",
)
+ # An undefined /v20180820 path answers 400 InvalidURI inside an
+ # <ErrorResponse> wrapper, with <URI> echoing the bad segment (measured eu-north-1 2026-09-19).
+ from xml.sax.saxutils import escape as _xml_esc
+
+ bad_uri = path.split("/v20180820/", 1)[-1] if "/v20180820/" in path else path.lstrip("/")
+ unsupported = (
+ '<?xml version="1.0" encoding="UTF-8"?>'
+ "<ErrorResponse><Error>"
+ "<Code>InvalidURI</Code>"
+ "<Message>Couldn't parse the specified URI.</Message>"
+ f"<URI>{_xml_esc(bad_uri)}</URI>"
+ "</Error>"
+ f"<RequestId>{request_id}</RequestId>"
+ f"<HostId>{uuid.uuid4().hex}</HostId>"
+ "</ErrorResponse>"
+ ).encode()
return (
- 200,
+ 400,
{
- "Content-Type": "application/json",
+ "Content-Type": "application/xml",
"x-amzn-requestid": request_id,
},
- b"{}",
+ unsupported,
)
@@ -2457,6 +2513,10 @@ async def app(scope, receive, send):
else:
headers[key] = decoded
+ # USE_SSL terminates TLS here, so no proxy sets the header; fill it in.
+ if scope.get("scheme") == "https":
+ headers.setdefault("x-forwarded-proto", "https")
+
request_id = str(uuid.uuid4())
# If a /_ministack/reset is in flight, wait for it to finish before
@@ -2532,8 +2592,34 @@ async def app(scope, receive, send):
# ---------------------------------------------------------------------------
+# The boot task that imports iot and binds the mTLS listener, and the state
+# /_ministack/health and /_ministack/ready report for it.
+_iot_mtls_task = None
+_iot_mtls_state = "disabled"
+
+
+async def _start_iot_mtls():
+ """Import the iot module and bind the mTLS MQTT listener."""
+ global _iot_mtls_state
+ try:
+ from ministack.services import iot as _iot_svc
+
+ await _iot_svc.mtls_start()
+ if _iot_svc.mtls_is_listening():
+ _iot_mtls_state = "listening"
+ else:
+ # mtls_start returns without binding when the listener is off
+ # (cryptography missing, or IOT_MTLS_ENABLED=0), which is not a
+ # failure and must not report a healthy MiniStack as degraded.
+ _iot_mtls_state = "degraded" if _iot_svc.mtls_enabled() else "disabled"
+ except Exception as e:
+ _iot_mtls_state = "degraded"
+ logger.warning("IoT mTLS listener startup failed: %s", e)
+
+
async def _handle_lifespan(scope, receive, send):
"""Handle ASGI lifespan events."""
+ global _iot_mtls_task, _iot_mtls_state
while True:
message = await receive()
if message["type"] == "lifespan.startup":
@@ -2624,12 +2710,12 @@ async def _handle_lifespan(scope, receive, send):
if _iot_mtls_env in ("0", "false", "no", "off"):
logger.debug("IOT_MTLS_ENABLED=%s — skipping iot module import.", _iot_mtls_env)
else:
- try:
- from ministack.services import iot as _iot_svc
-
- await _iot_svc.mtls_start()
- except Exception as e:
- logger.warning("IoT mTLS listener startup failed: %s", e)
+ # Off the startup sequence: importing iot and minting the
+ # broker certificate is the bulk of a boot. The listener comes
+ # up after the HTTP port; /_ministack/ready waits for it and
+ # shutdown joins the task before stopping the listener.
+ _iot_mtls_state = "starting"
+ _iot_mtls_task = asyncio.create_task(_start_iot_mtls())
# Start DSQL wire proxies for clusters restored from persistence.
# Guarded on the module already being loaded (i.e. it had state
# or was used this boot) so we never import dsql just for this.
@@ -2673,6 +2759,11 @@ async def _handle_lifespan(scope, receive, send):
await transfer.sftp_stop()
except Exception as e:
logger.debug("Transfer SFTP shutdown error: %s", e)
+ if _iot_mtls_task is not None:
+ try:
+ await _iot_mtls_task
+ except Exception as e:
+ logger.debug("IoT mTLS startup error: %s", e)
_iot_mod = sys.modules.get("ministack.services.iot")
if _iot_mod is not None:
try:
diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.py
index 9df6e297..1cee45d5 100644
--- a/ministack/core/iam_evaluator.py
+++ b/ministack/core/iam_evaluator.py
@@ -82,28 +82,47 @@ class AuthError:
# Wildcard matching (IAM-style)
# ---------------------------------------------------------------------------
-_FNMATCH_CACHE: dict[str, re.Pattern] = {}
+_FNMATCH_CACHE: dict[tuple[str, bool], 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()
+def _fnmatch_compile(pattern: str, ignore_case: bool) -> re.Pattern:
+ key = (pattern.lower() if ignore_case else pattern, ignore_case)
compiled = _FNMATCH_CACHE.get(key)
if compiled is None:
regex = ""
- for ch in key:
+ for ch in key[0]:
if ch == "*":
regex += ".*"
elif ch == "?":
regex += "."
else:
regex += re.escape(ch)
- compiled = re.compile(f"^{regex}$", re.IGNORECASE)
+ compiled = re.compile(f"^{regex}$", re.IGNORECASE if ignore_case else 0)
if len(_FNMATCH_CACHE) < 4096:
_FNMATCH_CACHE[key] = compiled
- return compiled.match(value) is not None
+ return compiled
+
+
+def fnmatch_iam(value: str, pattern: str) -> bool:
+ """Case-insensitive IAM wildcard match, for Action/NotAction.
+
+ ``*`` = any chars, ``?`` = one char.
+ """
+ if pattern == "*":
+ return True
+ return _fnmatch_compile(pattern, True).match(value) is not None
+
+
+def fnmatch_iam_cs(value: str, pattern: str) -> bool:
+ """Case-sensitive IAM wildcard match, for Resource/NotResource, StringLike
+ and the Arn operators: "In the Resource element, the IAM user name is case
+ sensitive" (reference_policies_elements_resource), "Case-sensitive matching"
+ for StringLike and "Case-sensitive matching of the ARN" for ArnEquals/ArnLike
+ (reference_policies_elements_condition_operators).
+ """
+ if pattern == "*":
+ return True
+ return _fnmatch_compile(pattern, False).match(value) is not None
# ---------------------------------------------------------------------------
@@ -122,9 +141,9 @@ def _action_matches(request_action: str, actions: list[str],
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)
+ return any(fnmatch_iam_cs(resource_arn, p) for p in resources)
if not_resources:
- return not any(fnmatch_iam(resource_arn, p) for p in not_resources)
+ return not any(fnmatch_iam_cs(resource_arn, p) for p in not_resources)
return True
@@ -224,11 +243,11 @@ def _op_string_not_equals_ignore_case(actual: str, expected: str) -> bool:
def _op_string_like(actual: str, expected: str) -> bool:
- return fnmatch_iam(actual, expected)
+ return fnmatch_iam_cs(actual, expected)
def _op_string_not_like(actual: str, expected: str) -> bool:
- return not fnmatch_iam(actual, expected)
+ return not fnmatch_iam_cs(actual, expected)
def _op_numeric(actual: str, expected: str, cmp: str) -> bool:
@@ -307,11 +326,11 @@ def _op_not_ip_address(actual: str, expected: str) -> bool:
def _op_arn_like(actual: str, expected: str) -> bool:
- return fnmatch_iam(actual, expected)
+ return fnmatch_iam_cs(actual, expected)
def _op_arn_not_like(actual: str, expected: str) -> bool:
- return not fnmatch_iam(actual, expected)
+ return not fnmatch_iam_cs(actual, expected)
# Operator dispatch table
diff --git a/ministack/core/rds_iam.py b/ministack/core/rds_iam.py
index f0af137f..7f81470a 100644
--- a/ministack/core/rds_iam.py
+++ b/ministack/core/rds_iam.py
@@ -16,7 +16,15 @@ import time
from dataclasses import dataclass
from urllib.parse import parse_qsl, urlsplit
-from ministack.core.iam_evaluator import CredentialResolutionError, resolve_credential
+from ministack.core.iam_evaluator import (
+ AuthError,
+ CredentialResolutionError,
+ EvalContext,
+ evaluate,
+ resolve_credential,
+ resolve_principal,
+)
+from ministack.core.responses import request_scope
from ministack.core.sigv4 import build_canonical_request, build_string_to_sign, calculate_signature, signatures_match
_MAX_TOKEN_LENGTH = 65536
@@ -181,3 +189,110 @@ def verify_rds_iam_token(
db_user=db_user,
expires_at=expires_at,
)
+
+
+# Stage 5 of #1744: resource-bound authorization. No runtime callers, no AUTH
+# lookup; integration gates AUTH at its call site.
+
+@dataclass(frozen=True)
+class RdsIamAuthorizationError:
+ """A bounded failure code, with no client token or credential material."""
+
+ code: str
+
+
+@dataclass(frozen=True)
+class AuthorizedRdsConnection:
+ identity: VerifiedRdsToken
+ resource_arn: str
+
+
+def authorize_rds_iam_token(
+ token: str,
+ *,
+ account_id: str,
+ region: str,
+ resource_kind: str,
+ resource_identifier: str,
+ db_user: str,
+ reader_endpoint: bool = False,
+) -> AuthorizedRdsConnection | RdsIamAuthorizationError | RdsIamTokenError:
+ """Verify and authorize against a trusted instance or cluster identifier.
+
+ The future broker must bind these arguments to its resource capability,
+ not accept a target/account claimed by the client. Endpoint/port, enablement,
+ and the stable dbuser resource ID are read from that resource's scoped state.
+ Aurora members use the parent cluster's enablement and resource ID, but the
+ member's endpoint. Cluster callers may explicitly select the reader endpoint.
+ Cross-account credentials must first assume a role in the resource account.
+ A success is a point-in-time decision, not a reusable authorization cache.
+ """
+ from ministack.services import rds
+
+ if (
+ not isinstance(account_id, str) or not re.fullmatch(r"[0-9]{12}", account_id)
+ or not isinstance(region, str) or not re.fullmatch(r"[a-z0-9-]+", region)
+ or resource_kind not in ("instance", "cluster")
+ or not isinstance(resource_identifier, str) or not resource_identifier
+ or type(reader_endpoint) is not bool
+ or (reader_endpoint and resource_kind != "cluster")
+ ):
+ return RdsIamAuthorizationError("InvalidTarget")
+
+ store = rds._instances if resource_kind == "instance" else rds._clusters
+ target = store.get_scoped(account_id, region, resource_identifier)
+ if target is None:
+ return RdsIamAuthorizationError("ResourceNotFound")
+ engines = ("mysql", "aurora", "aurora-mysql") if resource_kind == "instance" else ("aurora", "aurora-mysql")
+ if target.get("Engine") not in engines:
+ return RdsIamAuthorizationError("UnsupportedEngine")
+ if resource_kind == "instance" and target.get("Engine") != "mysql" and not target.get("DBClusterIdentifier"):
+ return RdsIamAuthorizationError("InvalidTarget")
+
+ owner = target
+ resource_id_key = "DbiResourceId" if resource_kind == "instance" else "DbClusterResourceId"
+ if resource_kind == "instance" and target.get("DBClusterIdentifier"):
+ owner = rds._clusters.get_scoped(account_id, region, target["DBClusterIdentifier"])
+ if owner is None:
+ return RdsIamAuthorizationError("ResourceNotFound")
+ if owner.get("Engine") not in ("aurora", "aurora-mysql"):
+ return RdsIamAuthorizationError("UnsupportedEngine")
+ resource_id_key = "DbClusterResourceId"
+ if owner.get("IAMDatabaseAuthenticationEnabled") is not True:
+ return RdsIamAuthorizationError("IAMDatabaseAuthenticationDisabled")
+ resource_id = owner.get(resource_id_key)
+ prefix = "db-" if resource_id_key == "DbiResourceId" else "cluster-"
+ if not isinstance(resource_id, str) or not re.fullmatch(prefix + r"[A-Za-z0-9]+", resource_id):
+ return RdsIamAuthorizationError("InvalidTarget")
+
+ endpoint = target.get("ReaderEndpoint" if reader_endpoint else "Endpoint")
+ if isinstance(endpoint, dict):
+ hostname, port = endpoint.get("Address"), endpoint.get("Port")
+ else:
+ hostname, port = endpoint, target.get("Port")
+ verified = verify_rds_iam_token(
+ token, hostname=hostname, port=port, db_user=db_user, region=region, account_id=account_id,
+ )
+ if isinstance(verified, RdsIamTokenError):
+ return verified
+
+ # MiniStack's credential and RDS stores currently issue arn:aws identities.
+ resource_arn = f"arn:aws:rds-db:{region}:{account_id}:dbuser:{resource_id}/{db_user}"
+ # Policy gathering includes ambient-scoped user/group/managed-policy stores.
+ # Pin the explicit resource account, restoring both contextvars on all exits.
+ with request_scope(account_id, region):
+ principal = resolve_principal(verified.access_key_id, account_id)
+ if (
+ isinstance(principal, AuthError) or principal.account != account_id
+ or principal.arn != verified.principal_arn or principal.type != verified.principal_type
+ ):
+ return RdsIamAuthorizationError("InvalidCredentials")
+ if principal.policies is not None:
+ result = evaluate(EvalContext(
+ principal_arn=principal.arn, principal_type=principal.type,
+ principal_account=account_id, action="rds-db:connect",
+ resource_arn=resource_arn, region=region,
+ ), principal.policies)
+ if result.decision != "Allow":
+ return RdsIamAuthorizationError(result.decision)
+ return AuthorizedRdsConnection(verified, resource_arn)
diff --git a/ministack/core/rds_iam_authorization.py b/ministack/core/rds_iam_authorization.py
deleted file mode 100644
index e75c291d..00000000
--- a/ministack/core/rds_iam_authorization.py
+++ /dev/null
@@ -1,134 +0,0 @@
-# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
-# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).
-"""Stage 5 of #1744: strict resource-bound RDS IAM authorization.
-
-No runtime callers or AUTH lookup. Future integration must define and test its
-AUTH gate separately from IAMDatabaseAuthenticationEnabled before using this
-helper. This is not a TLS check or permission to enable MySQL login.
-"""
-
-import re
-from dataclasses import dataclass, replace
-
-from ministack.core.iam_evaluator import AuthError, EvalContext, evaluate, resolve_principal
-from ministack.core.rds_iam import RdsIamTokenError, VerifiedRdsToken, verify_rds_iam_token
-from ministack.core.responses import request_scope
-
-
-@dataclass(frozen=True)
-class RdsIamAuthorizationError:
- """A bounded failure code, with no client token or credential material."""
-
- code: str
-
-
-@dataclass(frozen=True)
-class AuthorizedRdsConnection:
- identity: VerifiedRdsToken
- resource_arn: str
-
-
-def _resource_policies(policies, resource_arn):
- # The shared evaluator currently case-folds Resource as well as Action.
- # Database usernames are case-sensitive. Match Resource/NotResource here,
- # then leave action, conditions and deny precedence to the shared engine.
- # Do not change policy behavior for unrelated services in this stage.
- def matches(pattern):
- regex = re.escape(pattern).replace(r"\*", ".*").replace(r"\?", ".")
- return re.fullmatch(regex, resource_arn, re.DOTALL) is not None
-
- return [[replace(stmt, resources=["*"], not_resources=[]) for stmt in policy
- if (any(matches(p) for p in stmt.resources) if stmt.resources
- else bool(stmt.not_resources) and not any(matches(p) for p in stmt.not_resources))]
- for policy in policies]
-
-
-def authorize_rds_iam_token(
- token: str,
- *,
- account_id: str,
- region: str,
- resource_kind: str,
- resource_identifier: str,
- db_user: str,
- reader_endpoint: bool = False,
-) -> AuthorizedRdsConnection | RdsIamAuthorizationError | RdsIamTokenError:
- """Verify and authorize against a trusted instance or cluster identifier.
-
- The future broker must bind these arguments to its resource capability,
- not accept a target/account claimed by the client. Endpoint/port, enablement,
- and the stable dbuser resource ID are read from that resource's scoped state.
- Aurora members use the parent cluster's enablement and resource ID, but the
- member's endpoint. Cluster callers may explicitly select the reader endpoint.
- Cross-account credentials must first assume a role in the resource account.
- A success is a point-in-time decision, not a reusable authorization cache.
- """
- from ministack.services import rds
-
- if (
- not isinstance(account_id, str) or not re.fullmatch(r"[0-9]{12}", account_id)
- or not isinstance(region, str) or not re.fullmatch(r"[a-z0-9-]+", region)
- or resource_kind not in ("instance", "cluster")
- or not isinstance(resource_identifier, str) or not resource_identifier
- or type(reader_endpoint) is not bool
- or (reader_endpoint and resource_kind != "cluster")
- ):
- return RdsIamAuthorizationError("InvalidTarget")
-
- store = rds._instances if resource_kind == "instance" else rds._clusters
- target = store.get_scoped(account_id, region, resource_identifier)
- if target is None:
- return RdsIamAuthorizationError("ResourceNotFound")
- engines = ("mysql", "aurora", "aurora-mysql") if resource_kind == "instance" else ("aurora", "aurora-mysql")
- if target.get("Engine") not in engines:
- return RdsIamAuthorizationError("UnsupportedEngine")
- if resource_kind == "instance" and target.get("Engine") != "mysql" and not target.get("DBClusterIdentifier"):
- return RdsIamAuthorizationError("InvalidTarget")
-
- owner = target
- resource_id_key = "DbiResourceId" if resource_kind == "instance" else "DbClusterResourceId"
- if resource_kind == "instance" and target.get("DBClusterIdentifier"):
- owner = rds._clusters.get_scoped(account_id, region, target["DBClusterIdentifier"])
- if owner is None:
- return RdsIamAuthorizationError("ResourceNotFound")
- if owner.get("Engine") not in ("aurora", "aurora-mysql"):
- return RdsIamAuthorizationError("UnsupportedEngine")
- resource_id_key = "DbClusterResourceId"
- if owner.get("IAMDatabaseAuthenticationEnabled") is not True:
- return RdsIamAuthorizationError("IAMDatabaseAuthenticationDisabled")
- resource_id = owner.get(resource_id_key)
- prefix = "db-" if resource_id_key == "DbiResourceId" else "cluster-"
- if not isinstance(resource_id, str) or not re.fullmatch(prefix + r"[A-Za-z0-9]+", resource_id):
- return RdsIamAuthorizationError("InvalidTarget")
-
- endpoint = target.get("ReaderEndpoint" if reader_endpoint else "Endpoint")
- if isinstance(endpoint, dict):
- hostname, port = endpoint.get("Address"), endpoint.get("Port")
- else:
- hostname, port = endpoint, target.get("Port")
- verified = verify_rds_iam_token(
- token, hostname=hostname, port=port, db_user=db_user, region=region, account_id=account_id,
- )
- if isinstance(verified, RdsIamTokenError):
- return verified
-
- # MiniStack's credential and RDS stores currently issue arn:aws identities.
- resource_arn = f"arn:aws:rds-db:{region}:{account_id}:dbuser:{resource_id}/{db_user}"
- # Policy gathering includes ambient-scoped user/group/managed-policy stores.
- # Pin the explicit resource account, restoring both contextvars on all exits.
- with request_scope(account_id, region):
- principal = resolve_principal(verified.access_key_id, account_id)
- if (
- isinstance(principal, AuthError) or principal.account != account_id
- or principal.arn != verified.principal_arn or principal.type != verified.principal_type
- ):
- return RdsIamAuthorizationError("InvalidCredentials")
- if principal.policies is not None:
- result = evaluate(EvalContext(
- principal_arn=principal.arn, principal_type=principal.type,
- principal_account=account_id, action="rds-db:connect",
- resource_arn=resource_arn, region=region,
- ), _resource_policies(principal.policies, resource_arn))
- if result.decision != "Allow":
- return RdsIamAuthorizationError(result.decision)
- return AuthorizedRdsConnection(verified, resource_arn)
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index f594ad93..9daddf12 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -163,6 +163,7 @@ _gateway_responses = AccountRegionScopedDict() # rest_api_id -> {response_type
# rest_api_id -> {deployment_id -> customized gateway responses at CreateDeployment}
_deployed_gateway_responses = AccountRegionScopedDict()
_documentation_parts = AccountRegionScopedDict() # rest_api_id -> {part_id -> DocumentationPart}
+_request_validators = AccountRegionScopedDict() # rest_api_id -> {validator_id -> RequestValidator}
_GATEWAY_RESPONSE_TYPES = (
@@ -795,6 +796,7 @@ def get_state():
"base_path_mappings": copy.deepcopy(_base_path_mappings),
"v1_tags": copy.deepcopy(_v1_tags),
"account_settings": copy.deepcopy(_account_settings),
+ "request_validators": copy.deepcopy(_request_validators),
"gateway_responses": copy.deepcopy(_gateway_responses),
"deployed_gateway_responses": copy.deepcopy(_deployed_gateway_responses),
"documentation_parts": copy.deepcopy(_documentation_parts),
@@ -1011,6 +1013,7 @@ def load_persisted_state(data):
_restore_child_store(_deployments_v1, data.get("deployments_v1", {}), api_regions)
_restore_child_store(_authorizers_v1, data.get("authorizers_v1", {}), api_regions)
_restore_child_store(_models, data.get("models", {}), api_regions)
+ _restore_child_store(_request_validators, data.get("request_validators", {}), api_regions)
_restore_child_store(_gateway_responses, data.get("gateway_responses", {}), api_regions)
_restore_child_store(
_deployed_gateway_responses, data.get("deployed_gateway_responses", {}), api_regions
@@ -1037,6 +1040,7 @@ def reset():
_base_path_mappings.clear()
_v1_tags.clear()
_account_settings.clear()
+ _request_validators.clear()
_gateway_responses.clear()
_deployed_gateway_responses.clear()
_documentation_parts.clear()
@@ -1299,6 +1303,22 @@ async def handle_request(method, path, headers, body, query_params):
if method == "DELETE":
return _delete_authorizer(api_id, auth_id)
+ # /restapis/{id}/requestvalidators[/{validatorId}]
+ elif sub == "requestvalidators":
+ validator_id = parts[3] if len(parts) > 3 else None
+ if not validator_id:
+ if method == "POST":
+ return _create_request_validator(api_id, data)
+ if method == "GET":
+ return _get_request_validators(api_id, query_params)
+ else:
+ if method == "GET":
+ return _get_request_validator(api_id, validator_id)
+ if method == "PATCH":
+ return _update_request_validator(api_id, validator_id, data)
+ if method == "DELETE":
+ return _delete_request_validator(api_id, validator_id)
+
# /restapis/{id}/models[/{modelName}]
elif sub == "models":
model_name = parts[3] if len(parts) > 3 else None
@@ -1994,6 +2014,228 @@ async def _authorize_request_v1(
return None, auth_ctx
+# $context.error.message per gateway response type.
+_GATEWAY_ERROR_MESSAGES = {
+ "INVALID_API_KEY": "Forbidden",
+ "THROTTLED": "Too Many Requests",
+ "QUOTA_EXCEEDED": "Limit Exceeded", # not captured
+ "UNSUPPORTED_MEDIA_TYPE": "Unsupported Media Type",
+ "BAD_REQUEST_BODY": "Invalid request body",
+}
+
+# In-process only; a restart forgets them.
+_throttle_state = {}
+_quota_state = {}
+_QUOTA_PERIOD_SECONDS = {"DAY": 86400, "WEEK": 7 * 86400, "MONTH": 30 * 86400}
+
+
+def _api_key_from_request(headers):
+ return _header_ci(headers, "x-api-key")
+
+
+def _resolve_api_key(value):
+ """The enabled ApiKey record whose value matches, or None."""
+ if not value:
+ return None
+ for _scope, key in _api_keys.all_items():
+ if key.get("value") == value and key.get("enabled", True):
+ return key
+ return None
+
+
+def _usage_plans_for_key(key_id, api_id, stage_name):
+ """Every usage plan that carries this key and covers this api+stage."""
+ plans = []
+ for (account, region, plan_id), plan in list(_usage_plans.all_items()):
+ keys = _usage_plan_keys.get(plan_id, {}) or {}
+ if key_id not in keys:
+ continue
+ for entry in plan.get("apiStages") or []:
+ if entry.get("apiId") == api_id and entry.get("stage") == stage_name:
+ plans.append((plan_id, plan, entry))
+ break
+ return plans
+
+
+def _check_api_key(method_obj, api_id, stage_name, headers):
+ """(error, key_record) for a method with apiKeyRequired."""
+ if not method_obj.get("apiKeyRequired"):
+ return None, None
+ key = _resolve_api_key(_api_key_from_request(headers))
+ if key is None:
+ return _gw_error("INVALID_API_KEY",
+ _GATEWAY_ERROR_MESSAGES["INVALID_API_KEY"]), None
+ if not _usage_plans_for_key(key["id"], api_id, stage_name):
+ return _gw_error("INVALID_API_KEY",
+ _GATEWAY_ERROR_MESSAGES["INVALID_API_KEY"]), None
+ return None, key
+
+
+def _method_throttle_settings(stage, resource_path, http_method):
+ """The method override, else the stage-wide "*/*" entry."""
+ settings = stage.get("methodSettings") or {}
+ stripped = resource_path.lstrip("/")
+ # UpdateStage keeps the path's leading slash; accept either spelling.
+ for key in (f"/{stripped}/{http_method}", f"{stripped}/{http_method}", "*/*"):
+ entry = settings.get(key)
+ if isinstance(entry, dict) and (
+ "throttlingRateLimit" in entry or "throttlingBurstLimit" in entry):
+ return entry
+ return None
+
+
+def _check_throttle(stage, api_id, stage_name, resource_path, http_method):
+ """Token bucket per method: rate refills, burst caps, 0/0 refuses all."""
+ entry = _method_throttle_settings(stage, resource_path, http_method)
+ if entry is None:
+ return None
+ rate = entry.get("throttlingRateLimit")
+ burst = entry.get("throttlingBurstLimit")
+ if rate is None and burst is None:
+ return None
+ rate = float(rate if rate is not None else 0)
+ burst = float(burst if burst is not None else 0)
+ if rate <= 0 and burst <= 0:
+ return _gw_error("THROTTLED", _GATEWAY_ERROR_MESSAGES["THROTTLED"])
+ slot = (api_id, stage_name, resource_path, http_method)
+ now = time.time()
+ tokens, last = _throttle_state.get(slot, (burst, now))
+ tokens = min(burst, tokens + (now - last) * rate)
+ if tokens < 1:
+ _throttle_state[slot] = (tokens, now)
+ return _gw_error("THROTTLED", _GATEWAY_ERROR_MESSAGES["THROTTLED"])
+ _throttle_state[slot] = (tokens - 1, now)
+ return None
+
+
+def _check_quota(key, api_id, stage_name):
+ """Usage-plan quota, per key per plan period."""
+ if key is None:
+ return None
+ now = time.time()
+ for plan_id, plan, _entry in _usage_plans_for_key(key["id"], api_id, stage_name):
+ quota = plan.get("quota") or {}
+ limit = quota.get("limit")
+ if limit is None:
+ continue
+ period = _QUOTA_PERIOD_SECONDS.get(quota.get("period", "DAY"), 86400)
+ slot = (plan_id, key["id"])
+ used, window_start = _quota_state.get(slot, (0, now))
+ if now - window_start >= period:
+ used, window_start = 0, now
+ if used >= int(limit):
+ _quota_state[slot] = (used, window_start)
+ return _gw_error("QUOTA_EXCEEDED",
+ _GATEWAY_ERROR_MESSAGES["QUOTA_EXCEEDED"])
+ _quota_state[slot] = (used + 1, window_start)
+ return None
+
+
+def _missing_request_parameters(method_obj, request, headers, query_params):
+ """The absent required request parameters, in declaration order."""
+ missing = []
+ for name, required in (method_obj.get("requestParameters") or {}).items():
+ if not required:
+ continue
+ if name.startswith("method.request.querystring."):
+ key = name[len("method.request.querystring."):]
+ value = (query_params or {}).get(key)
+ if value in (None, "", []):
+ missing.append(key)
+ elif name.startswith("method.request.header."):
+ key = name[len("method.request.header."):]
+ if not _header_ci(headers, key):
+ missing.append(key)
+ elif name.startswith("method.request.path."):
+ key = name[len("method.request.path."):]
+ if not (request.get("path_params") or {}).get(key):
+ missing.append(key)
+ return missing
+
+
+def _json_schema_violation(schema, document):
+ """The first violation, or None. Subset: type, required, property type."""
+ if not isinstance(schema, dict):
+ return None
+ expected = schema.get("type")
+ if expected == "object" and not isinstance(document, dict):
+ return "expected an object"
+ if expected == "array" and not isinstance(document, list):
+ return "expected an array"
+ if expected == "string" and not isinstance(document, str):
+ return "expected a string"
+ if expected in ("number", "integer") and not isinstance(document, (int, float)):
+ return "expected a number"
+ if isinstance(document, dict):
+ for name in schema.get("required") or []:
+ if name not in document:
+ return f"missing required property {name}"
+ for name, sub in (schema.get("properties") or {}).items():
+ if name in document:
+ violation = _json_schema_violation(sub, document[name])
+ if violation:
+ return violation
+ return None
+
+
+def _check_request_validation(method_obj, api_id, request, headers, body, query_params):
+ """The method's request validator: parameters first, then the body."""
+ validator_id = method_obj.get("requestValidatorId")
+ if not validator_id:
+ return None
+ validator = _request_validators.get(api_id, {}).get(validator_id)
+ if not validator:
+ return None
+ if validator.get("validateRequestParameters"):
+ missing = _missing_request_parameters(method_obj, request, headers, query_params)
+ if missing:
+ return _gw_error(
+ "BAD_REQUEST_PARAMETERS",
+ "Missing required request parameters: [" + ", ".join(missing) + "]")
+ if not validator.get("validateRequestBody"):
+ return None
+ content_type = (_header_ci(headers, "content-type") or "application/json")
+ model_name = (method_obj.get("requestModels") or {}).get(
+ content_type.split(";", 1)[0].strip()) or (
+ method_obj.get("requestModels") or {}).get("application/json")
+ if not model_name:
+ return None
+ model = _models.get(api_id, {}).get(model_name)
+ if not model:
+ return None
+ schema = model.get("schema")
+ if isinstance(schema, str):
+ try:
+ schema = json.loads(schema or "{}")
+ except json.JSONDecodeError:
+ return None
+ try:
+ document = json.loads(body or b"{}")
+ except (json.JSONDecodeError, TypeError, ValueError):
+ return _gw_error("BAD_REQUEST_BODY",
+ _GATEWAY_ERROR_MESSAGES["BAD_REQUEST_BODY"])
+ if _json_schema_violation(schema, document):
+ return _gw_error("BAD_REQUEST_BODY",
+ _GATEWAY_ERROR_MESSAGES["BAD_REQUEST_BODY"])
+ return None
+
+
+def _check_passthrough_behavior(integration, headers):
+ """NEVER rejects a content type no request template matches."""
+ behavior = (integration.get("passthroughBehavior") or "WHEN_NO_MATCH").upper()
+ if behavior != "NEVER":
+ return None
+ templates = integration.get("requestTemplates") or {}
+ if not templates:
+ return None
+ content_type = (_header_ci(headers, "content-type")
+ or "application/json").split(";", 1)[0].strip().lower()
+ if any(key.split(";", 1)[0].strip().lower() == content_type for key in templates):
+ return None
+ return _gw_error("UNSUPPORTED_MEDIA_TYPE",
+ _GATEWAY_ERROR_MESSAGES["UNSUPPORTED_MEDIA_TYPE"])
+
+
async def _handle_execute_in_scope(
api_id, stage_name, method, path, headers, body, query_params,
owner_account_id, owner_region,
@@ -2081,6 +2323,25 @@ async def _execute_in_scope(
if auth_error is not None:
return auth_error
+ # API Gateway's own checks, in the order it runs them.
+ key_error, api_key = _check_api_key(method_obj, api_id, stage_name, headers)
+ if key_error is not None:
+ return key_error
+ throttle_error = _check_throttle(
+ stage, api_id, stage_name, resource["path"], method)
+ if throttle_error is not None:
+ return throttle_error
+ quota_error = _check_quota(api_key, api_id, stage_name)
+ if quota_error is not None:
+ return quota_error
+ validation_error = _check_request_validation(
+ method_obj, api_id, request, headers, body, query_params)
+ if validation_error is not None:
+ return validation_error
+ media_error = _check_passthrough_behavior(integration, headers)
+ if media_error is not None:
+ return media_error
+
int_type = integration.get("type", "")
if int_type in ("AWS_PROXY", "AWS"):
@@ -3039,6 +3300,7 @@ def _put_method(api_id, resource_id, http_method, data):
"operationName": data.get("operationName", ""),
"requestParameters": data.get("requestParameters", {}),
"requestModels": data.get("requestModels", {}),
+ "requestValidatorId": data.get("requestValidatorId"),
"methodResponses": {},
"methodIntegration": None,
}
@@ -3455,6 +3717,60 @@ def _delete_authorizer(api_id, auth_id):
# ---- Control plane: Models ----
+def _create_request_validator(api_id, data):
+ if api_id not in _rest_apis:
+ return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
+ validator = {
+ "id": _new_id()[:6],
+ "name": data.get("name", ""),
+ "validateRequestBody": bool(data.get("validateRequestBody", False)),
+ "validateRequestParameters": bool(data.get("validateRequestParameters", False)),
+ }
+ _request_validators.setdefault(api_id, {})[validator["id"]] = validator
+ return _v1_response(validator, 201)
+
+
+def _get_request_validators(api_id, query_params):
+ if api_id not in _rest_apis:
+ return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
+ return _v1_paginated_response(
+ list(_request_validators.get(api_id, {}).values()), query_params)
+
+
+def _get_request_validator(api_id, validator_id):
+ validator = _request_validators.get(api_id, {}).get(validator_id)
+ if not validator:
+ return _v1_error(
+ "NotFoundException", "Invalid Request Validator identifier specified", 404)
+ return _v1_response(validator)
+
+
+def _update_request_validator(api_id, validator_id, data):
+ validator = _request_validators.get(api_id, {}).get(validator_id)
+ if not validator:
+ return _v1_error(
+ "NotFoundException", "Invalid Request Validator identifier specified", 404)
+ for op in data.get("patchOperations", []) or []:
+ if op.get("op") != "replace":
+ continue
+ path = (op.get("path") or "").lstrip("/")
+ value = op.get("value")
+ if path == "name":
+ validator["name"] = value
+ elif path in ("validateRequestBody", "validateRequestParameters"):
+ validator[path] = str(value).lower() == "true"
+ return _v1_response(validator)
+
+
+def _delete_request_validator(api_id, validator_id):
+ validators = _request_validators.get(api_id, {})
+ if validator_id not in validators:
+ return _v1_error(
+ "NotFoundException", "Invalid Request Validator identifier specified", 404)
+ del validators[validator_id]
+ return 204, {}, b""
+
+
def _create_model(api_id, data):
if api_id not in _rest_apis:
return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
diff --git a/ministack/services/appconfig.py b/ministack/services/appconfig.py
index 221c1a00..0aad8deb 100644
--- a/ministack/services/appconfig.py
+++ b/ministack/services/appconfig.py
@@ -719,6 +719,21 @@ def _start_configuration_session(body):
return _json(201, {"InitialConfigurationToken": token})
+def _retrieval_time_content(app_id, profile_id, content: bytes) -> bytes:
+ """Feature flags are served in retrieval-time format: the `values` map
+ lifted to the top level. Anything else is served verbatim."""
+ profile = _config_profiles.get(f"{app_id}/{profile_id}") or {}
+ if profile.get("Type") != "AWS.AppConfig.FeatureFlags":
+ return content
+ try:
+ document = json.loads(content)
+ except (ValueError, TypeError):
+ return content
+ if not isinstance(document, dict) or not isinstance(document.get("values"), dict):
+ return content
+ return json.dumps(document["values"]).encode("utf-8")
+
+
def _get_latest_configuration(token):
session = _sessions.get(token)
if not session:
@@ -750,6 +765,7 @@ def _get_latest_configuration(token):
raw = version_record["Content"]
content = raw if isinstance(raw, bytes) else raw.encode("utf-8")
content_type = version_record.get("ContentType", "application/octet-stream")
+ content = _retrieval_time_content(app_id, profile_id, content)
next_token = uuid.uuid4().hex
_sessions[next_token] = session.copy()
diff --git a/ministack/services/autoscaling.py b/ministack/services/autoscaling.py
index 93f878b1..d96c07b4 100644
--- a/ministack/services/autoscaling.py
+++ b/ministack/services/autoscaling.py
@@ -225,7 +225,7 @@ def _create_asg(p):
if not name:
return _error("ValidationError", "AutoScalingGroupName is required")
if name in _asgs:
- return _error("AlreadyExistsFault", f"AutoScalingGroup {name} already exists")
+ return _error("AlreadyExists", f"AutoScalingGroup {name} already exists")
arn = _asg_arn(name)
_asgs[name] = {
@@ -471,7 +471,7 @@ def _create_lc(p):
if not name:
return _error("ValidationError", "LaunchConfigurationName is required")
if name in _launch_configs:
- return _error("AlreadyExistsFault", f"LaunchConfiguration {name} already exists")
+ return _error("AlreadyExists", f"LaunchConfiguration {name} already exists")
arn = f"arn:aws:autoscaling:{get_region()}:{get_account_id()}:launchConfiguration:{new_uuid()}:launchConfigurationName/{name}"
_launch_configs[name] = {
"LaunchConfigurationName": name,
diff --git a/ministack/services/bedrock_agent.py b/ministack/services/bedrock_agent.py
index c20f8493..c5ab6de6 100644
--- a/ministack/services/bedrock_agent.py
+++ b/ministack/services/bedrock_agent.py
@@ -932,7 +932,14 @@ def _run_s3_ingestion(kb_id: str, ds_id: str, ds_rec: dict) -> tuple[dict, list]
doc_key = f"{kb_id}/{ds_id}/{key}"
existing = doc_key in _kb_document_texts
uri = f"s3://{bucket_name}/{key}"
- _kb_document_texts[doc_key] = {"Text": text, "Uri": uri}
+ # The sidecar carries the attributes a Retrieve filter matches on.
+ metadata = {}
+ if f"{key}.metadata.json" in bucket["objects"]:
+ metadata = _metadata_attributes(
+ s3_svc._get_object_data(bucket_name, f"{key}.metadata.json"))
+ _kb_document_texts[doc_key] = {
+ "Text": text, "Uri": uri, "Metadata": metadata,
+ }
_kb_documents[doc_key] = {
"DocumentIdentifier": {"dataSourceType": "S3", "s3": {"uri": uri}},
"Status": "INDEXED",
@@ -946,6 +953,43 @@ def _run_s3_ingestion(kb_id: str, ds_id: str, ds_rec: dict) -> tuple[dict, list]
return stats, failures
+def _metadata_attributes(raw: bytes) -> dict:
+ """The attributes of a document's ``.metadata.json`` sidecar, flattened to
+ ``{key: value}``.
+
+ Two spellings are accepted: a plain scalar, and the typed form botocore
+ models as ``MetadataAttributeValue`` -- ``{"value": {"type": "STRING",
+ "stringValue": ...}}`` with type in BOOLEAN, NUMBER, STRING, STRING_LIST.
+ ``includeForEmbedding`` only affects embedding, never filtering, so it is
+ ignored here.
+ """
+ try:
+ document = json.loads(raw or b"{}")
+ except (ValueError, TypeError):
+ return {}
+ attributes = (document or {}).get("metadataAttributes")
+ if not isinstance(attributes, dict):
+ return {}
+ out = {}
+ for key, entry in attributes.items():
+ if isinstance(entry, dict):
+ value = entry.get("value", entry)
+ if isinstance(value, dict):
+ typed = {
+ "STRING": value.get("stringValue"),
+ "NUMBER": value.get("numberValue"),
+ "BOOLEAN": value.get("booleanValue"),
+ "STRING_LIST": value.get("stringListValue"),
+ }
+ value = typed.get(value.get("type"))
+ if value is None:
+ continue
+ out[key] = value
+ else:
+ out[key] = entry
+ return out
+
+
def _start_ingestion_job(kb_id: str, ds_id: str, body) -> tuple:
body_obj, err = _parse_body(body)
if err:
diff --git a/ministack/services/bedrock_agent_runtime.py b/ministack/services/bedrock_agent_runtime.py
index 1690b3a0..3741aa7e 100644
--- a/ministack/services/bedrock_agent_runtime.py
+++ b/ministack/services/bedrock_agent_runtime.py
@@ -285,6 +285,66 @@ def _delete_agent_memory(agent_id: str, alias_id: str, query_params) -> tuple:
# ===========================================================================
+# The metadata filter grammar of RetrievalFilter (botocore bedrock-agent-runtime):
+# eleven leaf comparators plus the andAll / orAll combinators.
+def _filter_leaf(op: str, attribute: dict, metadata: dict) -> bool:
+ key = (attribute or {}).get("key")
+ expected = (attribute or {}).get("value")
+ present = isinstance(metadata, dict) and key in metadata
+ actual = metadata.get(key) if present else None
+ # An absent attribute matches nothing, and its negation matches: the
+ # document simply does not carry the key.
+ if op in ("notEquals", "notIn"):
+ if not present:
+ return True
+ elif not present:
+ return False
+ if op == "equals":
+ return actual == expected
+ if op == "notEquals":
+ return actual != expected
+ if op in ("greaterThan", "greaterThanOrEquals", "lessThan", "lessThanOrEquals"):
+ try:
+ if op == "greaterThan":
+ return actual > expected
+ if op == "greaterThanOrEquals":
+ return actual >= expected
+ if op == "lessThan":
+ return actual < expected
+ return actual <= expected
+ except TypeError:
+ return False
+ if op == "in":
+ return isinstance(expected, list) and actual in expected
+ if op == "notIn":
+ return not (isinstance(expected, list) and actual in expected)
+ if op == "startsWith":
+ return isinstance(actual, str) and isinstance(expected, str) \
+ and actual.startswith(expected)
+ if op == "stringContains":
+ return isinstance(actual, str) and isinstance(expected, str) \
+ and expected in actual
+ if op == "listContains":
+ return isinstance(actual, list) and expected in actual
+ return False
+
+
+def _filter_matches(flt, metadata: dict) -> bool:
+ """Whether a document's metadata satisfies a RetrievalFilter."""
+ if not isinstance(flt, dict) or not flt:
+ return True
+ if "andAll" in flt:
+ clauses = flt["andAll"] or []
+ return all(_filter_matches(c, metadata) for c in clauses)
+ if "orAll" in flt:
+ clauses = flt["orAll"] or []
+ return any(_filter_matches(c, metadata) for c in clauses)
+ for op, attribute in flt.items():
+ if not _filter_leaf(op, attribute, metadata):
+ return False
+ return True
+
+
def _retrieve(kb_id: str, body) -> tuple:
body_obj, err = _parse_body(body)
if err:
@@ -295,9 +355,10 @@ def _retrieve(kb_id: str, body) -> tuple:
from ministack.services import bedrock_agent as agent_svc
if kb_id not in agent_svc._knowledge_bases:
return _not_found(f"Knowledge base {kb_id} not found.")
- number_of_results = (((body_obj.get("retrievalConfiguration") or {})
- .get("vectorSearchConfiguration") or {})
- .get("numberOfResults")) or 5
+ vector_config = ((body_obj.get("retrievalConfiguration") or {})
+ .get("vectorSearchConfiguration") or {})
+ number_of_results = vector_config.get("numberOfResults") or 5
+ metadata_filter = vector_config.get("filter")
# Lexical retrieval over the documents ingestion actually stored — no
# embeddings locally, so scoring is term overlap: the fraction of query
# terms present in the document.
@@ -306,16 +367,24 @@ def _retrieve(kb_id: str, body) -> tuple:
for key, doc in agent_svc._kb_document_texts.items():
if not key.startswith(f"{kb_id}/"):
continue
+ if not _filter_matches(metadata_filter, doc.get("Metadata") or {}):
+ continue
doc_terms = set(re.findall(r"[a-z0-9]+", doc["Text"].lower()))
hits = len(terms & doc_terms)
if hits:
scored.append((hits / len(terms), doc))
scored.sort(key=lambda pair: pair[0], reverse=True)
- results = [{
- "Content": {"Text": doc["Text"], "Type": "TEXT"},
- "Location": {"Type": "S3", "S3Location": {"Uri": doc["Uri"]}},
- "Score": round(score, 4),
- } for score, doc in scored[:number_of_results]]
+ results = []
+ for score, doc in scored[:number_of_results]:
+ result = {
+ "Content": {"Text": doc["Text"], "Type": "TEXT"},
+ "Location": {"Type": "S3", "S3Location": {"Uri": doc["Uri"]}},
+ "Score": round(score, 4),
+ }
+ # RetrievalResultMetadata has min 1, so it is omitted when empty.
+ if doc.get("Metadata"):
+ result["Metadata"] = doc["Metadata"]
+ results.append(result)
return _json({"RetrievalResults": results})
diff --git a/ministack/services/bedrock_agentcore.py b/ministack/services/bedrock_agentcore.py
index f6befda2..bd9b04d5 100644
--- a/ministack/services/bedrock_agentcore.py
+++ b/ministack/services/bedrock_agentcore.py
@@ -22,12 +22,12 @@ against botocore ``bedrock-agentcore-control`` / ``bedrock-agentcore``
service-2.json.
"""
import copy
+import datetime
import json
import logging
import re
import secrets
import string
-import time
from urllib.parse import unquote
from ministack.core.responses import (
@@ -37,6 +37,7 @@ from ministack.core.responses import (
get_region,
json_response,
new_uuid,
+ now_iso,
)
logger = logging.getLogger("bedrock_agentcore")
@@ -106,6 +107,17 @@ def _workload_identity_arn(name: str) -> str:
f"workload-identity-directory/default/workload-identity/{name}")
+def _iso(value):
+ """Every timestamp this service answers is the model's DateTimestamp, which
+ carries timestampFormat iso8601 -- an RFC 3339 string, not an epoch number.
+ Records persisted before this took epoch floats, so those are converted on
+ the way out."""
+ if isinstance(value, (int, float)):
+ return (datetime.datetime.fromtimestamp(value, datetime.timezone.utc)
+ .strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z")
+ return value
+
+
def _validation(message: str):
return error_response_json("ValidationException", message, 400)
@@ -145,7 +157,7 @@ def _create_agent_runtime(body):
runtime_uuid = new_uuid()
runtime_id = _resource_id(name)
version = "1"
- now = time.time()
+ now = now_iso()
arn = _runtime_arn(runtime_uuid, version)
workload = {"workloadIdentityArn": _workload_identity_arn(name)}
record = {
@@ -199,7 +211,7 @@ def _list_agent_runtimes(body):
"agentRuntimeVersion": r["agentRuntimeVersion"],
"agentRuntimeName": r["agentRuntimeName"],
"description": r.get("description", ""),
- "lastUpdatedAt": r["lastUpdatedAt"],
+ "lastUpdatedAt": _iso(r["lastUpdatedAt"]),
"status": r["status"],
})
return json_response({"agentRuntimes": summaries})
@@ -215,7 +227,7 @@ def _list_agent_runtime_versions(runtime_id, body):
"agentRuntimeVersion": record["agentRuntimeVersion"],
"agentRuntimeName": record["agentRuntimeName"],
"description": record.get("description", ""),
- "lastUpdatedAt": record["lastUpdatedAt"],
+ "lastUpdatedAt": _iso(record["lastUpdatedAt"]),
"status": record["status"],
}
return json_response({"agentRuntimes": [summary]})
@@ -229,7 +241,7 @@ def _update_agent_runtime(runtime_id, body):
for field in ("agentRuntimeArtifact", "roleArn", "networkConfiguration"):
if not data.get(field):
return _validation(f"{field} is required")
- now = time.time()
+ now = now_iso()
new_version = str(int(record["agentRuntimeVersion"]) + 1)
record["agentRuntimeVersion"] = new_version
record["agentRuntimeArn"] = _runtime_arn(record["_uuid"], new_version)
@@ -248,7 +260,7 @@ def _update_agent_runtime(runtime_id, body):
"agentRuntimeId": runtime_id,
"workloadIdentityDetails": record.get("workloadIdentityDetails"),
"agentRuntimeVersion": new_version,
- "createdAt": record["createdAt"],
+ "createdAt": _iso(record["createdAt"]),
"lastUpdatedAt": now,
"status": "UPDATING",
})
@@ -280,7 +292,7 @@ def _create_agent_runtime_endpoint(runtime_id, body):
return _conflict(f"Endpoint {name} already exists")
target_version = data.get("agentRuntimeVersion") or runtime["agentRuntimeVersion"]
endpoint_uuid = new_uuid()
- now = time.time()
+ now = now_iso()
record = {
"name": name,
"id": _resource_id(name),
@@ -316,8 +328,8 @@ def _get_agent_runtime_endpoint(runtime_id, endpoint_name):
"agentRuntimeArn": record["agentRuntimeArn"],
"description": record.get("description", ""),
"status": record["status"],
- "createdAt": record["createdAt"],
- "lastUpdatedAt": record["lastUpdatedAt"],
+ "createdAt": _iso(record["createdAt"]),
+ "lastUpdatedAt": _iso(record["lastUpdatedAt"]),
"name": record["name"],
"id": record["id"],
})
@@ -338,8 +350,8 @@ def _list_agent_runtime_endpoints(runtime_id, body):
"status": record["status"],
"id": record["id"],
"description": record.get("description", ""),
- "createdAt": record["createdAt"],
- "lastUpdatedAt": record["lastUpdatedAt"],
+ "createdAt": _iso(record["createdAt"]),
+ "lastUpdatedAt": _iso(record["lastUpdatedAt"]),
})
return json_response({"runtimeEndpoints": items})
@@ -352,7 +364,7 @@ def _update_agent_runtime_endpoint(runtime_id, endpoint_name, body):
if record is None:
return _not_found(f"Endpoint {endpoint_name} not found")
data = _parse_body(body)
- now = time.time()
+ now = now_iso()
if data.get("agentRuntimeVersion"):
record["targetVersion"] = data["agentRuntimeVersion"]
record["liveVersion"] = data["agentRuntimeVersion"]
@@ -366,7 +378,7 @@ def _update_agent_runtime_endpoint(runtime_id, endpoint_name, body):
"agentRuntimeEndpointArn": record["agentRuntimeEndpointArn"],
"agentRuntimeArn": record["agentRuntimeArn"],
"status": "UPDATING",
- "createdAt": record["createdAt"],
+ "createdAt": _iso(record["createdAt"]),
"lastUpdatedAt": now,
})
diff --git a/ministack/services/bedrock_runtime.py b/ministack/services/bedrock_runtime.py
index f8d78f5a..dd7086dc 100644
--- a/ministack/services/bedrock_runtime.py
+++ b/ministack/services/bedrock_runtime.py
@@ -218,7 +218,9 @@ def _mock_reply(model_id: str, messages, system) -> str:
def _build_converse_response(model_id: str, messages, system, started_at_ms: int, text: str,
input_tokens: int | None = None,
- output_tokens: int | None = None) -> dict:
+ output_tokens: int | None = None,
+ content_blocks=None,
+ stop_reason: str = "end_turn") -> dict:
if input_tokens is None:
input_tokens = _estimate_tokens(_system_text(system) + _messages_text(messages))
if output_tokens is None:
@@ -228,10 +230,10 @@ def _build_converse_response(model_id: str, messages, system, started_at_ms: int
"output": {
"message": {
"role": "assistant",
- "content": [{"text": text}],
+ "content": content_blocks if content_blocks else [{"text": text}],
}
},
- "stopReason": "end_turn",
+ "stopReason": stop_reason,
"usage": {
"inputTokens": input_tokens,
"outputTokens": output_tokens,
@@ -246,29 +248,101 @@ def _build_converse_response(model_id: str, messages, system, started_at_ms: int
# ---------------------------------------------------------------------------
-def _proxy_to_openai_chat(model_id: str, messages, system, inference_config) -> str | None:
- """Forward to MINISTACK_BEDROCK_PROXY_URL using OpenAI chat-completions
- shape. Returns assistant text on success, None on any failure (caller falls
- back to mock)."""
+def _openai_tools(tool_config):
+ """The Converse toolConfig as OpenAI function tools, the shape Ollama's
+ OpenAI-compatible endpoint takes. toolSpec.inputSchema.json is already a
+ JSON Schema, which is what `parameters` wants."""
+ tools = []
+ for entry in (tool_config or {}).get("tools") or []:
+ spec = (entry or {}).get("toolSpec")
+ if not isinstance(spec, dict) or not spec.get("name"):
+ continue
+ function = {"name": spec["name"],
+ "parameters": (spec.get("inputSchema") or {}).get("json") or {}}
+ if spec.get("description"):
+ function["description"] = spec["description"]
+ tools.append({"type": "function", "function": function})
+ choice = (tool_config or {}).get("toolChoice") or {}
+ if "any" in choice:
+ tool_choice = "required"
+ elif "tool" in choice:
+ tool_choice = {"type": "function",
+ "function": {"name": (choice["tool"] or {}).get("name", "")}}
+ elif "auto" in choice:
+ tool_choice = "auto"
+ else:
+ tool_choice = None
+ return tools, tool_choice
+
+
+def _openai_messages(messages, system):
+ """Converse messages as OpenAI chat messages.
+
+ A toolUse block becomes an assistant tool_call and a toolResult block
+ becomes a role "tool" message, so a tool-calling loop survives the round
+ trip instead of losing its history.
+ """
+ out = []
+ for entry in system or []:
+ if isinstance(entry, dict) and "text" in entry:
+ out.append({"role": "system", "content": entry["text"]})
+ for message in messages or []:
+ role = message.get("role", "user")
+ parts, tool_calls, tool_results = [], [], []
+ for block in message.get("content") or []:
+ if not isinstance(block, dict):
+ continue
+ if "text" in block:
+ parts.append(block["text"])
+ elif "toolUse" in block:
+ use = block["toolUse"] or {}
+ tool_calls.append({
+ "id": use.get("toolUseId", ""),
+ "type": "function",
+ "function": {"name": use.get("name", ""),
+ "arguments": json.dumps(use.get("input") or {})},
+ })
+ elif "toolResult" in block:
+ result = block["toolResult"] or {}
+ texts = []
+ for item in result.get("content") or []:
+ if not isinstance(item, dict):
+ continue
+ if "text" in item:
+ texts.append(item["text"])
+ elif "json" in item:
+ texts.append(json.dumps(item["json"]))
+ tool_results.append({
+ "role": "tool",
+ "tool_call_id": result.get("toolUseId", ""),
+ "content": "\n".join(texts),
+ })
+ if tool_calls:
+ out.append({"role": "assistant", "content": "\n".join(parts) or None,
+ "tool_calls": tool_calls})
+ elif parts:
+ out.append({"role": role, "content": "\n".join(parts)})
+ out.extend(tool_results)
+ return out
+
+
+def _proxy_openai_chat_message(model_id: str, messages, system, inference_config,
+ tool_config=None):
+ """Forward to MINISTACK_BEDROCK_PROXY_URL in OpenAI chat-completions shape
+ and return the assistant message object, or None on any failure (the caller
+ falls back to the mock)."""
if not _PROXY_URL:
return None
- openai_messages = []
- for s in system or []:
- if isinstance(s, dict) and "text" in s:
- openai_messages.append({"role": "system", "content": s["text"]})
- for m in messages or []:
- role = m.get("role", "user")
- parts = []
- for c in m.get("content") or []:
- if isinstance(c, dict) and "text" in c:
- parts.append(c["text"])
- if parts:
- openai_messages.append({"role": role, "content": "\n".join(parts)})
payload = {
"model": model_id,
- "messages": openai_messages,
+ "messages": _openai_messages(messages, system),
"stream": False,
}
+ tools, tool_choice = _openai_tools(tool_config)
+ if tools:
+ payload["tools"] = tools
+ if tool_choice is not None:
+ payload["tool_choice"] = tool_choice
if inference_config:
if "maxTokens" in inference_config:
payload["max_tokens"] = inference_config["maxTokens"]
@@ -278,9 +352,8 @@ def _proxy_to_openai_chat(model_id: str, messages, system, inference_config) ->
payload["top_p"] = inference_config["topP"]
if "stopSequences" in inference_config:
payload["stop"] = inference_config["stopSequences"]
- url = f"{_PROXY_URL}/v1/chat/completions"
req = urllib.request.Request(
- url,
+ f"{_PROXY_URL}/v1/chat/completions",
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
@@ -295,9 +368,50 @@ def _proxy_to_openai_chat(model_id: str, messages, system, inference_config) ->
logger.exception("bedrock proxy returned malformed response, falling back to mock")
return None
try:
- return data["choices"][0]["message"]["content"]
+ message = data["choices"][0]["message"]
except (KeyError, IndexError, TypeError):
return None
+ return message if isinstance(message, dict) else None
+
+
+def _converse_blocks_from_message(message):
+ """The assistant content blocks for an OpenAI message, plus the stop reason.
+
+ An OpenAI tool_call becomes a Converse toolUse block; a model that asked for
+ a tool stops with tool_use rather than end_turn.
+ """
+ blocks, stop_reason = [], "end_turn"
+ text = message.get("content")
+ if isinstance(text, str) and text:
+ blocks.append({"text": text})
+ for index, call in enumerate(message.get("tool_calls") or []):
+ function = (call or {}).get("function") or {}
+ raw = function.get("arguments")
+ if isinstance(raw, str):
+ try:
+ arguments = json.loads(raw or "{}")
+ except ValueError:
+ # A model that emits unparseable arguments is a documented
+ # Converse outcome, not a proxy failure.
+ return blocks, "malformed_tool_use"
+ else:
+ arguments = raw or {}
+ blocks.append({"toolUse": {
+ "toolUseId": call.get("id") or f"tooluse_{index}",
+ "name": function.get("name", ""),
+ "input": arguments,
+ }})
+ stop_reason = "tool_use"
+ return blocks, stop_reason
+
+
+def _proxy_to_openai_chat(model_id: str, messages, system, inference_config) -> str | None:
+ """The assistant text only, for the callers that do not handle tools."""
+ message = _proxy_openai_chat_message(model_id, messages, system, inference_config)
+ if message is None:
+ return None
+ content = message.get("content")
+ return content if isinstance(content, str) else None
# ---------------------------------------------------------------------------
@@ -366,9 +480,15 @@ def _converse(model_id: str, headers, body) -> tuple:
"x-amzn-bedrock-output-token-count": str(response["usage"]["outputTokens"]),
}, json.dumps(response).encode()
- text = _proxy_to_openai_chat(model_id, messages, system, inference_config)
- if text is None:
+ tool_config = body_obj.get("toolConfig")
+ message = _proxy_openai_chat_message(
+ model_id, messages, system, inference_config, tool_config)
+ blocks, stop_reason = ([], "end_turn")
+ if message is None:
text = _mock_reply(model_id, messages, system)
+ else:
+ blocks, stop_reason = _converse_blocks_from_message(message)
+ text = "".join(b["text"] for b in blocks if "text" in b)
output_assessment = None
if guardrail is not None:
@@ -376,10 +496,17 @@ def _converse(model_id: str, headers, body) -> tuple:
output_assessment = output_result["assessment"]
if output_result["blocked"]:
text = guardrail.get("BlockedOutputsMessaging") or "Blocked by guardrail."
+ # A blocked output replaces the turn, tool calls included: serving
+ # the original blocks would hand back what the guardrail refused.
+ blocks, stop_reason = [], "end_turn"
elif output_result["anonymized"]:
text = output_result["masked_text"]
+ blocks = ([{"text": text}]
+ + [b for b in blocks if "toolUse" in b])
- response = _build_converse_response(model_id, messages, system, started, text)
+ response = _build_converse_response(
+ model_id, messages, system, started, text,
+ content_blocks=blocks or None, stop_reason=stop_reason)
if guardrail is not None:
if output_assessment and any(
f.get("action") == "BLOCKED"
@@ -436,10 +563,14 @@ def _es_event(event_type: str, payload: dict) -> bytes:
def _build_converse_stream(model_id: str, messages, system, started_at_ms: int, text: str,
- stop_reason: str = "end_turn") -> bytes:
+ stop_reason: str = "end_turn", tool_uses=()) -> bytes:
"""Emit the AWS ConverseStream event sequence:
messageStart -> contentBlockDelta* -> contentBlockStop -> messageStop -> metadata
All events under :event-type, payload is application/json per AWS wire trace.
+
+ A tool call adds its own block after the text one: contentBlockStart carries
+ toolUseId and name, and the input arrives as a contentBlockDelta whose
+ toolUse.input is a JSON string, per ToolUseBlockStart / ToolUseBlockDelta.
"""
stream = b""
stream += _es_event("messageStart", {"role": "assistant"})
@@ -459,6 +590,17 @@ def _build_converse_stream(model_id: str, messages, system, started_at_ms: int,
"delta": {"text": ""},
})
stream += _es_event("contentBlockStop", {"contentBlockIndex": 0})
+ for offset, use in enumerate(tool_uses or ()):
+ index = offset + 1
+ stream += _es_event("contentBlockStart", {
+ "contentBlockIndex": index,
+ "start": {"toolUse": {"toolUseId": use["toolUseId"], "name": use["name"]}},
+ })
+ stream += _es_event("contentBlockDelta", {
+ "contentBlockIndex": index,
+ "delta": {"toolUse": {"input": json.dumps(use.get("input") or {})}},
+ })
+ stream += _es_event("contentBlockStop", {"contentBlockIndex": index})
stream += _es_event("messageStop", {"stopReason": stop_reason})
input_tokens = _estimate_tokens(_system_text(system) + _messages_text(messages))
output_tokens = _estimate_tokens(text)
@@ -506,20 +648,31 @@ def _converse_stream(model_id: str, headers, body) -> tuple:
stop_reason = "guardrail_intervened"
guardrail = None # no output pass on a blocked input
+ tool_uses = []
if stop_reason is None:
- text = _proxy_to_openai_chat(model_id, messages, system, inference_config)
- if text is None:
+ message = _proxy_openai_chat_message(
+ model_id, messages, system, inference_config, body_obj.get("toolConfig"))
+ if message is None:
text = _mock_reply(model_id, messages, system)
+ else:
+ blocks, proxied_stop = _converse_blocks_from_message(message)
+ text = "".join(b["text"] for b in blocks if "text" in b)
+ tool_uses = [b["toolUse"] for b in blocks if "toolUse" in b]
+ if proxied_stop != "end_turn":
+ stop_reason = proxied_stop
if guardrail is not None:
output_result = _evaluate_guardrail(guardrail, "OUTPUT", text)
if output_result["blocked"]:
text = guardrail.get("BlockedOutputsMessaging") or "Blocked by guardrail."
stop_reason = "guardrail_intervened"
+ # A blocked output withholds the tool calls with the text.
+ tool_uses = []
elif output_result["anonymized"]:
text = output_result["masked_text"]
stream_bytes = _build_converse_stream(model_id, messages, system, started, text,
- stop_reason=stop_reason or "end_turn")
+ stop_reason=stop_reason or "end_turn",
+ tool_uses=tool_uses)
resp_headers = {
"Content-Type": "application/vnd.amazon.eventstream",
"x-amzn-bedrock-content-type": "application/json",
diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.py
index 0c37af7f..7f190ab5 100644
--- a/ministack/services/cloudformation/changesets.py
+++ b/ministack/services/cloudformation/changesets.py
@@ -397,7 +397,7 @@ def _execute_change_set(params):
f"ChangeSet [{cs_name}] does not exist", 404)
if cs["ExecutionStatus"] != "AVAILABLE":
- return _error("InvalidChangeSetStatusException",
+ return _error("InvalidChangeSetStatus",
f"ChangeSet [{cs_name}] is in {cs['ExecutionStatus']} status")
cs["ExecutionStatus"] = "EXECUTE_IN_PROGRESS"
diff --git a/ministack/services/cloudformation/engine.py b/ministack/services/cloudformation/engine.py
index 1e61e657..b77f2267 100644
--- a/ministack/services/cloudformation/engine.py
+++ b/ministack/services/cloudformation/engine.py
@@ -326,6 +326,7 @@ _MAPPING_ATTRIBUTES_MAX = 200
_NAME_MAX_CHARS = 255
_DESCRIPTION_MAX_BYTES = 1024
_PARAMETER_VALUE_MAX_BYTES = 4096
+_DYNAMIC_REFERENCES_MAX = 60 # "60 dynamic references in a stack template" (quotas table)
def _quota_error(noun: str, count: int, maximum: int) -> ValueError:
@@ -366,6 +367,10 @@ def _validate_template_limits(template: dict) -> None:
raise ValueError(
f"Template format error: Mapping attribute name {str(attribute)[:32]}"
f"... of mapping {name} may not exceed {_NAME_MAX_CHARS} characters")
+ refs: set = set()
+ _find_dynamic_references(template, refs)
+ if len(refs) > _DYNAMIC_REFERENCES_MAX:
+ raise _quota_error("dynamic references", len(refs), _DYNAMIC_REFERENCES_MAX)
description = template.get("Description")
if isinstance(description, str) and len(description.encode("utf-8")) > _DESCRIPTION_MAX_BYTES:
raise ValueError(
@@ -641,10 +646,12 @@ def _evaluate_conditions(template: dict, params: dict) -> dict:
# Rules section
# ===========================================================================
-# The functions the Rules section accepts (rules-section-structure.html lists
-# them; Ref may be nested in all but Fn::ValueOf and Fn::ValueOfAll).
+# The functions the Rules section accepts. rules-section-structure.html lists
+# Fn::If, but a real account refuses it: "Following functions are not supported
+# in the Rules block of the template: [Fn::If]" (measured eu-north-1 2026-09-19). Ref may be nested in
+# all but Fn::ValueOf and Fn::ValueOfAll.
_RULE_FUNCTIONS = frozenset({
- "Fn::And", "Fn::Or", "Fn::Not", "Fn::Equals", "Fn::If", "Fn::Contains",
+ "Fn::And", "Fn::Or", "Fn::Not", "Fn::Equals", "Fn::Contains",
"Fn::EachMemberEquals", "Fn::EachMemberIn", "Fn::RefAll", "Fn::ValueOf",
"Fn::ValueOfAll", "Ref",
})
@@ -667,12 +674,12 @@ class _RuleUnsupported(Exception):
# The argument list each rule function takes (intrinsic-function-reference-rules):
-# ``Fn::Not`` one condition, ``Fn::If`` a condition and two values, the rest
-# two elements; ``Fn::And`` / ``Fn::Or`` any list, ``Ref`` / ``Fn::RefAll`` a name.
+# ``Fn::Not`` one condition, the rest two elements; ``Fn::And`` / ``Fn::Or`` any
+# list, ``Ref`` / ``Fn::RefAll`` a name.
_RULE_ARITY = {
"Fn::Equals": 2, "Fn::Contains": 2, "Fn::EachMemberEquals": 2,
"Fn::EachMemberIn": 2, "Fn::ValueOf": 2, "Fn::ValueOfAll": 2,
- "Fn::Not": 1, "Fn::If": 3,
+ "Fn::Not": 1,
}
@@ -874,15 +881,6 @@ def _evaluate_rules(template: dict, params: dict, conditions: dict) -> None:
return any(as_bool(ev(a), fn) for a in args)
if fn == "Fn::Not":
return not as_bool(ev(args[0]), fn)
- if fn == "Fn::If":
- chosen = ev(args[0])
- if isinstance(args[0], str):
- if args[0] not in conditions:
- raise ValueError(
- f"Template error: Fn::If refers to condition {args[0]} "
- "which is not defined in the Conditions block")
- chosen = conditions[args[0]]
- return ev(args[1]) if as_bool(chosen, fn) else ev(args[2])
if fn == "Fn::Contains":
return str(ev(args[1])) in as_list(ev(args[0]), fn)
if fn == "Fn::EachMemberEquals":
@@ -1187,6 +1185,12 @@ def _resolve_refs(value, resources, params, conditions, mappings,
if "Fn::If" in value:
args = value["Fn::If"]
cond_name = args[0]
+ if not isinstance(cond_name, str):
+ # AWS wants a condition NAME here, not an inline condition
+ # (measured eu-north-1 2026-09-19); without this the dict reaches conditions.get().
+ raise ValueError(
+ "Template error: Fn::If requires a list argument with the "
+ "first element being a condition")
cond_val = conditions.get(cond_name, False)
branch = args[1] if cond_val else args[2]
result = _resolve_refs(branch, resources, params, conditions,
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 6d8d200f..36bc7c40 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -664,6 +664,13 @@ _CUSTOM_NAME_REPLACEMENT = {
"name": "InstanceProfileName",
"requires_replacement": lambda old, new: old.get("Path", "/") != new.get("Path", "/"),
},
+ "AWS::IoT::ProvisioningTemplate": {
+ "name": "TemplateName",
+ "requires_replacement": lambda old, new: (
+ old.get("TemplateType", "FLEET_PROVISIONING")
+ != new.get("TemplateType", "FLEET_PROVISIONING")
+ ),
+ },
# "If you specify a name, you cannot perform updates that require
# replacement of this resource, but you can perform other updates"
# (aws-resource-elasticloadbalancingv2-loadbalancer), which is this rule
@@ -1568,7 +1575,7 @@ def _sns_sub_create(logical_id, props, stack_name):
topic = _sns._topics.get(topic_arn)
if not topic:
sub_arn = f"{topic_arn}:{new_uuid()}"
- return sub_arn, {"SubscriptionArn": sub_arn}
+ return sub_arn, {"Arn": sub_arn}
sub_arn = f"{topic_arn}:{new_uuid()}"
attributes = {
@@ -1588,7 +1595,7 @@ def _sns_sub_create(logical_id, props, stack_name):
}
topic["subscriptions"].append(sub)
_sns._sub_arn_to_topic[sub_arn] = topic_arn
- return sub_arn, {"SubscriptionArn": sub_arn}
+ return sub_arn, {"Arn": sub_arn}
def _sns_sub_update(physical_id, old_props, new_props, stack_name, logical_id=None):
@@ -1623,7 +1630,7 @@ def _sns_sub_update(physical_id, old_props, new_props, stack_name, logical_id=No
})
if resp[0] >= 400:
raise ValueError(f"AWS::SNS::Subscription update failed: {resp[2]!r}")
- return physical_id, {"SubscriptionArn": physical_id}
+ return physical_id, {"Arn": physical_id}
def _sns_sub_delete(physical_id, props):
@@ -1996,7 +2003,13 @@ def _lambda_update(physical_id, old_props, new_props, stack_name, logical_id=Non
code = new_props.get("Code", {})
image_uri = code.get("ImageUri")
is_image = new_props.get("PackageType") == "Image" or bool(image_uri)
- if is_image != (func["config"].get("PackageType") == "Image"):
+ # DurableConfig and TenancyConfig are "Update requires: Replacement" in the
+ # resource reference, like a PackageType flip: same local equivalent.
+ replacing = is_image != (func["config"].get("PackageType") == "Image") or any(
+ old_props.get(p) != new_props.get(p)
+ for p in ("DurableConfig", "TenancyConfig")
+ )
+ if replacing:
# The re-provision replaces the whole function record under the same
# name — a stale warm worker or pooled container would keep serving
# the old package. Invalidate both, the way _update_code does.
@@ -3299,7 +3312,9 @@ def _eks_nodegroup_create(logical_id, props, stack_name):
key = f"{cluster_name}/{ng_name}"
ng = _eks._nodegroups.get(key, {})
arn = ng.get("nodegroupArn", "")
- return ng_name, {"Arn": arn}
+ return ng_name, {"ClusterName": ng.get("clusterName", cluster_name),
+ "NodegroupName": ng.get("nodegroupName", ng_name),
+ "Arn": arn}
def _eks_nodegroup_delete(physical_id, props):
@@ -3597,15 +3612,16 @@ def _cfn_wait_condition_create(logical_id, props, stack_name):
data = _wc.wait_for(token, stack_id, stack_name, logical_id,
"AWS::CloudFormation::WaitCondition", count, timeout_s)
pid = f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
- attrs = {"Data": json.dumps(data), "Id": pid}
- _wc.remember_result(pid, attrs)
- return pid, attrs
+ return pid, {"Data": json.dumps(data), "Id": pid}
def _cfn_wait_condition_update(physical_id, old_props, new_props, stack_name):
- """Updates are not supported on AWS; the resource keeps its id and data."""
- from ministack.services.cloudformation import wait_conditions as _wc
- return physical_id, _wc.recall_result(physical_id) or {"Data": "{}", "Id": physical_id}
+ """AWS refuses the update outright: UPDATE_FAILED with "Update to resource
+ type AWS::CloudFormation::WaitCondition is not supported", then a rollback
+ (captured eu-north-1 2026-09-19). Succeeding silently hid that."""
+ raise ValueError(
+ "Update to resource type AWS::CloudFormation::WaitCondition is not supported."
+ )
def _cfn_wait_condition_handle_create(logical_id, props, stack_name):
@@ -4068,6 +4084,7 @@ def _apigw_rest_api_create(logical_id, props, stack_name):
root_id = rid
break
return api_id, {
+ "RestApiId": api_id,
"RootResourceId": root_id,
"Arn": f"arn:aws:apigateway:{get_region()}::/restapis/{api_id}",
}
@@ -4121,6 +4138,7 @@ def _apigw_rest_api_update(physical_id, old_props, new_props, stack_name, logica
root_id = rid
break
return physical_id, {
+ "RestApiId": physical_id,
"RootResourceId": root_id,
"Arn": f"arn:aws:apigateway:{get_region()}::/restapis/{physical_id}",
}
@@ -4997,6 +5015,20 @@ def _apigw_documentation_version_delete(physical_id, props):
# --- Lambda EventSourceMapping ---
+def _lambda_esm_attrs(esm_id: str) -> dict:
+ """``Id`` and ``EventSourceMappingArn`` are the type's documented attributes;
+ ``UUID`` is kept for templates written against earlier releases. The ARN
+ shape is botocore's ``EventSourceMappingArn`` pattern."""
+ return {
+ "Id": esm_id,
+ "EventSourceMappingArn": (
+ f"arn:aws:lambda:{get_region()}:{get_account_id()}:"
+ f"event-source-mapping:{esm_id}"
+ ),
+ "UUID": esm_id,
+ }
+
+
def _lambda_esm_create(logical_id, props, stack_name):
func, func_name, resource_arn, qualifier = _lambda_function_for_cfn_ref(props.get("FunctionName", ""))
esm_id = new_uuid()
@@ -5042,7 +5074,7 @@ def _lambda_esm_create(logical_id, props, stack_name):
# API CreateEventSourceMapping path; no-op for SQS/Kinesis sources (#936).
_lambda_svc._init_stream_position(esm_id, esm["EventSourceArn"], esm["StartingPosition"])
_lambda_svc._ensure_poller()
- return esm_id, {"UUID": esm_id}
+ return esm_id, _lambda_esm_attrs(esm_id)
def _lambda_esm_delete(physical_id, props):
@@ -5087,7 +5119,7 @@ def _lambda_esm_update(physical_id, old_props, new_props, stack_name):
esm["FunctionName"] = func_name
esm["FunctionArn"] = func_arn + (f":{qualifier}" if qualifier else "")
esm["LastModified"] = int(time.time())
- return physical_id, {"UUID": physical_id}
+ return physical_id, _lambda_esm_attrs(physical_id)
# --- Lambda EventInvokeConfig ---
@@ -5328,7 +5360,7 @@ def _policy_attachment_update(physical_id, old_props, new_props, members, store)
record = store.get(member)
if record:
record["attributes"]["Policy"] = policy_doc
- return physical_id, {}
+ return physical_id, {"Id": physical_id}
def _policy_attachment_create(logical_id, props, stack_name, members, store):
@@ -5340,7 +5372,8 @@ def _policy_attachment_create(logical_id, props, stack_name, members, store):
record = store.get(member)
if record:
record["attributes"]["Policy"] = policy_doc
- return f"{stack_name}-{logical_id}-{new_uuid()[:8]}", {}
+ pid = f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ return pid, {"Id": pid}
def _policy_attachment_delete(props, members, store):
@@ -5532,7 +5565,8 @@ def _appsync_apikey_create(logical_id, props, stack_name):
"expires": props.get("Expires", int(time.time()) + 604800),
}
_appsync._api_keys.setdefault(api_id, {})[key_id] = key
- return key_id, {"ApiKey": key_id, "Arn": f"arn:aws:appsync:{get_region()}:{get_account_id()}:apis/{api_id}/apikeys/{key_id}"}
+ return key_id, {"ApiKeyId": key_id, "ApiKey": key_id,
+ "Arn": f"arn:aws:appsync:{get_region()}:{get_account_id()}:apis/{api_id}/apikeys/{key_id}"}
def _appsync_apikey_delete(physical_id, props):
@@ -5594,7 +5628,7 @@ def _sm_secret_create(logical_id, props, stack_name):
}
if props.get("ReplicaRegions"):
_sm_secret_replicate(name, props["ReplicaRegions"])
- return name, {"Arn": arn}
+ return name, {"Id": arn, "Arn": arn}
def _sm_secret_replicate(secret_id, regions):
@@ -5648,7 +5682,7 @@ def _sm_secret_update(physical_id, old_props, new_props, stack_name, logical_id=
# a region dropped from the template keeps its replica, the service
# has no RemoveRegionsFromReplication to take it down with.
_sm_secret_replicate(physical_id, new_props["ReplicaRegions"])
- return physical_id, {"Arn": secret["ARN"]}
+ return physical_id, {"Id": secret["ARN"], "Arn": secret["ARN"]}
def _sm_secret_delete(physical_id, props):
@@ -8805,15 +8839,30 @@ def _ses_configuration_set_event_destination_delete(physical_id, props):
# WAFv2 WebACL
# ---------------------------------------------------------------------------
+def _waf_web_acl_parts(physical_id, props):
+ """The ``name, id, scope`` a web ACL's physical id carries. A physical id
+ written before the Ref carried all three is the bare id, so its scope has
+ to come from the template."""
+ parts = str(physical_id).split("|")
+ if len(parts) == 3:
+ return parts[0], parts[1], parts[2]
+ return "", str(physical_id), props.get("Scope", "REGIONAL")
+
+
def _waf_web_acl_create(logical_id, props, stack_name):
name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=128)
- scope = props.get("Scope", "REGIONAL")
- uid, arn, _record = _waf.create_web_acl_record(name, scope, props)
- return uid, {"Arn": arn, "Id": uid}
+ uid, arn, record = _waf.create_web_acl_record(
+ name, props.get("Scope", "REGIONAL"), props)
+ # Ref is "name|id|scope", not the bare id: "The Ref for the resource,
+ # containing the resource name, physical ID, and scope, formatted as
+ # follows: name|id|scope" (aws-resource-wafv2-webacl). The scope comes
+ # from the record, which normalised it.
+ return f"{name}|{uid}|{record['Scope']}", {"Arn": arn, "Id": uid}
def _waf_web_acl_delete(physical_id, props):
- _waf.delete_web_acl_record(physical_id, props.get("Scope", "REGIONAL"))
+ _name, uid, scope = _waf_web_acl_parts(physical_id, props)
+ _waf.delete_web_acl_record(uid, scope)
def _waf_web_acl_update(physical_id, old_props, new_props, stack_name,
@@ -8837,7 +8886,9 @@ def _waf_web_acl_update(physical_id, old_props, new_props, stack_name,
# asks for: the store is keyed by the scope's home region, so the new
# scope addresses a different store. _waf_web_acl_delete reads old_props
# for the same reason.
- acl = _waf.web_acl_record(physical_id, old_props.get("Scope", "REGIONAL"))
+ # The physical id is "name|id|scope"; the store is keyed by the id alone.
+ _old_name, acl_id, acl_scope = _waf_web_acl_parts(physical_id, old_props)
+ acl = _waf.web_acl_record(acl_id, acl_scope)
replaced = _rename_replacement(
physical_id, old_props, new_props, stack_name, logical_id,
name, acl.get("Name") if acl else None,
@@ -8855,7 +8906,7 @@ def _waf_web_acl_update(physical_id, old_props, new_props, stack_name,
return created
_waf.update_web_acl_record(acl, new_props)
- return physical_id, {"Arn": acl["ARN"], "Id": physical_id}
+ return physical_id, {"Arn": acl["ARN"], "Id": acl_id}
# ---------------------------------------------------------------------------
@@ -9240,7 +9291,7 @@ def _asg_create(logical_id, props, stack_name):
asg["Tags"] = tags
_asg._asgs[name] = asg
_asg._tags[name] = tags
- return name, {"Arn": arn}
+ return name, {"AutoScalingGroupARN": arn, "Arn": arn}
def _asg_delete(physical_id, props):
@@ -9707,13 +9758,18 @@ def _iot_thing_group_update(physical_id, old_props, new_props, stack_name, logic
the new group is created before the old one is removed, as CloudFormation
orders a replacement, and Ref follows the new id. QueryString and Tags are
accepted without effect — the service has no dynamic groups and no tag
- store for thing groups."""
+ store for thing groups. An auto-named group takes its deterministic name
+ back on a replacement, so the predecessor comes off first or
+ CreateThingGroup answers ResourceAlreadyExistsException; same shape as the
+ DynamoDB key-schema and Location tracker branches."""
rec = _iot_thing_group_record(physical_id)
replacement = rec is None or any(
new_props.get(key) != old_props.get(key)
for key in ("ThingGroupName", "ParentGroupName")
)
if replacement:
+ if rec is not None and not new_props.get("ThingGroupName"):
+ _iot_thing_group_delete(physical_id, old_props)
return _iot_thing_group_create(logical_id or physical_id, new_props, stack_name)
name = rec["thingGroupName"]
resp = _iot._update_thing_group(
@@ -9859,12 +9915,20 @@ def _iot_provisioning_template_update(physical_id, old_props, new_props, stack_n
an UpdateProvisioningTemplate member (AWS stores it as a new version via
CreateProvisioningTemplateVersion, which MiniStack does not model), so a
changed body is written onto the stored record directly — the template
- always stays at defaultVersionId 1. TemplateType is create-only on AWS
- (a change replaces the template); a changed value is ignored here.
+ always stays at defaultVersionId 1. TemplateType requires replacement: under
+ an explicit name _custom_named_replacement_error refuses it as CloudFormation
+ does, and under a generated name the deterministic value is reused, so the
+ predecessor comes off first.
"""
name = new_props.get("TemplateName") or _physical_name(
stack_name, logical_id or physical_id, max_len=36
)
+ if (old_props.get("TemplateType", "FLEET_PROVISIONING")
+ != new_props.get("TemplateType", "FLEET_PROVISIONING")):
+ _iot_provisioning_template_delete(physical_id, old_props)
+ return _iot_provisioning_template_create(
+ logical_id or physical_id, new_props, stack_name
+ )
if name != physical_id:
created = _iot_provisioning_template_create(
logical_id or physical_id, new_props, stack_name
@@ -9981,6 +10045,16 @@ def _iot_ca_certificate_update(physical_id, old_props, new_props, stack_name):
"the certificate id is derived from the PEM. Declare a new "
"CACertificate resource for the new PEM and remove this one."
)
+ if new_props.get("VerificationCertificatePem") != old_props.get(
+ "VerificationCertificatePem"
+ ):
+ # Update-requires-replacement in the resource reference, and
+ # UpdateCACertificate carries no verification-certificate member, so
+ # the same refusal as CertificateMode below applies.
+ raise ValueError(
+ "AWS::IoT::CACertificate cannot update VerificationCertificatePem "
+ "in place: declare a new CACertificate resource for it."
+ )
if not new_props.get("Status"):
raise ValueError("AWS::IoT::CACertificate requires Status")
stored_mode = (_iot._ca_certificates.get(physical_id) or {}).get(
@@ -10475,7 +10549,7 @@ _RESOURCE_HANDLERS = {
"delete_with_logical_id": True,
},
"AWS::Lambda::Version": {"create": _lambda_version_create, "delete": _lambda_version_delete},
- "AWS::CloudFormation::WaitCondition": {"create": _cfn_wait_condition_create, "update": _cfn_wait_condition_update, "delete": _cfn_noop_delete},
+ "AWS::CloudFormation::WaitCondition": {"create": _cfn_wait_condition_create, "update": _cfn_wait_condition_update},
"AWS::CloudFormation::WaitConditionHandle": {"create": _cfn_wait_condition_handle_create, "delete": _cfn_wait_condition_handle_delete},
"AWS::CloudFormation::Stack": {
"create": _cfn_nested_stack_create,
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index 00a0c86a..1f920106 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -79,15 +79,36 @@ def _is_custom_resource(resource_type: str) -> bool:
# ===========================================================================
+def _default_resource_policy(res_def, attribute) -> str:
+ """``Delete``, except where AWS documents ``Snapshot`` as the default."""
+ if attribute != "DeletionPolicy":
+ return "Delete"
+ rtype = (res_def or {}).get("Type")
+ props = (res_def or {}).get("Properties") or {}
+ if rtype == "AWS::RDS::DBCluster":
+ return "Retain"
+ if rtype == "AWS::RDS::DBInstance" and not props.get("DBClusterIdentifier"):
+ return "Retain"
+ return "Delete"
+
+
def _resource_policy(res_def, attribute, resources, params, conditions, mappings,
stack_name, stack_id):
"""A resource's ``DeletionPolicy`` / ``UpdateReplacePolicy`` as a string,
- ``Delete`` when the template sets none. An intrinsic (``Fn::If``) is
- resolved like a property; one that does not resolve counts as ``Delete``
- and is logged, since that is the destructive reading."""
+ ``Delete`` when the template sets none, with one documented exception: AWS
+ defaults ``DeletionPolicy`` to ``Snapshot`` for ``AWS::RDS::DBCluster`` and
+ for ``AWS::RDS::DBInstance`` without ``DBClusterIdentifier``
+ (aws-attribute-deletionpolicy.html; captured eu-north-1 2026-09-19, the
+ stack delete left a manual snapshot behind). This emulator takes no
+ snapshots, so those two default to ``Retain``: the data survives the stack
+ delete, which is what Snapshot is for, where ``Delete`` would destroy it.
+
+ An intrinsic (``Fn::If``) is resolved like a property; one that does not
+ resolve counts as ``Delete`` and is logged, since that is the destructive
+ reading."""
value = (res_def or {}).get(attribute)
if value is None:
- return "Delete"
+ return _default_resource_policy(res_def, attribute)
if isinstance(value, dict):
try:
value = _resolve_refs(copy.deepcopy(value), resources, params, conditions,
diff --git a/ministack/services/cloudformation/wait_conditions.py b/ministack/services/cloudformation/wait_conditions.py
index 8ac84ad1..c84fea69 100644
--- a/ministack/services/cloudformation/wait_conditions.py
+++ b/ministack/services/cloudformation/wait_conditions.py
@@ -35,9 +35,6 @@ _generation = 0
_handles: dict = {}
# (stack id, logical id) → {"token", "stack_name", "resource_type"}, while that wait condition waits
_waiting: dict = {}
-# physical id of a completed wait condition → its attributes (updates are not
-# supported on AWS, so an update returns what the create produced)
-_results: dict = {}
# --- validation of the template values -------------------------------------
@@ -253,21 +250,10 @@ def wait_for(
_handles.pop(token, None)
-def remember_result(physical_id: str, attrs: dict) -> None:
- with _lock:
- _results[physical_id] = dict(attrs)
-
-
-def recall_result(physical_id: str) -> dict:
- with _lock:
- return dict(_results.get(physical_id, {}))
-
-
def reset():
global _generation
with _changed:
_generation += 1
_handles.clear()
_waiting.clear()
- _results.clear()
_changed.notify_all()
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 00ab2672..6a60fd8a 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -239,7 +239,8 @@ def well_known_jwks(pool_id: str):
return 200, {"Content-Type": "application/json"}, json.dumps({"keys": [_JWKS_KEY]}).encode()
-def well_known_openid_configuration(pool_id: str, region: str | None = None, host: str | None = None):
+def well_known_openid_configuration(pool_id: str, region: str | None = None,
+ host: str | None = None, scheme: str = "http"):
"""Return OpenID Connect discovery document.
`issuer` matches the JWT `iss` claim (real AWS URL) so OIDC clients that
@@ -255,7 +256,9 @@ def well_known_openid_configuration(pool_id: str, region: str | None = None, hos
# fallback for malformed pool_ids.
r = _pool_region(pool_id) if pool_id else (region or get_region())
issuer = f"https://cognito-idp.{r}.amazonaws.com/{pool_id}"
- base = f"http://{host}" if host else f"http://{_MINISTACK_HOST}:{_MINISTACK_PORT}"
+ # Behind a TLS terminator every URL in the document has to be https, or it
+ # disagrees with the https issuer and discovery fails.
+ base = f"{scheme}://{host}" if host else f"{scheme}://{_MINISTACK_HOST}:{_MINISTACK_PORT}"
pool_base = f"{base}/{pool_id}"
doc = {
"issuer": issuer,
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index 87c11771..70faaf36 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -75,7 +75,7 @@ _CSV_DELIMITER_RE = re.compile(r"[,;:|\t ]")
# COMPLETED happens asynchronously. We simulate that by holding IN_PROGRESS
# on the first DescribeExport/DescribeImport calls within this grace window.
_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"))
+_IMPORT_COMPLETE_AFTER_SEC = 1.0
# "The log group name is /aws-dynamodb/imports. The error log stream name is
# import-id/error."
_IMPORT_LOG_GROUP = "/aws-dynamodb/imports"
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index b03df02b..4a932483 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -2393,7 +2393,16 @@ def _parse_ec2_docker_flags(flags: str) -> dict:
if args.privileged:
kwargs["privileged"] = True
if args.env:
- kwargs["environment"] = dict(e.partition("=")[::2] for e in args.env)
+ # Bare `-e FOO` takes the host value, or is left out if unset: docker's rule.
+ environment = {}
+ for entry in args.env:
+ name, sep, value = entry.partition("=")
+ if sep:
+ environment[name] = value
+ elif name in os.environ:
+ environment[name] = os.environ[name]
+ if environment:
+ kwargs["environment"] = environment
if args.volume:
kwargs["volumes"] = args.volume
if args.cap_add:
diff --git a/ministack/services/glue.py b/ministack/services/glue.py
index 5472f8a9..5a4579ec 100644
--- a/ministack/services/glue.py
+++ b/ministack/services/glue.py
@@ -47,7 +47,7 @@ _DOCKER_TIMEOUT = float(os.environ.get("MINISTACK_DOCKER_TIMEOUT", "10"))
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
-CRAWLER_RUN_SECONDS = int(os.environ.get("GLUE_CRAWLER_RUN_SECONDS", "5"))
+CRAWLER_RUN_SECONDS = 5
S3_DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/ministack-data/s3")
DOCKER_NETWORK = os.environ.get("DOCKER_NETWORK", "")
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 3e27c72c..66cd55ab 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -637,6 +637,16 @@ def _describe_endpoint(qp: dict) -> tuple:
host = f"{prefix}-ats.iot.{region}.{_MINISTACK_HOST}:{_GATEWAY_PORT}"
elif endpoint_type == "iot:CredentialProvider":
host = f"{prefix}.credentials.iot.{region}.{_MINISTACK_HOST}:{_GATEWAY_PORT}"
+ elif endpoint_type == "iot:Jobs":
+ # Retired: AWS now serves Jobs and Commands from the Data-ATS endpoint
+ # (captured eu-north-1 2026-09-19). Signing with the `iot-jobs-data`
+ # scope against the Data-ATS host routes there already.
+ return error_response_json(
+ "InvalidRequestException",
+ "IoT Jobs and Commands APIs are now available through iot:Data-ATS "
+ "endpoints instead of iot:Jobs endpoints. Please use iot:Data-ATS.",
+ 400,
+ )
else:
return error_response_json(
"InvalidRequestException",
@@ -2989,9 +2999,8 @@ def _eval_select_function(
return _MISSING
return value.replace(old, new)
if name == "clientid" and not args:
- # HTTP publishes carry no MQTT client id — AWS resolves clientid() to
- # Undefined there, so the field is omitted from the projection.
- return client_id if client_id else _MISSING
+ # Documented as the client id "or n/a if the message wasn't sent over MQTT".
+ return client_id if client_id else "n/a"
# principal() and traceid() land here too: this publish path carries no
# certificate identity or trace id to report, so they warn like any other
# function the evaluator does not implement.
@@ -3058,7 +3067,9 @@ def _eval_select_expr(expr: str, topic: str, payload: bytes, message, client_id:
# NOT can tell that apart from false. `_eval_where` then fires the rule on true
# alone, so an Undefined predicate fails closed however it was reached.
-_WHERE_OPERATORS = ("<>", "!=", "==", "<=", ">=", "=", "<", ">")
+# AWS refuses `!=` ("Unexpected character '!'") and `==` ("Unexpected token,
+# 'EQ'") — captured eu-north-1 2026-09-19. Longest first so <= beats <.
+_WHERE_OPERATORS = ("<>", "<=", ">=", "=", "<", ">")
_REGEXP_MATCHES_RE = re.compile(
r"regexp_matches\s*\(\s*(?P<expr>.+?)\s*,\s*'(?P<regex>[^']*)'\s*\)",
re.IGNORECASE | re.DOTALL,
@@ -3494,10 +3505,10 @@ def _eval_where_node(node: tuple, topic: str, payload: bytes, message, client_id
right = _eval_select_expr(right_expr, topic, payload, message, client_id)
if left is _MISSING or right is _MISSING:
return _MISSING
- if op in ("=", "=="):
+ if op == "=":
# Equality does not convert: on AWS a mismatched pair is simply unequal.
return _where_values_equal(left, right)
- if op in ("<>", "!="):
+ if op == "<>":
return not _where_values_equal(left, right)
lnum, rnum = _sql_as_number(left), _sql_as_number(right)
if lnum is None or rnum is None:
@@ -3552,8 +3563,15 @@ def _validate_rule_sql(sql: str) -> str | None:
):
return "FROM clause must name a topic filter in single quotes"
pred = _rule_where_clause(sql)
- if pred and _parse_where(pred) is None:
- return f"Unsupported WHERE clause: {pred}"
+ if pred:
+ # A nested SELECT (the documented EXISTS-subquery form) is refused by
+ # AWS itself: "Unexpected token, 'SELECT'" (captured eu-north-1
+ # 2026-09-19). Literals are blanked first so 'select' inside a string
+ # is not mistaken for the keyword.
+ if re.search(r"\bSELECT\b", _SQL_LITERAL_RE.sub("''", pred), re.IGNORECASE):
+ return f"Unexpected token, 'SELECT' in WHERE clause: {pred}"
+ if _parse_where(pred) is None:
+ return f"Unsupported WHERE clause: {pred}"
return None
@@ -3745,6 +3763,11 @@ def _list_topic_rules(qp: dict) -> tuple:
# device that has to fetch that job by id could then never reach it.
_JOB_ID_RE = re.compile(r"^[a-zA-Z0-9_-]{1,64}$")
+# schedulingConfig start/end times are minute-precision and carry no timezone
+# suffix: "must follow the format YYYY-MM-DDThh:mm" (measured eu-north-1
+# 2026-09-19).
+_JOB_SCHEDULE_TIME_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$")
+
_JOB_TARGET_SELECTIONS = {"SNAPSHOT", "CONTINUOUS"}
_JOB_EXECUTION_TERMINAL = {
@@ -3777,9 +3800,9 @@ def _jobs_now_ms() -> int:
return int(time.time() * 1000)
-def _jobs_ms_to_s(millis: int | None) -> float | None:
- """Millisecond record stamp → epoch-seconds float for `timestamp` shapes."""
- return None if millis is None else millis / 1000.0
+def _jobs_ms_to_s(millis: int | None) -> int | None:
+ """Millisecond record stamp → whole epoch seconds for `timestamp` shapes."""
+ return None if millis is None else millis // 1000
def _jobs_ms_to_long_s(millis: int | None) -> int | None:
@@ -3872,6 +3895,65 @@ def _jobs_materialize_all() -> None:
_jobs_materialize_executions(job_id)
+def _jobs_timeout_minutes(execution: dict, job: dict | None) -> int | None:
+ """The in-progress timeout for one execution, in minutes, or None.
+
+ ``stepTimeoutInMinutes`` from the device's own UpdateJobExecution wins over
+ the job's ``timeoutConfig.inProgressTimeoutInMinutes``, which the reference
+ describes as applying to every execution of the job.
+ """
+ step = execution.get("stepTimeoutInMinutes")
+ if step is not None:
+ return step
+ cfg = (job or {}).get("timeoutConfig") or {}
+ minutes = cfg.get("inProgressTimeoutInMinutes")
+ return minutes if isinstance(minutes, int) else None
+
+
+def _jobs_seconds_before_timeout(execution: dict) -> int | None:
+ """Seconds an IN_PROGRESS execution has left before TIMED_OUT, or None when
+ no timeout applies. The device plane models this as a ``long``."""
+ if execution.get("status") != "IN_PROGRESS":
+ return None
+ minutes = _jobs_timeout_minutes(execution, _jobs.get(execution["jobId"]))
+ if not minutes:
+ return None
+ started = (execution.get("timeoutStartedAt")
+ or execution.get("startedAt")
+ or execution.get("lastUpdatedAt"))
+ if started is None:
+ return None
+ left = minutes * 60 - (_jobs_now_ms() - started) // 1000
+ return max(0, int(left))
+
+
+def _jobs_apply_timeout(execution: dict) -> dict:
+ """Flip an execution that has outstayed its timeout to TIMED_OUT.
+
+ Evaluated on read rather than by a timer, the way the broker's session
+ expiry is: "whenever a job execution remains in the IN_PROGRESS status for
+ longer than this interval, the job execution will fail and switch to the
+ terminal TIMED_OUT status".
+ """
+ if execution.get("status") != "IN_PROGRESS":
+ return execution
+ minutes = _jobs_timeout_minutes(execution, _jobs.get(execution["jobId"]))
+ if not minutes:
+ return execution
+ started = (execution.get("timeoutStartedAt")
+ or execution.get("startedAt")
+ or execution.get("lastUpdatedAt"))
+ if started is None:
+ return execution
+ if _jobs_now_ms() - started <= minutes * 60_000:
+ return execution
+ execution["status"] = "TIMED_OUT"
+ execution["lastUpdatedAt"] = _jobs_now_ms()
+ execution["versionNumber"] += 1
+ _jobs_maybe_complete(execution["jobId"])
+ return execution
+
+
def _jobs_maybe_complete(job_id: str) -> None:
"""A non-CONTINUOUS job whose executions are all terminal is COMPLETED.
@@ -3991,6 +4073,33 @@ async def _create_job(job_id: str, payload: dict) -> tuple:
+ ", ".join(sorted(_JOB_TARGET_SELECTIONS)),
400,
)
+ sched_cfg = payload.get("schedulingConfig") or {}
+ for field in ("startTime", "endTime"):
+ value = sched_cfg.get(field)
+ if value is None:
+ continue
+ if not isinstance(value, str) or not _JOB_SCHEDULE_TIME_RE.match(value):
+ # Exact wording measured eu-north-1 2026-09-19; note the minute
+ # precision — an ISO stamp with seconds or a Z is refused.
+ return error_response_json(
+ "InvalidRequestException",
+ f"1 validation error detected: Provided time {value} UTC must "
+ "follow the format YYYY-MM-DDThh:mm.",
+ 400,
+ )
+ timeout_cfg = payload.get("timeoutConfig") or {}
+ if timeout_cfg:
+ minutes = timeout_cfg.get("inProgressTimeoutInMinutes")
+ try:
+ minutes = int(minutes)
+ except (TypeError, ValueError):
+ minutes = None
+ if minutes is None or not 1 <= minutes <= 10080:
+ return error_response_json(
+ "InvalidRequestException",
+ "inProgressTimeoutInMinutes must be between 1 and 10080",
+ 400,
+ )
targets = payload.get("targets")
if not targets:
return error_response_json(
@@ -4014,6 +4123,23 @@ async def _create_job(job_id: str, payload: dict) -> tuple:
)
target_things.update(resolved)
document = payload.get("document")
+ if isinstance(document, str) and len(document) > 32768:
+ return error_response_json(
+ "InvalidRequestException",
+ "document exceeds the maximum length of 32768", 400,
+ )
+ source = payload.get("documentSource")
+ if isinstance(source, str) and not 1 <= len(source) <= 1350:
+ return error_response_json(
+ "InvalidRequestException",
+ "documentSource must be between 1 and 1350 characters", 400,
+ )
+ if not document and not payload.get("documentSource"):
+ return error_response_json(
+ "InvalidRequestException",
+ "document is required if you do not specify a value for documentSource",
+ 400,
+ )
if not document and payload.get("documentSource"):
# DELIBERATE DIVERGENCE: AWS fetches the document from the S3 URL and
# serves its CONTENT to devices. MiniStack does not fetch it — it
@@ -4042,6 +4168,18 @@ async def _create_job(job_id: str, payload: dict) -> tuple:
"presignedUrlConfig": payload.get("presignedUrlConfig") or {},
"jobExecutionsRolloutConfig": payload.get("jobExecutionsRolloutConfig")
or {},
+ # Modelled CreateJob members stored so DescribeJob echoes them. Storing
+ # is all this does: nothing acts on timeoutConfig or abortConfig, so no
+ # execution reaches TIMED_OUT and nothing aborts.
+ "abortConfig": payload.get("abortConfig"),
+ "timeoutConfig": payload.get("timeoutConfig"),
+ "jobExecutionsRetryConfig": payload.get("jobExecutionsRetryConfig"),
+ "namespaceId": payload.get("namespaceId"),
+ "jobTemplateArn": payload.get("jobTemplateArn"),
+ "documentParameters": payload.get("documentParameters"),
+ "schedulingConfig": payload.get("schedulingConfig"),
+ "destinationPackageVersions": payload.get("destinationPackageVersions"),
+ "tags": payload.get("tags"),
"snapshotted": False,
}
_jobs_materialize_executions(job_id)
@@ -4107,6 +4245,26 @@ def _describe_job(job_id: str) -> tuple:
job_doc["comment"] = job["comment"]
if job.get("reasonCode") is not None:
job_doc["reasonCode"] = job["reasonCode"]
+ if job.get("forceCanceled") is not None:
+ job_doc["forceCanceled"] = job["forceCanceled"]
+ # Members the Job shape models and CreateJob accepted. `tags` is NOT among
+ # them (tags are read through ListTagsForResource), so it is not echoed.
+ for member in (
+ "abortConfig", "jobExecutionsRetryConfig", "namespaceId", "jobTemplateArn",
+ "documentParameters", "destinationPackageVersions",
+ ):
+ if job.get(member) is not None:
+ job_doc[member] = job[member]
+ # timeoutConfig and schedulingConfig come back as {} even when unset, unlike
+ # abortConfig, which is omitted (captured eu-north-1 2026-09-19).
+ job_doc["timeoutConfig"] = job.get("timeoutConfig") or {}
+ job_doc["schedulingConfig"] = job.get("schedulingConfig") or {}
+ # isConcurrent is false in every steady state (captured eu-north-1
+ # 2026-09-19 with a QUEUED, an IN_PROGRESS and a SUCCEEDED execution). It is
+ # true only inside the rollout/cancel window the reference describes, which
+ # this emulator does not model. processingTargets is null throughout the same
+ # capture, so it stays omitted rather than echoing the target ARNs.
+ job_doc["isConcurrent"] = False
response = {"job": job_doc}
if job.get("documentSource") is not None:
response["documentSource"] = job["documentSource"]
@@ -4181,6 +4339,8 @@ async def _cancel_job(job_id: str, payload: dict, qp: dict) -> tuple:
force = _qp_bool(qp, "force")
now = _jobs_now_ms()
job["status"] = "CANCELED"
+ if force:
+ job["forceCanceled"] = True
job["lastUpdatedAt"] = now
job["completedAt"] = now
if payload.get("comment") is not None:
@@ -4268,6 +4428,7 @@ def _list_job_executions_for_thing(thing: str, qp: dict) -> tuple:
"queuedAt": _jobs_ms_to_s(execution["queuedAt"]),
"lastUpdatedAt": _jobs_ms_to_s(execution["lastUpdatedAt"]),
"executionNumber": execution["executionNumber"],
+ "retryAttempt": execution.get("retryAttempt", 0),
}
if execution.get("startedAt") is not None:
summary["startedAt"] = _jobs_ms_to_s(execution["startedAt"])
@@ -4363,6 +4524,9 @@ def jobs_pending_for_thing(thing_name: str) -> list[dict]:
creation gets its execution here, on the read that first needs it.
"""
_jobs_materialize_all()
+ for execution in _job_executions.values():
+ if execution["thingName"] == thing_name:
+ _jobs_apply_timeout(execution)
pending = [
dict(execution)
for execution in _job_executions.values()
@@ -4413,7 +4577,9 @@ def jobs_describe_execution(thing_name: str, job_id: str) -> dict | None:
"""One execution (a copy), materializing the job's targets first."""
_jobs_materialize_executions(job_id)
execution = _job_executions.get((thing_name, job_id))
- return None if execution is None else dict(execution)
+ if execution is None:
+ return None
+ return dict(_jobs_apply_timeout(execution))
def jobs_job_document(job_id: str) -> str:
@@ -4441,6 +4607,7 @@ def jobs_update_execution(
status,
expected_version=None,
status_details: dict | None = None,
+ step_timeout_minutes=None,
) -> tuple:
"""Apply a device-reported status to an execution.
@@ -4479,11 +4646,12 @@ def jobs_update_execution(
409,
)
if status not in _DEVICE_SETTABLE_STATUSES:
+ # InvalidStateTransitionException, not InvalidRequestException
+ # (measured eu-north-1 2026-09-19).
return None, error_response_json(
- "InvalidRequestException",
- f"A device cannot set status {status} via UpdateJobExecution; "
- "allowed statuses are IN_PROGRESS, SUCCEEDED, FAILED, and REJECTED",
- 400,
+ "InvalidStateTransitionException",
+ f"The status of job execution cannot be changed to be {status}",
+ 409,
)
now = _jobs_now_ms()
execution["status"] = status
@@ -4491,6 +4659,11 @@ def jobs_update_execution(
execution["statusDetails"] = dict(status_details)
if status == "IN_PROGRESS" and execution.get("startedAt") is None:
execution["startedAt"] = now
+ if status == "IN_PROGRESS" and step_timeout_minutes is not None:
+ # The device's own step timeout, reset every time it re-reports
+ # IN_PROGRESS with a new value.
+ execution["stepTimeoutInMinutes"] = step_timeout_minutes
+ execution["timeoutStartedAt"] = now
execution["lastUpdatedAt"] = now
execution["versionNumber"] += 1
_jobs_maybe_complete(job_id)
@@ -4516,6 +4689,9 @@ def jobs_execution_view(execution: dict, document: str | dict | None) -> dict:
}
if execution.get("startedAt") is not None:
view["startedAt"] = _jobs_ms_to_long_s(execution["startedAt"])
+ remaining = _jobs_seconds_before_timeout(execution)
+ if remaining is not None:
+ view["approximateSecondsBeforeTimedOut"] = remaining
if document is not None:
view["jobDocument"] = document
return view
@@ -5344,7 +5520,9 @@ async def _dispatch_rule_error_action(
"topic": topic,
# The emulator's publish path carries no CloudWatch trace id.
"cloudwatchTraceId": "",
- "clientId": client_id or "",
+ # "N/A", not "" — and not clientid()'s lowercase "n/a" (measured eu-north-1 2026-09-19).
+ "clientId": client_id or "N/A",
+ "sourceIp": _publish_source_ip.get(),
"base64OriginalPayload": base64.b64encode(payload).decode("ascii"),
"failures": failures,
}
@@ -5361,6 +5539,40 @@ async def _dispatch_rule_error_action(
)
+# failedResource is the resource the action targeted, a different member per type.
+_RULE_ACTION_RESOURCE_KEYS = {
+ "dynamoDBv2": ("putItem", "tableName"),
+ "sns": ("targetArn",),
+ "sqs": ("queueUrl",),
+ "republish": ("topic",),
+ "lambda": ("functionArn",),
+}
+
+
+def _rule_action_name(action_type: str) -> str:
+ """``failedAction`` for an action type: the key capitalised, plus ``Action``.
+ ``DynamoDBv2Action`` (measured eu-north-1 2026-09-19); ``S3Action`` is the reference's own example."""
+ if not action_type:
+ return ""
+ return action_type[0].upper() + action_type[1:] + "Action"
+
+
+def _rule_action_resource(action: dict, action_type: str) -> str:
+ """The resource an action names, for the errorAction document's
+ ``failedResource``. Empty when the action type does not name one."""
+ spec = action.get(action_type)
+ if not isinstance(spec, dict):
+ return ""
+ for key in _RULE_ACTION_RESOURCE_KEYS.get(action_type, ()):
+ value = spec.get(key)
+ if isinstance(value, dict):
+ spec = value
+ continue
+ if isinstance(value, str):
+ return value
+ return ""
+
+
async def _run_rule_actions(
account_id: str,
region: str,
@@ -5408,9 +5620,11 @@ async def _run_rule_actions(
type(exc).__name__,
exc,
)
- failures.append(
- {"action": action_type, "errorMessage": f"{type(exc).__name__}: {exc}"}
- )
+ failures.append({
+ "failedAction": _rule_action_name(action_type),
+ "failedResource": _rule_action_resource(action, action_type),
+ "errorMessage": f"{type(exc).__name__}: {exc}",
+ })
if failures:
await _dispatch_rule_error_action(
account_id, region, rule, topic, payload, client_id, failures
@@ -6320,6 +6534,14 @@ _delivery_properties: contextvars.ContextVar[bytes] = contextvars.ContextVar(
"_iot_delivery_properties", default=b""
)
+# The publisher's IP, for the errorAction document's `sourceIp`. Carried the
+# same way as the two below: the publish path is several frames deep and only
+# the error document needs it.
+_publish_source_ip: contextvars.ContextVar[str] = contextvars.ContextVar(
+ "_iot_publish_source_ip", default="127.0.0.1"
+)
+
+
# The RETAIN flag one delivery goes out with, carried the same way and for the
# same reason. It is resolved per subscriber rather than per message, because
# Retain As Published makes it a property of the subscription: two subscribers
@@ -7200,6 +7422,9 @@ async def handle_websocket(
scope: dict, receive, send, account_id: str, region: str
) -> None:
"""Drive an MQTT-over-WebSocket session."""
+ client = scope.get("client")
+ if client:
+ _publish_source_ip.set(client[0])
msg = await receive()
if msg.get("type") != "websocket.connect":
return
@@ -7548,6 +7773,11 @@ def _mtls_build_ssl_context() -> ssl.SSLContext:
return ctx
+def mtls_is_listening() -> bool:
+ """Whether the mTLS listener holds a bound socket."""
+ return _mtls_server is not None
+
+
async def mtls_start() -> None:
"""Idempotent: bind the mTLS MQTT listener, unless disabled."""
if not mtls_enabled():
diff --git a/ministack/services/iot_data.py b/ministack/services/iot_data.py
index 31c932ac..2a9b04cd 100644
--- a/ministack/services/iot_data.py
+++ b/ministack/services/iot_data.py
@@ -107,6 +107,11 @@ async def handle_request(
method: str, path: str, headers: dict, body: bytes, query_params: dict
) -> tuple:
qp = {k: (v[0] if isinstance(v, list) else v) for k, v in query_params.items()}
+ # The errorAction document reports the publisher's IP; same header the
+ # API Gateway integration reads.
+ _iot_module._publish_source_ip.set(
+ (headers.get("x-forwarded-for") or "127.0.0.1").split(",")[0].strip()
+ )
if method == "POST" and path.startswith("/topics/"):
return await _publish(path[len("/topics/"):], body, qp)
diff --git a/ministack/services/iot_jobs_data.py b/ministack/services/iot_jobs_data.py
index 91eeaf58..a8decb4e 100644
--- a/ministack/services/iot_jobs_data.py
+++ b/ministack/services/iot_jobs_data.py
@@ -199,6 +199,23 @@ def _describe_execution(thing: str, job_id: str, qp: dict) -> tuple:
async def _update_execution(thing: str, job_id: str, payload: dict) -> tuple:
+ # Nothing re-queues here, so only execution number 1 exists.
+ execution_number = payload.get("executionNumber")
+ if execution_number is not None:
+ try:
+ execution_number = int(execution_number)
+ except (TypeError, ValueError):
+ return error_response_json(
+ "InvalidRequestException",
+ f"Invalid executionNumber: {execution_number!r}", 400,
+ )
+ current = _iot_module.jobs_describe_execution(thing, job_id)
+ if current is not None and execution_number != current["executionNumber"]:
+ return error_response_json(
+ "ResourceNotFoundException",
+ f"No job execution {execution_number} found for thing {thing} "
+ f"and job {job_id}", 404,
+ )
prev_next = _iot_module.jobs_first_pending_job_id(thing)
execution, error = _iot_module.jobs_update_execution(
thing,
@@ -206,6 +223,7 @@ async def _update_execution(thing: str, job_id: str, payload: dict) -> tuple:
status=payload.get("status"),
expected_version=payload.get("expectedVersion"),
status_details=payload.get("statusDetails"),
+ step_timeout_minutes=payload.get("stepTimeoutInMinutes"),
)
if error:
return error
diff --git a/ministack/services/kms.py b/ministack/services/kms.py
index f22d34d4..03f30b74 100644
--- a/ministack/services/kms.py
+++ b/ministack/services/kms.py
@@ -35,7 +35,7 @@ logger = logging.getLogger("kms")
try:
from cryptography.exceptions import InvalidSignature
- from cryptography.hazmat.primitives import hashes, serialization
+ from cryptography.hazmat.primitives import hashes, keywrap, serialization
from cryptography.hazmat.primitives.asymmetric import ec, ed25519, padding, rsa, utils
HAS_CRYPTO = True
except ImportError:
@@ -109,7 +109,18 @@ def get_state():
for scoped_key, rec in _keys._data.items():
entry = {k: v for k, v in rec.items()
if k not in ("_private_key", "_public_key_der", "_symmetric_key",
- "_hmac_key")}
+ "_hmac_key", "_import_wrapping_key", "_import_token")}
+ if "_import_token" in rec:
+ entry["_import_token_b64"] = base64.b64encode(rec["_import_token"]).decode()
+ if "_import_wrapping_key" in rec and HAS_CRYPTO:
+ try:
+ entry["_import_wrapping_key_pem"] = base64.b64encode(
+ rec["_import_wrapping_key"].private_bytes(
+ serialization.Encoding.PEM,
+ serialization.PrivateFormat.PKCS8,
+ serialization.NoEncryption())).decode()
+ except Exception:
+ pass
if "_symmetric_key" in rec:
entry["_symmetric_key_b64"] = base64.b64encode(rec["_symmetric_key"]).decode()
if "_hmac_key" in rec:
@@ -150,6 +161,15 @@ def _restore_state(data):
def _restore_key_entry(entry):
if "_symmetric_key_b64" in entry:
entry["_symmetric_key"] = base64.b64decode(entry.pop("_symmetric_key_b64"))
+ if "_import_token_b64" in entry:
+ entry["_import_token"] = base64.b64decode(entry.pop("_import_token_b64"))
+ if "_import_wrapping_key_pem" in entry and HAS_CRYPTO:
+ try:
+ entry["_import_wrapping_key"] = serialization.load_pem_private_key(
+ base64.b64decode(entry.pop("_import_wrapping_key_pem")),
+ password=None)
+ except Exception:
+ entry.pop("_import_wrapping_key_pem", None)
if "_hmac_key_b64" in entry:
entry["_hmac_key"] = base64.b64decode(entry.pop("_hmac_key_b64"))
if "_public_key_der_b64" in entry:
@@ -235,6 +255,11 @@ def _key_metadata(rec):
# that is, when its KeyState is PendingDeletion."
if "DeletionDate" in rec:
metadata["DeletionDate"] = rec["DeletionDate"]
+ # Both are reported only for a key with imported material.
+ if "ExpirationModel" in rec:
+ metadata["ExpirationModel"] = rec["ExpirationModel"]
+ if "ValidTo" in rec:
+ metadata["ValidTo"] = rec["ValidTo"]
metadata["MultiRegion"] = rec.get("MultiRegion", False)
if rec.get("MultiRegion"):
account = get_account_id()
@@ -306,6 +331,12 @@ def _check_key_state(rec):
f"{rec['Arn']} is pending deletion.",
400,
)
+ if rec["KeyState"] == "PendingImport":
+ return error_response_json(
+ "KMSInvalidStateException",
+ f"{rec['Arn']} is pending import.",
+ 400,
+ )
if rec["KeyState"] == "Disabled":
return error_response_json(
"DisabledException",
@@ -368,6 +399,16 @@ def _create_key(data):
)
description = data.get("Description", "")
tags = data.get("Tags", [])
+ origin = data.get("Origin", "AWS_KMS")
+ if origin not in ("AWS_KMS", "EXTERNAL"):
+ return error_response_json(
+ "UnsupportedOperationException",
+ f"Origin {origin} is not supported.", 400)
+ if origin == "EXTERNAL" and key_spec != "SYMMETRIC_DEFAULT":
+ return error_response_json(
+ "UnsupportedOperationException",
+ "Imported key material is supported for SYMMETRIC_DEFAULT keys only.",
+ 400)
policy = data.get("Policy", json.dumps({
"Version": "2012-10-17",
"Id": "key-default-1",
@@ -389,7 +430,7 @@ def _create_key(data):
"KeyUsage": key_usage,
"Description": description,
"CreationDate": int(time.time()),
- "Origin": "AWS_KMS",
+ "Origin": origin,
"Tags": tags,
"Policy": policy,
"MultiRegion": multi_region,
@@ -404,7 +445,13 @@ def _create_key(data):
rec["_mrk_regions"] = [get_region()]
if key_spec == "SYMMETRIC_DEFAULT":
- rec["_symmetric_key"] = os.urandom(32)
+ # An EXTERNAL key has no material until ImportKeyMaterial supplies it,
+ # so it starts PendingImport rather than Enabled.
+ if origin != "EXTERNAL":
+ rec["_symmetric_key"] = os.urandom(32)
+ else:
+ rec["KeyState"] = "PendingImport"
+ rec["Enabled"] = False
rec["EncryptionAlgorithms"] = ["SYMMETRIC_DEFAULT"]
rec["SigningAlgorithms"] = []
elif key_spec in _HMAC_KEY_SPECS:
@@ -1625,6 +1672,175 @@ def _cancel_key_deletion(data):
# ---- Tags ----
+# ---------------------------------------------------------------------------
+# Imported key material (BYOK). AWS's own flow, not a config file: create the
+# key with Origin EXTERNAL, fetch a wrapping public key and an import token
+# with GetParametersForImport, wrap the material, and hand it to
+# ImportKeyMaterial. Enums and errors from botocore kms service-2.json.
+# ---------------------------------------------------------------------------
+
+_WRAPPING_ALGORITHMS = (
+ "RSAES_PKCS1_V1_5", "RSAES_OAEP_SHA_1", "RSAES_OAEP_SHA_256",
+ "RSA_AES_KEY_WRAP_SHA_1", "RSA_AES_KEY_WRAP_SHA_256",
+)
+_WRAPPING_KEY_SIZES = {"RSA_2048": 2048, "RSA_3072": 3072, "RSA_4096": 4096}
+_IMPORT_TOKEN_VALID_SECONDS = 24 * 3600
+
+
+def _unwrap_key_material(private_key, algorithm: str, wrapped: bytes) -> bytes:
+ """The key material inside `wrapped`, per the WrappingAlgorithm used."""
+ if algorithm == "RSAES_PKCS1_V1_5":
+ return private_key.decrypt(wrapped, padding.PKCS1v15())
+ if algorithm in ("RSAES_OAEP_SHA_1", "RSAES_OAEP_SHA_256"):
+ digest = hashes.SHA1() if algorithm.endswith("SHA_1") else hashes.SHA256()
+ return private_key.decrypt(wrapped, padding.OAEP(
+ mgf=padding.MGF1(algorithm=digest), algorithm=digest, label=None))
+ # RSA_AES_KEY_WRAP_*: an ephemeral AES key wrapped with RSA-OAEP, followed
+ # by the material wrapped under it with AES key wrap with padding (RFC 5649).
+ digest = hashes.SHA1() if algorithm.endswith("SHA_1") else hashes.SHA256()
+ rsa_len = private_key.key_size // 8
+ if len(wrapped) <= rsa_len:
+ raise ValueError("wrapped material is shorter than the RSA block")
+ ephemeral = private_key.decrypt(wrapped[:rsa_len], padding.OAEP(
+ mgf=padding.MGF1(algorithm=digest), algorithm=digest, label=None))
+ return keywrap.aes_key_unwrap_with_padding(ephemeral, wrapped[rsa_len:])
+
+
+def _get_parameters_for_import(data):
+ key_id = data.get("KeyId", "")
+ rec = _resolve_key(key_id)
+ if not rec:
+ return error_response_json("NotFoundException", f"Key {key_id} not found", 400)
+ algorithm = data.get("WrappingAlgorithm", "")
+ key_spec = data.get("WrappingKeySpec", "")
+ if algorithm not in _WRAPPING_ALGORITHMS:
+ return error_response_json(
+ "ValidationException",
+ f"1 validation error detected: Value '{algorithm}' at "
+ "'wrappingAlgorithm' failed to satisfy constraint: Member must "
+ "satisfy enum value set: " + str(sorted(_WRAPPING_ALGORITHMS)), 400)
+ if key_spec not in _WRAPPING_KEY_SIZES:
+ return error_response_json(
+ "UnsupportedOperationException",
+ f"WrappingKeySpec {key_spec} is not supported.", 400)
+ if rec.get("Origin") != "EXTERNAL":
+ return error_response_json(
+ "UnsupportedOperationException",
+ f"{rec['Arn']} origin is not EXTERNAL.", 400)
+ if rec["KeyState"] == "PendingDeletion":
+ return error_response_json(
+ "KMSInvalidStateException", f"{rec['Arn']} is pending deletion.", 400)
+ err = _require_crypto("GetParametersForImport")
+ if err:
+ return err
+
+ wrapping_key = rsa.generate_private_key(
+ public_exponent=65537, key_size=_WRAPPING_KEY_SIZES[key_spec])
+ token = os.urandom(32)
+ rec["_import_wrapping_key"] = wrapping_key
+ rec["_import_token"] = token
+ rec["_import_algorithm"] = algorithm
+ rec["_import_token_expires"] = int(time.time()) + _IMPORT_TOKEN_VALID_SECONDS
+ return json_response({
+ "KeyId": rec["Arn"],
+ "ImportToken": base64.b64encode(token).decode(),
+ "PublicKey": base64.b64encode(wrapping_key.public_key().public_bytes(
+ serialization.Encoding.DER,
+ serialization.PublicFormat.SubjectPublicKeyInfo)).decode(),
+ "ParametersValidTo": rec["_import_token_expires"],
+ })
+
+
+def _import_key_material(data):
+ key_id = data.get("KeyId", "")
+ rec = _resolve_key(key_id)
+ if not rec:
+ return error_response_json("NotFoundException", f"Key {key_id} not found", 400)
+ if rec.get("Origin") != "EXTERNAL":
+ return error_response_json(
+ "UnsupportedOperationException",
+ f"{rec['Arn']} origin is not EXTERNAL.", 400)
+ if rec["KeyState"] == "PendingDeletion":
+ return error_response_json(
+ "KMSInvalidStateException", f"{rec['Arn']} is pending deletion.", 400)
+ expiration = data.get("ExpirationModel", "KEY_MATERIAL_EXPIRES")
+ if expiration not in ("KEY_MATERIAL_EXPIRES", "KEY_MATERIAL_DOES_NOT_EXPIRE"):
+ return error_response_json(
+ "ValidationException",
+ f"1 validation error detected: Value '{expiration}' at "
+ "'expirationModel' failed to satisfy constraint: Member must "
+ "satisfy enum value set: [KEY_MATERIAL_DOES_NOT_EXPIRE, "
+ "KEY_MATERIAL_EXPIRES]", 400)
+ if expiration == "KEY_MATERIAL_EXPIRES" and data.get("ValidTo") is None:
+ return error_response_json(
+ "ValidationException",
+ "ValidTo is required when ExpirationModel is KEY_MATERIAL_EXPIRES.",
+ 400)
+ try:
+ token = base64.b64decode(data.get("ImportToken", "") or "", validate=True)
+ wrapped = base64.b64decode(data.get("EncryptedKeyMaterial", "") or "",
+ validate=True)
+ except (binascii.Error, ValueError):
+ return error_response_json(
+ "ValidationException", "Invalid base64 in the request.", 400)
+ stored = rec.get("_import_token")
+ if not stored or token != stored:
+ return error_response_json(
+ "InvalidImportTokenException",
+ "The import token is invalid for this key.", 400)
+ if int(time.time()) > rec.get("_import_token_expires", 0):
+ return error_response_json(
+ "ExpiredImportTokenException", "The import token has expired.", 400)
+
+ try:
+ material = _unwrap_key_material(
+ rec["_import_wrapping_key"], rec["_import_algorithm"], wrapped)
+ except Exception:
+ return error_response_json(
+ "InvalidCiphertextException",
+ "The key material could not be unwrapped with the wrapping key.",
+ 400)
+ if len(material) != 32:
+ return error_response_json(
+ "IncorrectKeyMaterialException",
+ "A SYMMETRIC_DEFAULT key takes 256 bits of key material.", 400)
+
+ rec["_symmetric_key"] = material
+ rec["KeyState"] = "Enabled"
+ rec["Enabled"] = True
+ rec["ExpirationModel"] = expiration
+ if expiration == "KEY_MATERIAL_EXPIRES":
+ rec["ValidTo"] = data["ValidTo"]
+ else:
+ rec.pop("ValidTo", None)
+ # The token is single-use: a second import needs fresh parameters.
+ for field in ("_import_wrapping_key", "_import_token", "_import_algorithm",
+ "_import_token_expires"):
+ rec.pop(field, None)
+ logger.info("ImportKeyMaterial: %s", rec["KeyId"])
+ return json_response({"KeyId": rec["Arn"]})
+
+
+def _delete_imported_key_material(data):
+ key_id = data.get("KeyId", "")
+ rec = _resolve_key(key_id)
+ if not rec:
+ return error_response_json("NotFoundException", f"Key {key_id} not found", 400)
+ if rec.get("Origin") != "EXTERNAL":
+ return error_response_json(
+ "UnsupportedOperationException",
+ f"{rec['Arn']} origin is not EXTERNAL.", 400)
+ if rec["KeyState"] == "PendingDeletion":
+ return error_response_json(
+ "KMSInvalidStateException", f"{rec['Arn']} is pending deletion.", 400)
+ rec.pop("_symmetric_key", None)
+ rec.pop("ValidTo", None)
+ rec["KeyState"] = "PendingImport"
+ rec["Enabled"] = False
+ logger.info("DeleteImportedKeyMaterial: %s", rec["KeyId"])
+ return json_response({"KeyId": rec["Arn"]})
+
+
def _tag_resource(data):
rec = _resolve_key(data.get("KeyId", ""))
if not rec:
@@ -1746,6 +1962,9 @@ async def handle_request(method, path, headers, body, query_params):
"UpdateKeyDescription": _update_key_description,
"ScheduleKeyDeletion": _schedule_key_deletion,
"CancelKeyDeletion": _cancel_key_deletion,
+ "GetParametersForImport": _get_parameters_for_import,
+ "ImportKeyMaterial": _import_key_material,
+ "DeleteImportedKeyMaterial": _delete_imported_key_material,
"TagResource": _tag_resource,
"UntagResource": _untag_resource,
"ListResourceTags": _list_resource_tags,
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index cf7437f4..15264214 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -1680,14 +1680,44 @@ def _layer_access_denied(layer_arn: str):
)
+# The extensions AWS publishes from its own accounts and grants
+# lambda:GetLayerVersion on to everyone. Keyed by LAYER NAME, not by publisher
+# account: the name is stable while the account differs in every region, so one
+# short list replaces ~190 account ids that go stale as regions are added.
+_AWS_PUBLISHED_LAYER_PREFIXES = (
+ "LambdaInsightsExtension",
+ "AWS-Parameters-and-Secrets-Lambda-Extension",
+ "AWS-AppConfig-Extension",
+ "AWSOpenTelemetryDistro",
+ "aws-otel-",
+ "AWSSDKPandas-",
+)
+
+
+def _is_aws_published_layer(layer_name: str) -> bool:
+ return layer_name.startswith(_AWS_PUBLISHED_LAYER_PREFIXES)
+
+
def _resolve_cross_account_layer(layer_arn: str, spec, name_and_version):
- """Resolve another account's layer version through its stored grant."""
+ """Another account's layer through its grant; an unknown account passes by
+ name, and the bytes are not available offline (CodeSize 0, does not run)."""
if spec.region != get_region():
return _layer_access_denied(layer_arn)
layer_name, version = name_and_version
vc, _ = _find_layer_version(layer_name, version, spec.account_id, spec.region)
if vc is not None and _layer_policy_allows(vc, get_account_id()):
return vc, None
+ if vc is None and _is_aws_published_layer(layer_name):
+ logger.warning(
+ "Layer %s is an AWS-published extension: the reference resolves so "
+ "the stack deploys, but the bytes are not available offline and the "
+ "extension will not run", layer_arn,
+ )
+ return {
+ "LayerVersionArn": layer_arn,
+ "Version": version,
+ "Content": {"CodeSize": 0},
+ }, None
return _layer_access_denied(layer_arn)
@@ -3457,7 +3487,7 @@ def _ensure_reaper_thread() -> None:
# Active / Successful asynchronously when the runtime is ready. Real AWS takes
# seconds to tens of seconds (image pull time for Image type); we use a short
# delay so local integration tests see the transition without spinning.
-_LAMBDA_STATE_TRANSITION_DELAY = float(os.environ.get("LAMBDA_STATE_TRANSITION_SECONDS", "0.5"))
+_LAMBDA_STATE_TRANSITION_DELAY = 0.5
def _schedule_state_transition(func_name: str, delay: float) -> None:
@@ -6342,6 +6372,9 @@ def _find_layer_version(
# rejected with PreconditionFailedException (412) rather than silently
# clobbering a policy that changed underneath them.
_LAYER_PRINCIPAL_RE = re.compile(r"^(\d{12}|\*|arn:aws[a-zA-Z-]*:iam::\d{12}:root)$")
+# The other two modeled constraints on AddLayerVersionPermission.
+_LAYER_ORG_ID_RE = re.compile(r"^o-[a-z0-9]{10,32}$")
+_LAYER_STATEMENT_ID_RE = re.compile(r"^[a-zA-Z0-9\-_]{1,100}$")
def _layer_policy_revision_id(vc: dict) -> str:
@@ -6434,12 +6467,28 @@ def _add_layer_version_permission(
"The principal must be * when an organization id is provided.",
400,
)
+ if org_id and not _LAYER_ORG_ID_RE.match(org_id):
+ return error_response_json(
+ "ValidationException",
+ f"1 validation error detected: Value '{org_id}' at 'organizationId' failed to "
+ "satisfy constraint: Member must satisfy regular expression pattern: "
+ r"o-[a-z0-9]{10,32}",
+ 400,
+ )
err = _layer_policy_revision_mismatch(vc, query_params)
if err:
return err
sid = data.get("StatementId", "")
+ if not _LAYER_STATEMENT_ID_RE.match(sid):
+ return error_response_json(
+ "ValidationException",
+ f"1 validation error detected: Value '{sid}' at 'statementId' failed to satisfy "
+ "constraint: Member must satisfy regular expression pattern: "
+ r"([a-zA-Z0-9-_]+)",
+ 400,
+ )
policy = vc.setdefault("_policy", {"Version": "2012-10-17", "Id": "default", "Statement": []})
for s in policy["Statement"]:
if s.get("Sid") == sid:
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index 539d26f0..e6bf2383 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -44,6 +44,7 @@ import contextvars
import copy
import datetime
import hashlib
+import io
import json
import logging
import math
@@ -51,6 +52,7 @@ import os
import re
import secrets as stdlib_secrets
import socket
+import tarfile
import threading
import time
from urllib.parse import parse_qs
@@ -1049,6 +1051,146 @@ def _rds_container_is_owned_by(
return labels.get("region") in (None, region or get_region())
+# ---------------------------------------------------------------------------
+# PostgreSQL server TLS. AWS installs the DB server certificate itself and
+# rotates it; there is no way to supply your own ("The CA signs the DB server
+# certificate, which is installed on each DB instance", UsingWithRDS.SSL), and
+# every instance we report already carries CACertificateIdentifier
+# rds-ca-rsa2048-g1. So MiniStack mints its own CA and signs a per-container
+# server certificate, and TLS is always on. The stock postgres image ships no
+# key material and dies with `ssl=on` alone, unlike MySQL, which
+# auto-generates (measured: `auto-generate-certs TRUE`).
+# ---------------------------------------------------------------------------
+
+_PG_TLS_DIR = "/ministack-rds-tls"
+_pg_ca_lock = threading.Lock()
+_pg_ca: tuple[str, str] | None = None
+
+
+def pg_ca_cert_pem() -> str:
+ """The RDS CA certificate, minted on first use. Clients verifying a
+ MiniStack database trust this one file, as they would AWS's bundle."""
+ return _ensure_pg_ca()[0]
+
+
+def _ensure_pg_ca() -> tuple[str, str]:
+ global _pg_ca
+ if _pg_ca is not None:
+ return _pg_ca
+ with _pg_ca_lock:
+ if _pg_ca is None:
+ from ministack.core.x509_utils import generate_ca
+
+ _pg_ca = generate_ca(common_name="Ministack RDS Root CA")
+ logger.info("RDS: generated the server-certificate CA")
+ return _pg_ca
+
+
+def _pg_server_material(names, ips) -> tuple[str, str]:
+ """A server certificate for the names a client may connect to."""
+ from ministack.core.x509_utils import sign_leaf_certificate
+
+ ca_cert, ca_key = _ensure_pg_ca()
+ cert_pem, key_pem, _public = sign_leaf_certificate(
+ ca_cert, ca_key,
+ common_name=(names[0] if names else "localhost"),
+ san_dns=names, san_ips=ips,
+ )
+ return cert_pem, key_pem
+
+
+def _pg_tls_archive(cert_pem: str, key_pem: str) -> bytes:
+ """The cert and key as a tar for put_archive: no host path is shared with
+ the daemon, and the key lands outside every PGDATA mount at 0600."""
+ archive = io.BytesIO()
+ with tarfile.open(fileobj=archive, mode="w") as bundle:
+ entry = tarfile.TarInfo(_PG_TLS_DIR.lstrip("/"))
+ entry.type = tarfile.DIRTYPE
+ entry.mode = 0o700
+ bundle.addfile(entry)
+ for filename, content in (("server.crt", cert_pem), ("server.key", key_pem)):
+ data = content.encode()
+ entry = tarfile.TarInfo(f"{_PG_TLS_DIR.lstrip('/')}/{filename}")
+ entry.mode = 0o600
+ entry.size = len(data)
+ bundle.addfile(entry, io.BytesIO(data))
+ return archive.getvalue()
+
+
+def _run_rds_container(docker_client, engine, container_kwargs, tls_names=(), tls_ips=()):
+ """Start a backing container, with PostgreSQL TLS enabled.
+
+ MySQL needs nothing: its image generates its own material and defaults to
+ ssl=ON. PostgreSQL gets a certificate copied in before it starts, so a
+ client using sslmode=verify-full with our CA connects. Plaintext clients
+ keep working, as they do on AWS without rds.force_ssl.
+ """
+ if engine not in ("postgres", "aurora-postgresql"):
+ return docker_client.containers.run(**container_kwargs)
+ # Injecting the certificate needs create -> put_archive -> start, so a
+ # client that cannot do that keeps the plain launch and serves plaintext.
+ if not hasattr(docker_client.containers, "create"):
+ return docker_client.containers.run(**container_kwargs)
+
+ container = None
+ try:
+ names = [n for n in dict.fromkeys(tls_names) if n and not _is_ip_address(n)]
+ names += [n for n in ("localhost", _MINISTACK_HOST) if n and n not in names]
+ ips = [i for i in dict.fromkeys(tuple(tls_ips) + ("127.0.0.1", "::1")) if i]
+ cert_pem, key_pem = _pg_server_material(names, ips)
+ archive = _pg_tls_archive(cert_pem, key_pem)
+
+ kwargs = dict(container_kwargs)
+ command = list(kwargs.get("command") or ["postgres"])
+ if command[:2] == ["sh", "-c"]:
+ # `sh -c SCRIPT` takes the next argument as $0, so the flags land
+ # in "$@" for the script's own exec.
+ command.append("ministack-pg")
+ command += ["-c", "ssl=on",
+ "-c", f"ssl_cert_file={_PG_TLS_DIR}/server.crt",
+ "-c", f"ssl_key_file={_PG_TLS_DIR}/server.key"]
+ entrypoint = kwargs.get("entrypoint") or ["docker-entrypoint.sh"]
+ if isinstance(entrypoint, str):
+ entrypoint = [entrypoint]
+ # Archive members arrive root-owned; chown before the image's own
+ # entrypoint drops privileges. postgres refuses a group/world-readable
+ # key, so the mode matters as much as the owner.
+ kwargs["user"] = "0:0"
+ kwargs["entrypoint"] = [
+ "sh", "-c",
+ f"chown -R postgres:postgres {_PG_TLS_DIR} && exec \"$@\"",
+ "ministack-pg-tls",
+ ]
+ kwargs["command"] = list(entrypoint) + command
+
+ from docker.errors import ImageNotFound
+ try:
+ container = docker_client.containers.create(**kwargs)
+ except ImageNotFound:
+ docker_client.images.pull(kwargs["image"])
+ container = docker_client.containers.create(**kwargs)
+ if not container.put_archive("/", archive):
+ raise RuntimeError("Docker rejected the PostgreSQL TLS archive")
+ container.start()
+ return container
+ except Exception:
+ if container is not None:
+ try:
+ container.remove(force=True, v=False)
+ except Exception:
+ logger.warning("RDS: could not remove a failed TLS container")
+ raise
+
+
+def _is_ip_address(value: str) -> bool:
+ import ipaddress
+ try:
+ ipaddress.ip_address(value)
+ return True
+ except ValueError:
+ return False
+
+
def _start_cluster_shared_container(cluster_id, cluster, remove_stale=False):
"""Start the single backing container owned by an Aurora cluster.
@@ -1198,7 +1340,10 @@ def _start_cluster_shared_container(cluster_id, cluster, remove_stale=False):
container_kwargs["network"]: {"Aliases": list(endpoint_aliases)},
}
try:
- container = docker_client.containers.run(**container_kwargs)
+ container = _run_rds_container(
+ docker_client, engine, container_kwargs,
+ tls_names=list(endpoint_aliases) + [container_kwargs.get("name") or ""],
+ )
except Exception as e:
cluster["_shared_container_ready"] = False
logger.warning("RDS: failed to start shared container for cluster %s: %s", cluster_id, e)
@@ -1431,7 +1576,11 @@ def _start_pg_reader_container(db_id, cluster):
data_path: f"rw,noexec,nosuid,size={RDS_TMPFS_SIZE}",
}
try:
- container = docker_client.containers.run(**container_kwargs)
+ container = _run_rds_container(
+ docker_client, engine, container_kwargs,
+ tls_names=_cluster_endpoint_aliases(cluster)
+ + [container_kwargs.get("name") or ""],
+ )
except Exception as e:
logger.warning(
"RDS: failed to start reader container for %s: %s", db_id, e,
@@ -2296,7 +2445,11 @@ def _start_rds_container_for_instance(db_id, instance):
}
try:
- container = docker_client.containers.run(**container_kwargs)
+ container = _run_rds_container(
+ docker_client, engine, container_kwargs,
+ tls_names=[(instance.get("Endpoint") or {}).get("Address") or "",
+ container_kwargs.get("name") or ""],
+ )
except Exception as e:
logger.warning("RDS: failed to respawn container for %s: %s", db_id, e)
instance["DBInstanceStatus"] = "failed"
@@ -4561,7 +4714,11 @@ def _create_db_instance_impl(p):
container_kwargs["tmpfs"] = {
data_path: f"rw,noexec,nosuid,size={RDS_TMPFS_SIZE}",
}
- container = docker_client.containers.run(**container_kwargs)
+ container = _run_rds_container(
+ docker_client, engine, container_kwargs,
+ tls_names=[endpoint_host or "",
+ container_kwargs.get("name") or ""],
+ )
docker_container_id = container.id
real_container_started = True
if ms_network:
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 17d89810..d81fcf3a 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -2812,6 +2812,51 @@ def _get_bucket_notification(name: str):
return 200, {"Content-Type": "application/xml"}, _xml_body(root)
+def _generated_notification_id() -> str:
+ """An omitted Id is base64 of a UUID (captured us-east-1 2026-09-20)."""
+ return base64.b64encode(new_uuid().encode()).decode().rstrip("=")
+
+
+def _notification_configs_to_xml(configs, has_eventbridge: bool) -> str:
+ """The canonical wire form of a notification configuration.
+
+ Element names come from the S3 model's locationName, which is what every
+ AWS SDK reads: LambdaFunctionConfigurations -> CloudFunctionConfiguration
+ and LambdaFunctionArn -> CloudFunction. Storing whatever spelling the
+ caller happened to send means a GET only parses for that same client.
+ """
+ root = Element("NotificationConfiguration", xmlns=S3_NS)
+ wire = {
+ "sqs": ("QueueConfiguration", "Queue"),
+ "sns": ("TopicConfiguration", "Topic"),
+ "lambda": ("CloudFunctionConfiguration", "CloudFunction"),
+ }
+ for config in configs or []:
+ names = wire.get(config.get("type"))
+ if not names:
+ continue
+ cfg_tag, arn_tag = names
+ cfg_el = SubElement(root, cfg_tag)
+ if config.get("id"):
+ SubElement(cfg_el, "Id").text = str(config["id"])
+ SubElement(cfg_el, arn_tag).text = str(config.get("arn", ""))
+ for event in config.get("events") or []:
+ SubElement(cfg_el, "Event").text = str(event)
+ rules = [("prefix", config.get("filter_prefix")),
+ ("suffix", config.get("filter_suffix"))]
+ if any(value is not None for _name, value in rules):
+ s3key_el = SubElement(SubElement(cfg_el, "Filter"), "S3Key")
+ for name, value in rules:
+ if value is None:
+ continue
+ rule_el = SubElement(s3key_el, "FilterRule")
+ SubElement(rule_el, "Name").text = name
+ SubElement(rule_el, "Value").text = value
+ if has_eventbridge:
+ SubElement(root, "EventBridgeConfiguration")
+ return tostring(root, encoding="unicode")
+
+
def _put_bucket_notification(name: str, body: bytes):
if name not in _buckets:
return _no_such_bucket(name)
@@ -2821,7 +2866,8 @@ def _put_bucket_notification(name: str, body: bytes):
validation_error = _validate_notification_configs(configs, bucket_region)
if validation_error:
return validation_error
- _bucket_notifications[name] = raw
+ _bucket_notifications[name] = _notification_configs_to_xml(
+ configs, "EventBridgeConfiguration" in raw)
# Fire the s3:TestEvent synchronously so it's delivered before PutBucketNotification
# returns — matches AWS's effective behaviour and avoids a race where the
# client polls the destination queue/topic before the background thread has
@@ -3110,7 +3156,8 @@ def _parse_notification_config_raw(raw: str | None) -> list[dict]:
continue
id_el = _find_xml_tag(cfg_el, "Id")
- config_id = id_el.text if id_el is not None and id_el.text else new_uuid()
+ config_id = (id_el.text if id_el is not None and id_el.text
+ else _generated_notification_id())
events: list[str] = []
for ev_el in list(cfg_el.findall(f"{{{S3_NS}}}Event")) + list(cfg_el.findall("Event")):
diff --git a/ministack/services/signer.py b/ministack/services/signer.py
index 9d5d3aa8..d1286e73 100644
--- a/ministack/services/signer.py
+++ b/ministack/services/signer.py
@@ -107,6 +107,7 @@ logger = logging.getLogger("signer")
_jobs = AccountRegionScopedDict() # jobId -> job record (camelCase fields)
_profiles = AccountRegionScopedDict() # profileName -> profile record
_tokens = AccountRegionScopedDict() # clientRequestToken -> first StartSigningJob response
+_TOKEN_CACHE_MAX = 1024 # same bound apigateway_v1 uses for its authorizer cache
def reset():
@@ -544,10 +545,25 @@ def _start_signing_job(body, headers=None):
}
response = {"jobId": job_id, "jobOwner": account}
if token:
- _tokens[token] = dict(response)
+ _remember_token(token, response)
return json_response(response)
+def _remember_token(token: str, response: dict) -> None:
+ """Record a clientRequestToken's first response so a replay returns it.
+
+ Bounded like ``_AUTHORIZER_CACHE_MAX`` in ``apigateway_v1``: the key is the
+ caller's, so an unbounded map grows with every distinct token and is
+ persisted with the rest of the service state. The oldest entries go first;
+ replaying a token older than the bound re-runs the job, which is the same
+ outcome as never having sent one.
+ """
+ if len(_tokens) >= _TOKEN_CACHE_MAX:
+ for stale in list(_tokens)[: len(_tokens) - _TOKEN_CACHE_MAX + 1]:
+ _tokens.pop(stale, None)
+ _tokens[token] = dict(response)
+
+
def _describe_signing_job(job_id):
job = _jobs.get(job_id)
if job is None:
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index 4c505443..74dd989d 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -366,7 +366,7 @@ def _validate_redrive_policy(rp_str: str) -> None:
# CreateQueue/SetQueueAttributes time with InvalidAttributeValue (400).
_NUMERIC_ATTR_RANGES = {
"VisibilityTimeout": (0, 43200), # 0 .. 12 h
- "MaximumMessageSize": (1024, 262144), # 1 KB .. 256 KB
+ "MaximumMessageSize": (1024, 1048576), # 1 KiB .. 1 MiB (captured default)
"MessageRetentionPeriod": (60, 1209600), # 1 min .. 14 days
"DelaySeconds": (0, 900), # 0 .. 15 min
"ReceiveMessageWaitTimeSeconds":(0, 20), # 0 .. 20 s
@@ -428,7 +428,7 @@ def _act_create_queue(data: dict, _u: str) -> dict:
"CreatedTimestamp": ts,
"LastModifiedTimestamp": ts,
"VisibilityTimeout": "30",
- "MaximumMessageSize": "262144",
+ "MaximumMessageSize": "1048576",
"MessageRetentionPeriod": "345600",
"DelaySeconds": "0",
"ReceiveMessageWaitTimeSeconds": "0",
@@ -509,12 +509,12 @@ def _act_send_message(data: dict, qurl: str) -> dict:
)
# AWS SQS rejects messages exceeding the queue's MaximumMessageSize attribute
- # (default 262144 bytes; configurable up to 1 MiB / 1048576). Real AWS error
+ # (default 1048576 bytes / 1 MiB, captured eu-north-1 2026-09-19). Real AWS error
# is InvalidParameterValue (400) with the queue-configured limit in the message.
try:
- max_size = int(q["attributes"].get("MaximumMessageSize", "262144"))
+ max_size = int(q["attributes"].get("MaximumMessageSize", "1048576"))
except (TypeError, ValueError):
- max_size = 262144
+ max_size = 1048576
body_bytes = len(body_text.encode("utf-8"))
if body_bytes > max_size:
raise _Err(
diff --git a/ministack/services/transcribe.py b/ministack/services/transcribe.py
index d5f019e5..b896829c 100644
--- a/ministack/services/transcribe.py
+++ b/ministack/services/transcribe.py
@@ -15,8 +15,7 @@ as the documented AWS response does. QUEUED is reached on AWS only by a
request that opted into job queueing (``JobExecutionSettings.AllowDeferredExecution``)
while the account is at its concurrent job limit; neither the quota nor the
opt-in is modelled here, so a job never queues. A background task
-walks the job to COMPLETED or FAILED over ``TRANSCRIBE_JOB_RUN_SECONDS``
-(0 completes immediately), reads the media
+walks the job to COMPLETED or FAILED over two seconds, reads the media
object out of MiniStack's S3 store, and writes a transcript document back to
S3 in the real Transcribe result format. Entering a terminal state publishes a
``Transcribe Job State Change`` event so EventBridge rules downstream of a
@@ -78,10 +77,8 @@ from ministack.core.responses import (
logger = logging.getLogger("transcribe")
-# How long a job spends between IN_PROGRESS and COMPLETED. Same knob shape as
-# GLUE_CRAWLER_RUN_SECONDS: tests that want to observe a job mid-flight need a
-# non-zero value, tests that just want a result set it to 0.
-_JOB_RUN_SECONDS = float(os.environ.get("TRANSCRIBE_JOB_RUN_SECONDS", "2"))
+# How long a job spends between IN_PROGRESS and COMPLETED.
+_JOB_RUN_SECONDS = 2.0
# Where transcripts land when the caller supplies no OutputBucketName. Real
# Transcribe uses a service-managed bucket and hands back a presigned URL; the
diff --git a/tests/test_account.py b/tests/test_account.py
index a5ddbea3..f975e1f6 100644
--- a/tests/test_account.py
+++ b/tests/test_account.py
@@ -2,9 +2,8 @@ import json
import os
import urllib.request
-import pytest
-
import boto3
+import pytest
_ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.py
index 105160f1..dd04d938 100644
--- a/tests/test_apigatewayv1.py
+++ b/tests/test_apigatewayv1.py
@@ -1034,8 +1034,8 @@ def test_apigwv1_execute_token_authorizer(apigw_v1, lam):
- Allow policy -> 200, with the returned context (values
stringified) plus principalId injected into requestContext.authorizer.
"""
- import urllib.request as _urlreq
import urllib.error as _urlerr
+ import urllib.request as _urlreq
import uuid as _uuid
suffix = _uuid.uuid4().hex[:8]
@@ -1155,8 +1155,8 @@ def test_apigwv1_execute_aws_iam_requires_auth_header(apigw_v1, lam):
We do not verify the SigV4 signature; only the presence check is enforced.
"""
- import urllib.request as _urlreq
import urllib.error as _urlerr
+ import urllib.request as _urlreq
import uuid as _uuid
fname = f"intg-v1-iam-{_uuid.uuid4().hex[:8]}"
@@ -3830,6 +3830,44 @@ def test_apigwv1_authorizer_invalid_validation_expression_is_500(apigw_v1, lam):
_auth_drop_lambda(lam, authz)
+def test_apigwv1_authorizer_without_principal_id_reaches_the_backend(apigw_v1, lam, sqs):
+ """An Allow policy with no principalId is NOT a configuration error: the
+ request reaches the backend with 200 and an authorizer context carrying no
+ principalId (captured eu-north-1 2026-09-20 — HTTP 200, body "ok").
+
+ Restores the coverage #1756 dropped. The sibling below is the contrast: a
+ response with no policyDocument IS a configuration error, because API
+ Gateway has nothing to authorize against.
+ """
+ qname = _auth_counter_queue(sqs)
+ backend = _auth_make_lambda(lam, "be", _AUTH_ECHO_BACKEND)
+ authz = _auth_make_lambda(
+ lam, "noprincipal",
+ _AUTH_MARK_PRELUDE
+ + "def handler(event, context):\n"
+ f" _mark({qname!r})\n"
+ " return {'policyDocument': {'Version': '2012-10-17', 'Statement': [\n"
+ " {'Action': 'execute-api:Invoke', 'Effect': 'Allow',\n"
+ " 'Resource': event['methodArn']}]}}\n",
+ )
+ api_id, _ = _auth_build_api(
+ apigw_v1, backend,
+ dict(name="noprincipal", type="TOKEN", authorizerUri=_auth_lambda_uri(authz),
+ authorizerResultTtlInSeconds=0),
+ )
+ try:
+ url = _auth_execute_url(api_id, "test", "secure")
+ status, body = _auth_http(url, headers={"Authorization": "allow-abc"})
+ assert status == 200, body
+ context = json.loads(body)
+ assert not (context or {}).get("principalId")
+ finally:
+ _auth_drop_api(apigw_v1, api_id)
+ _auth_drop_lambda(lam, backend)
+ _auth_drop_lambda(lam, authz)
+ _auth_delete_queue(sqs, qname)
+
+
def test_apigwv1_authorizer_without_policy_document_is_500_and_not_cached(apigw_v1, lam, sqs):
"""A response with no policyDocument is a misconfigured authorizer: AWS
answers 500 AuthorizerConfigurationException, not an implicit deny — and
@@ -4774,3 +4812,207 @@ def test_apigwv1_gateway_response_defaults_on_the_control_plane(apigw_v1, gwresp
apigw_v1.delete_gateway_response(restApiId=gwresp_api, responseType="DEFAULT_4XX")
got = apigw_v1.get_gateway_response(restApiId=gwresp_api, responseType="UNAUTHORIZED")
assert (got["defaultResponse"], got["responseParameters"]) == (True, {})
+
+
+# The checks API Gateway runs before the integration.
+
+def _mock_method(apigw_v1, api_id, resource_id, http_method, **method_kwargs):
+ apigw_v1.put_method(restApiId=api_id, resourceId=resource_id,
+ httpMethod=http_method, authorizationType="NONE",
+ **method_kwargs)
+ apigw_v1.put_integration(
+ restApiId=api_id, resourceId=resource_id, httpMethod=http_method,
+ type="MOCK", requestTemplates={"application/json": '{"statusCode":200}'})
+ apigw_v1.put_method_response(restApiId=api_id, resourceId=resource_id,
+ httpMethod=http_method, statusCode="200")
+ apigw_v1.put_integration_response(
+ restApiId=api_id, resourceId=resource_id, httpMethod=http_method,
+ statusCode="200", responseTemplates={"application/json": '{"ok":true}'})
+
+
+def _stage_call(api_id, path, method="GET", body=None, headers=()):
+ import urllib.error as _urlerr
+ import urllib.request as _urlreq
+
+ host = f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"
+ req = _urlreq.Request(f"http://{host}/p{path}", method=method,
+ data=body.encode() if isinstance(body, str) else body)
+ req.add_header("Host", host)
+ for name, value in headers:
+ req.add_header(name, value)
+ try:
+ response = _urlreq.urlopen(req)
+ return response.status, response.read().decode()
+ except _urlerr.HTTPError as e:
+ return e.code, e.read().decode()
+
+
+def _gw_api(apigw_v1, name):
+ api_id = apigw_v1.create_rest_api(name=name)["id"]
+ root = apigw_v1.get_resources(restApiId=api_id)["items"][0]["id"]
+ return api_id, root
+
+
+def test_apigwv1_api_key_required_refuses_a_missing_or_unknown_key(apigw_v1):
+ """403 INVALID_API_KEY for a missing or unknown key."""
+ api_id, root = _gw_api(apigw_v1, f"gwkey-{_uuid_mod.uuid4().hex[:8]}")
+ try:
+ resource = apigw_v1.create_resource(restApiId=api_id, parentId=root,
+ pathPart="key")["id"]
+ _mock_method(apigw_v1, api_id, resource, "GET", apiKeyRequired=True)
+ apigw_v1.create_deployment(restApiId=api_id, stageName="p")
+
+ assert _stage_call(api_id, "/key") == (403, '{"message":"Forbidden"}')
+ assert _stage_call(api_id, "/key", headers=[("x-api-key", "nope")]) == (
+ 403, '{"message":"Forbidden"}')
+
+ key = apigw_v1.create_api_key(name=f"k-{_uuid_mod.uuid4().hex[:6]}",
+ enabled=True)
+ assert _stage_call(api_id, "/key",
+ headers=[("x-api-key", key["value"])])[0] == 403
+ plan = apigw_v1.create_usage_plan(
+ name=f"p-{_uuid_mod.uuid4().hex[:6]}",
+ apiStages=[{"apiId": api_id, "stage": "p"}])["id"]
+ apigw_v1.create_usage_plan_key(usagePlanId=plan, keyId=key["id"],
+ keyType="API_KEY")
+ assert _stage_call(api_id, "/key",
+ headers=[("x-api-key", key["value"])]) == (200, '{"ok":true}')
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_usage_plan_quota_is_enforced_per_key(apigw_v1):
+ """Quota 1 serves one request, then 429 QUOTA_EXCEEDED."""
+ api_id, root = _gw_api(apigw_v1, f"gwquota-{_uuid_mod.uuid4().hex[:8]}")
+ try:
+ resource = apigw_v1.create_resource(restApiId=api_id, parentId=root,
+ pathPart="key")["id"]
+ _mock_method(apigw_v1, api_id, resource, "GET", apiKeyRequired=True)
+ apigw_v1.create_deployment(restApiId=api_id, stageName="p")
+ key = apigw_v1.create_api_key(name=f"k-{_uuid_mod.uuid4().hex[:6]}",
+ enabled=True)
+ plan = apigw_v1.create_usage_plan(
+ name=f"p-{_uuid_mod.uuid4().hex[:6]}",
+ apiStages=[{"apiId": api_id, "stage": "p"}],
+ quota={"limit": 1, "offset": 0, "period": "DAY"})["id"]
+ apigw_v1.create_usage_plan_key(usagePlanId=plan, keyId=key["id"],
+ keyType="API_KEY")
+ headers = [("x-api-key", key["value"])]
+ assert _stage_call(api_id, "/key", headers=headers) == (200, '{"ok":true}')
+ assert _stage_call(api_id, "/key", headers=headers) == (
+ 429, '{"message":"Limit Exceeded"}')
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_method_and_stage_throttling_answer_429(apigw_v1):
+ """A 0/0 limit refuses everything; a real limit does not."""
+ api_id, root = _gw_api(apigw_v1, f"gwthr-{_uuid_mod.uuid4().hex[:8]}")
+ try:
+ resource = apigw_v1.create_resource(restApiId=api_id, parentId=root,
+ pathPart="thr")["id"]
+ _mock_method(apigw_v1, api_id, resource, "GET")
+ apigw_v1.create_deployment(restApiId=api_id, stageName="p")
+ assert _stage_call(api_id, "/thr") == (200, '{"ok":true}')
+
+ def throttle(path_prefix, rate, burst):
+ apigw_v1.update_stage(restApiId=api_id, stageName="p", patchOperations=[
+ {"op": "replace", "path": f"{path_prefix}/throttling/rateLimit",
+ "value": str(rate)},
+ {"op": "replace", "path": f"{path_prefix}/throttling/burstLimit",
+ "value": str(burst)},
+ ])
+
+ throttle("/~1thr/GET", 0, 0)
+ assert _stage_call(api_id, "/thr") == (429, '{"message":"Too Many Requests"}')
+ throttle("/~1thr/GET", 100, 50)
+ assert _stage_call(api_id, "/thr") == (200, '{"ok":true}')
+ apigw_v1.update_stage(restApiId=api_id, stageName="p", patchOperations=[
+ {"op": "remove", "path": "/~1thr/GET"}])
+ throttle("/*/*", 0, 0)
+ assert _stage_call(api_id, "/thr") == (429, '{"message":"Too Many Requests"}')
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_request_validator_checks_parameters_and_body(apigw_v1):
+ """BAD_REQUEST_PARAMETERS and BAD_REQUEST_BODY."""
+ api_id, root = _gw_api(apigw_v1, f"gwval-{_uuid_mod.uuid4().hex[:8]}")
+ try:
+ apigw_v1.create_model(
+ restApiId=api_id, name="m1", contentType="application/json",
+ schema=json.dumps({"type": "object", "required": ["name"],
+ "properties": {"name": {"type": "string"}}}))
+ validator = apigw_v1.create_request_validator(
+ restApiId=api_id, name="v", validateRequestBody=True,
+ validateRequestParameters=True)["id"]
+ resource = apigw_v1.create_resource(restApiId=api_id, parentId=root,
+ pathPart="val")["id"]
+ _mock_method(apigw_v1, api_id, resource, "POST",
+ requestValidatorId=validator,
+ requestModels={"application/json": "m1"},
+ requestParameters={"method.request.querystring.q": True})
+ apigw_v1.create_deployment(restApiId=api_id, stageName="p")
+ json_header = [("Content-Type", "application/json")]
+
+ assert _stage_call(api_id, "/val", "POST", '{"name":"x"}', json_header) == (
+ 400, '{"message":"Missing required request parameters: [q]"}')
+ assert _stage_call(api_id, "/val?q=1", "POST", "{}", json_header) == (
+ 400, '{"message":"Invalid request body"}')
+ assert _stage_call(api_id, "/val?q=1", "POST", "not json", json_header) == (
+ 400, '{"message":"Invalid request body"}')
+ assert _stage_call(api_id, "/val?q=1", "POST", '{"name":123}', json_header) == (
+ 400, '{"message":"Invalid request body"}')
+ assert _stage_call(api_id, "/val?q=1", "POST", '{"name":"x"}',
+ json_header) == (200, '{"ok":true}')
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_strict_passthrough_refuses_an_unmatched_media_type(apigw_v1):
+ """415 UNSUPPORTED_MEDIA_TYPE."""
+ api_id, root = _gw_api(apigw_v1, f"gwmedia-{_uuid_mod.uuid4().hex[:8]}")
+ try:
+ resource = apigw_v1.create_resource(restApiId=api_id, parentId=root,
+ pathPart="media")["id"]
+ _mock_method(apigw_v1, api_id, resource, "POST")
+ apigw_v1.update_integration(
+ restApiId=api_id, resourceId=resource, httpMethod="POST",
+ patchOperations=[{"op": "replace", "path": "/passthroughBehavior",
+ "value": "NEVER"}])
+ apigw_v1.create_deployment(restApiId=api_id, stageName="p")
+ assert _stage_call(api_id, "/media", "POST", "hello",
+ [("Content-Type", "text/plain")]) == (
+ 415, '{"message":"Unsupported Media Type"}')
+ assert _stage_call(api_id, "/media", "POST", "{}",
+ [("Content-Type", "application/json")]) == (200, '{"ok":true}')
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_request_validator_crud(apigw_v1):
+ api_id, _root = _gw_api(apigw_v1, f"gwrv-{_uuid_mod.uuid4().hex[:8]}")
+ try:
+ created = apigw_v1.create_request_validator(
+ restApiId=api_id, name="v1", validateRequestBody=True,
+ validateRequestParameters=True)
+ assert created["name"] == "v1"
+ assert created["validateRequestBody"] is True
+ assert [v["name"] for v in apigw_v1.get_request_validators(
+ restApiId=api_id)["items"]] == ["v1"]
+ assert apigw_v1.get_request_validator(
+ restApiId=api_id, requestValidatorId=created["id"])["name"] == "v1"
+ updated = apigw_v1.update_request_validator(
+ restApiId=api_id, requestValidatorId=created["id"], patchOperations=[
+ {"op": "replace", "path": "/name", "value": "renamed"},
+ {"op": "replace", "path": "/validateRequestBody", "value": "false"}])
+ assert (updated["name"], updated["validateRequestBody"]) == ("renamed", False)
+ apigw_v1.delete_request_validator(
+ restApiId=api_id, requestValidatorId=created["id"])
+ assert apigw_v1.get_request_validators(restApiId=api_id)["items"] == []
+ with pytest.raises(ClientError) as exc:
+ apigw_v1.get_request_validator(restApiId=api_id,
+ requestValidatorId=created["id"])
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api_id)
diff --git a/tests/test_appconfig.py b/tests/test_appconfig.py
index e0a287ee..ad7e73bd 100644
--- a/tests/test_appconfig.py
+++ b/tests/test_appconfig.py
@@ -836,3 +836,86 @@ def test_appconfig_applications_are_region_scoped():
client.delete_application(ApplicationId=app_id)
except Exception:
pass
+
+
+def _deploy_and_fetch(appconfig_client, appconfigdata_client, profile_type, content,
+ suffix):
+ """Create app/env/profile, deploy `content`, and return the served bytes."""
+ app = appconfig_client.create_application(Name=f"ff-app-{suffix}")
+ env = appconfig_client.create_environment(ApplicationId=app["Id"], Name="env")
+ profile = appconfig_client.create_configuration_profile(
+ ApplicationId=app["Id"], Name=f"p-{suffix}", LocationUri="hosted",
+ Type=profile_type,
+ )
+ appconfig_client.create_hosted_configuration_version(
+ ApplicationId=app["Id"], ConfigurationProfileId=profile["Id"],
+ Content=json.dumps(content).encode("utf-8"), ContentType="application/json",
+ )
+ strategy = appconfig_client.create_deployment_strategy(
+ Name=f"s-{suffix}", DeploymentDurationInMinutes=0, GrowthFactor=100.0,
+ ReplicateTo="NONE",
+ )
+ appconfig_client.start_deployment(
+ ApplicationId=app["Id"], EnvironmentId=env["Id"],
+ DeploymentStrategyId=strategy["Id"],
+ ConfigurationProfileId=profile["Id"], ConfigurationVersion="1",
+ )
+ session = appconfigdata_client.start_configuration_session(
+ ApplicationIdentifier=app["Id"], EnvironmentIdentifier=env["Id"],
+ ConfigurationProfileIdentifier=profile["Id"],
+ )
+ latest = appconfigdata_client.get_latest_configuration(
+ ConfigurationToken=session["InitialConfigurationToken"])
+ return json.loads(latest["Configuration"].read())
+
+
+_FEATURE_FLAGS_DEPLOYMENT_TIME = {
+ "flags": {
+ "my_flag": {"name": "my_flag", "attributes": {"level": {"constraints": {"type": "string"}}}},
+ "off_flag": {"name": "off_flag"},
+ },
+ "values": {
+ "my_flag": {"enabled": True, "level": "INFO"},
+ "off_flag": {"enabled": False},
+ },
+ "version": "1",
+}
+
+
+def test_appconfig_feature_flags_are_served_in_retrieval_time_format(
+ appconfig_client, appconfigdata_client):
+ """A feature-flag profile is stored in deployment-time format and served in
+ retrieval-time format, "which only contains the flag's value" -- the values
+ map lifted to the top level, with no flags/version wrapper. A disabled flag
+ is still served, carrying enabled false."""
+ served = _deploy_and_fetch(
+ appconfig_client, appconfigdata_client, "AWS.AppConfig.FeatureFlags",
+ _FEATURE_FLAGS_DEPLOYMENT_TIME, "ff",
+ )
+ assert served == {
+ "my_flag": {"enabled": True, "level": "INFO"},
+ "off_flag": {"enabled": False},
+ }
+ assert "flags" not in served
+ assert "version" not in served
+
+
+def test_appconfig_freeform_content_is_served_verbatim(
+ appconfig_client, appconfigdata_client):
+ """Only a feature-flag profile is transformed; a freeform profile that
+ happens to carry a `values` key keeps it."""
+ document = {"values": {"not": "a flag"}, "greeting": "hello"}
+ assert _deploy_and_fetch(
+ appconfig_client, appconfigdata_client, "AWS.Freeform", document, "free",
+ ) == document
+
+
+def test_appconfig_feature_flags_without_values_are_served_verbatim(
+ appconfig_client, appconfigdata_client):
+ """Content that does not carry the deployment-time shape is passed through
+ rather than emptied."""
+ document = {"my_flag": {"enabled": True}}
+ assert _deploy_and_fetch(
+ appconfig_client, appconfigdata_client, "AWS.AppConfig.FeatureFlags",
+ document, "noval",
+ ) == document
diff --git a/tests/test_bedrock.py b/tests/test_bedrock.py
index 14e42a75..61d40f3a 100644
--- a/tests/test_bedrock.py
+++ b/tests/test_bedrock.py
@@ -12,6 +12,7 @@ import urllib.parse
import urllib.request
import botocore.exceptions
+import pytest
from conftest import ENDPOINT, make_client
# ---------------------------------------------------------------------------
@@ -1815,3 +1816,159 @@ def test_bedrock_list_tags_rejects_unknown_resource_arn():
assert exc.response["Error"]["Code"] == "ResourceNotFoundException"
else:
raise AssertionError("expected ResourceNotFoundException")
+
+
+# ---------------------------------------------------------------------------
+# Converse toolConfig <-> OpenAI tools. The mapping is pure, so it is exercised
+# directly rather than through a live model endpoint.
+# ---------------------------------------------------------------------------
+
+_TOOL_SPEC = {
+ "tools": [{"toolSpec": {
+ "name": "get_weather",
+ "description": "Get weather",
+ "inputSchema": {"json": {"type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"]}},
+ }}],
+}
+
+
+def test_bedrock_converse_tool_config_maps_to_openai_tools():
+ from ministack.services import bedrock_runtime as br
+
+ tools, choice = br._openai_tools(_TOOL_SPEC)
+ assert tools == [{"type": "function", "function": {
+ "name": "get_weather",
+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}},
+ "required": ["city"]},
+ "description": "Get weather",
+ }}]
+ assert choice is None
+
+
[email protected](("tool_choice", "expected"), [
+ ({"auto": {}}, "auto"),
+ ({"any": {}}, "required"),
+ ({"tool": {"name": "get_weather"}},
+ {"type": "function", "function": {"name": "get_weather"}}),
+])
+def test_bedrock_converse_tool_choice_maps(tool_choice, expected):
+ from ministack.services import bedrock_runtime as br
+
+ _tools, choice = br._openai_tools({**_TOOL_SPEC, "toolChoice": tool_choice})
+ assert choice == expected
+
+
+def test_bedrock_converse_tool_use_and_result_survive_the_round_trip():
+ """A tool-calling loop keeps its history: the assistant's toolUse becomes an
+ OpenAI tool_call and the user's toolResult becomes a role "tool" message."""
+ from ministack.services import bedrock_runtime as br
+
+ messages = [
+ {"role": "user", "content": [{"text": "weather in Paris?"}]},
+ {"role": "assistant", "content": [{"toolUse": {
+ "toolUseId": "call_abc", "name": "get_weather", "input": {"city": "Paris"}}}]},
+ {"role": "user", "content": [{"toolResult": {
+ "toolUseId": "call_abc", "content": [{"json": {"tempC": 18}}],
+ "status": "success"}}]},
+ ]
+ assert br._openai_messages(messages, []) == [
+ {"role": "user", "content": "weather in Paris?"},
+ {"role": "assistant", "content": None, "tool_calls": [{
+ "id": "call_abc", "type": "function",
+ "function": {"name": "get_weather", "arguments": '{"city": "Paris"}'}}]},
+ {"role": "tool", "tool_call_id": "call_abc", "content": '{"tempC": 18}'},
+ ]
+
+
+def test_bedrock_converse_tool_call_becomes_a_tool_use_block():
+ from ministack.services import bedrock_runtime as br
+
+ blocks, stop_reason = br._converse_blocks_from_message({
+ "role": "assistant", "content": "",
+ "tool_calls": [{"id": "call_abc", "type": "function",
+ "function": {"name": "get_weather",
+ "arguments": '{"city": "Paris"}'}}],
+ })
+ assert stop_reason == "tool_use"
+ assert blocks == [{"toolUse": {"toolUseId": "call_abc", "name": "get_weather",
+ "input": {"city": "Paris"}}}]
+
+
+def test_bedrock_converse_plain_reply_still_ends_the_turn():
+ from ministack.services import bedrock_runtime as br
+
+ blocks, stop_reason = br._converse_blocks_from_message(
+ {"role": "assistant", "content": "hello"})
+ assert (blocks, stop_reason) == ([{"text": "hello"}], "end_turn")
+
+
+def test_bedrock_converse_unparseable_tool_arguments_are_malformed_tool_use():
+ """malformed_tool_use is a documented Converse stopReason; a model that
+ emits invalid JSON arguments is not a proxy failure."""
+ from ministack.services import bedrock_runtime as br
+
+ _blocks, stop_reason = br._converse_blocks_from_message({
+ "role": "assistant", "content": "",
+ "tool_calls": [{"id": "c", "type": "function",
+ "function": {"name": "t", "arguments": "{not json"}}],
+ })
+ assert stop_reason == "malformed_tool_use"
+
+
+def test_bedrock_converse_without_tool_config_sends_no_tools():
+ from ministack.services import bedrock_runtime as br
+
+ assert br._openai_tools(None) == ([], None)
+ assert br._openai_tools({}) == ([], None)
+
+
+def test_bedrock_converse_stream_emits_the_tool_use_event_sequence():
+ """A tool call streams as its own content block: contentBlockStart carries
+ toolUseId and name, the input arrives as a JSON string in a toolUse delta,
+ and the turn stops with tool_use."""
+ from botocore.eventstream import EventStreamBuffer
+
+ from ministack.services import bedrock_runtime as br
+
+ raw = br._build_converse_stream(
+ "m", [{"role": "user", "content": [{"text": "hi"}]}], [], 0, "",
+ stop_reason="tool_use",
+ tool_uses=[{"toolUseId": "call_abc", "name": "get_weather",
+ "input": {"city": "Paris"}}],
+ )
+ buffer = EventStreamBuffer()
+ buffer.add_data(raw)
+ events = []
+ for event in buffer:
+ headers = event.headers
+ events.append((headers.get(":event-type"), json.loads(event.payload)))
+
+ kinds = [name for name, _ in events]
+ assert kinds == ["messageStart", "contentBlockDelta", "contentBlockStop",
+ "contentBlockStart", "contentBlockDelta", "contentBlockStop",
+ "messageStop", "metadata"], kinds
+ start = dict(events)["contentBlockStart"]
+ assert start == {"contentBlockIndex": 1,
+ "start": {"toolUse": {"toolUseId": "call_abc",
+ "name": "get_weather"}}}
+ tool_delta = [p for name, p in events
+ if name == "contentBlockDelta" and "toolUse" in p["delta"]][0]
+ assert tool_delta["contentBlockIndex"] == 1
+ assert json.loads(tool_delta["delta"]["toolUse"]["input"]) == {"city": "Paris"}
+ assert dict(events)["messageStop"] == {"stopReason": "tool_use"}
+
+
+def test_bedrock_converse_stream_without_tools_is_unchanged():
+ from botocore.eventstream import EventStreamBuffer
+
+ from ministack.services import bedrock_runtime as br
+
+ raw = br._build_converse_stream(
+ "m", [{"role": "user", "content": [{"text": "hi"}]}], [], 0, "hello")
+ buffer = EventStreamBuffer()
+ buffer.add_data(raw)
+ kinds = [e.headers.get(":event-type") for e in buffer]
+ assert "contentBlockStart" not in kinds
+ assert kinds[0] == "messageStart" and kinds[-1] == "metadata"
diff --git a/tests/test_bedrock_agent_runtime.py b/tests/test_bedrock_agent_runtime.py
index afde0aac..ef4b8588 100644
--- a/tests/test_bedrock_agent_runtime.py
+++ b/tests/test_bedrock_agent_runtime.py
@@ -6,7 +6,11 @@ bedrock-agent-runtime-2023-07-26. Streaming ops drive boto3's EventStream
parser to validate eventstream framing + event sequence.
"""
+import json
+import uuid as _uuid_mod
+
import botocore.exceptions
+import pytest
from conftest import make_client
@@ -445,3 +449,91 @@ def test_bedrock_ar_list_tags_rejects_unknown_resource_arn():
assert exc.response["Error"]["Code"] == "ResourceNotFoundException"
else:
raise AssertionError("expected ResourceNotFoundException")
+
+
+def _ingest_with_metadata(suffix):
+ """Three documents sharing a query term: one without metadata, one with the
+ typed sidecar form, one with a plain scalar."""
+ bucket = f"kb-filter-{suffix}"
+ s3 = make_client("s3")
+ s3.create_bucket(Bucket=bucket)
+ s3.put_object(Bucket=bucket, Key="kb/a.txt", Body=b"alpha shared keyword")
+ s3.put_object(Bucket=bucket, Key="kb/b.txt", Body=b"beta shared keyword")
+ s3.put_object(Bucket=bucket, Key="kb/b.txt.metadata.json", Body=json.dumps({
+ "metadataAttributes": {
+ "file_id": {"value": {"type": "STRING", "stringValue": "file-abc123"},
+ "includeForEmbedding": False},
+ "rank": {"value": {"type": "NUMBER", "numberValue": 7}},
+ "tags": {"value": {"type": "STRING_LIST", "stringListValue": ["x", "y"]}},
+ },
+ }).encode())
+ s3.put_object(Bucket=bucket, Key="kb/c.txt", Body=b"gamma shared keyword")
+ s3.put_object(Bucket=bucket, Key="kb/c.txt.metadata.json",
+ Body=json.dumps({"metadataAttributes": {"file_id": "plain-form"}}).encode())
+ kb = _make_kb(f"kb-filter-{suffix}")["knowledgeBaseId"]
+ agent_api = make_client("bedrock-agent")
+ ds = agent_api.create_data_source(
+ knowledgeBaseId=kb, name="ds",
+ dataSourceConfiguration={"type": "S3", "s3Configuration": {
+ "bucketArn": f"arn:aws:s3:::{bucket}", "inclusionPrefixes": ["kb/"]}},
+ )["dataSource"]["dataSourceId"]
+ agent_api.start_ingestion_job(knowledgeBaseId=kb, dataSourceId=ds)
+ return kb
+
+
+def _names(kb, metadata_filter=None):
+ config = {"vectorSearchConfiguration": {"numberOfResults": 10}}
+ if metadata_filter is not None:
+ config["vectorSearchConfiguration"]["filter"] = metadata_filter
+ response = _ar().retrieve(
+ knowledgeBaseId=kb, retrievalQuery={"text": "shared keyword"},
+ retrievalConfiguration=config,
+ )
+ return sorted(r["location"]["s3Location"]["uri"].rsplit("/", 1)[-1]
+ for r in response["retrievalResults"])
+
+
[email protected](("metadata_filter", "expected"), [
+ (None, ["a.txt", "b.txt", "c.txt"]),
+ ({"equals": {"key": "file_id", "value": "file-abc123"}}, ["b.txt"]),
+ ({"equals": {"key": "file_id", "value": "plain-form"}}, ["c.txt"]),
+ ({"notEquals": {"key": "file_id", "value": "file-abc123"}}, ["a.txt", "c.txt"]),
+ ({"startsWith": {"key": "file_id", "value": "file-"}}, ["b.txt"]),
+ ({"stringContains": {"key": "file_id", "value": "abc"}}, ["b.txt"]),
+ ({"in": {"key": "file_id", "value": ["file-abc123", "plain-form"]}},
+ ["b.txt", "c.txt"]),
+ ({"notIn": {"key": "file_id", "value": ["file-abc123"]}}, ["a.txt", "c.txt"]),
+ ({"greaterThan": {"key": "rank", "value": 5}}, ["b.txt"]),
+ ({"greaterThanOrEquals": {"key": "rank", "value": 7}}, ["b.txt"]),
+ ({"lessThan": {"key": "rank", "value": 7}}, []),
+ ({"lessThanOrEquals": {"key": "rank", "value": 7}}, ["b.txt"]),
+ ({"listContains": {"key": "tags", "value": "x"}}, ["b.txt"]),
+ ({"andAll": [{"equals": {"key": "file_id", "value": "file-abc123"}},
+ {"greaterThan": {"key": "rank", "value": 5}}]}, ["b.txt"]),
+ ({"orAll": [{"equals": {"key": "file_id", "value": "file-abc123"}},
+ {"equals": {"key": "file_id", "value": "plain-form"}}]},
+ ["b.txt", "c.txt"]),
+ ({"equals": {"key": "missing", "value": "x"}}, []),
+])
+def test_bedrock_ar_retrieve_applies_the_metadata_filter(metadata_filter, expected):
+ """Retrieve honours retrievalConfiguration.vectorSearchConfiguration.filter
+ across the RetrievalFilter grammar: the eleven comparators plus andAll and
+ orAll. Without it a shared knowledge base leaks every tenant's documents."""
+ kb = _ingest_with_metadata(f"{_uuid_mod.uuid4().hex[:8]}")
+ assert _names(kb, metadata_filter) == expected
+
+
+def test_bedrock_ar_retrieve_returns_the_document_metadata():
+ """RetrievalResultMetadata carries the attributes the sidecar defined; a
+ document without a sidecar omits the key, since the map has min 1."""
+ kb = _ingest_with_metadata(f"{_uuid_mod.uuid4().hex[:8]}")
+ response = _ar().retrieve(
+ knowledgeBaseId=kb, retrievalQuery={"text": "shared keyword"},
+ retrievalConfiguration={"vectorSearchConfiguration": {"numberOfResults": 10}},
+ )
+ by_name = {r["location"]["s3Location"]["uri"].rsplit("/", 1)[-1]: r
+ for r in response["retrievalResults"]}
+ assert by_name["b.txt"]["metadata"] == {
+ "file_id": "file-abc123", "rank": 7, "tags": ["x", "y"]}
+ assert by_name["c.txt"]["metadata"] == {"file_id": "plain-form"}
+ assert "metadata" not in by_name["a.txt"]
diff --git a/tests/test_bedrock_agentcore.py b/tests/test_bedrock_agentcore.py
index 96c4831d..6f3e84fd 100644
--- a/tests/test_bedrock_agentcore.py
+++ b/tests/test_bedrock_agentcore.py
@@ -5,12 +5,14 @@ InvokeAgentRuntime (deterministic echo), region isolation, and validation.
"""
import json
import os
+import urllib.request
import uuid as _uuid_mod
import boto3
import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
+from botocore.utils import parse_timestamp
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
@@ -156,3 +158,62 @@ def test_agentcore_create_validation():
agentRuntimeName="bad name!", agentRuntimeArtifact=_ARTIFACT,
roleArn=_ROLE, networkConfiguration=_NET)
assert exc.value.response["Error"]["Code"] == "ValidationException"
+
+
+def _raw(method, path, body=None):
+ """The wire bytes, not boto3's parse: botocore accepts a number for an
+ iso8601 timestamp, so only the raw JSON shows what the SDKs actually get."""
+ request = urllib.request.Request(
+ f"{ENDPOINT}{path}", method=method,
+ data=json.dumps(body).encode() if body is not None else None,
+ headers={
+ "Content-Type": "application/json",
+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/"
+ "us-east-1/bedrock-agentcore/aws4_request",
+ },
+ )
+ with urllib.request.urlopen(request, timeout=15) as response:
+ return json.loads(response.read() or b"{}")
+
+
+def test_agentcore_timestamps_are_iso8601_strings_on_the_wire():
+ """DateTimestamp carries timestampFormat iso8601, so every timestamp this
+ service answers is an RFC 3339 string. A JSON number fails the Go SDK's
+ deserializer outright, so Terraform cannot record the resource."""
+ ctl = _client("bedrock-agentcore-control")
+ name = f"rt_{_uuid_mod.uuid4().hex[:8]}"
+ created = _raw("PUT", "/runtimes", {
+ "agentRuntimeName": name, "roleArn": _ROLE,
+ "networkConfiguration": _NET, "agentRuntimeArtifact": _ARTIFACT,
+ })
+ rid = created["agentRuntimeId"]
+ try:
+ def check(payload, *fields, where=""):
+ for field in fields:
+ value = payload[field]
+ assert isinstance(value, str), f"{where}{field} is {type(value).__name__}"
+ # botocore parses what it is handed; a float would also parse,
+ # so the type assertion above is the one that matters.
+ assert parse_timestamp(value).tzinfo is not None, f"{where}{field}"
+
+ check(created, "createdAt", where="CreateAgentRuntime.")
+ check(_raw("GET", f"/runtimes/{rid}"), "createdAt", "lastUpdatedAt",
+ where="GetAgentRuntime.")
+ listed = _raw("POST", "/runtimes?maxResults=10", {})["agentRuntimes"]
+ check(next(r for r in listed if r["agentRuntimeId"] == rid),
+ "lastUpdatedAt", where="ListAgentRuntimes.")
+ updated = _raw("PUT", f"/runtimes/{rid}", {
+ "roleArn": _ROLE, "networkConfiguration": _NET,
+ "agentRuntimeArtifact": _ARTIFACT,
+ })
+ check(updated, "createdAt", "lastUpdatedAt", where="UpdateAgentRuntime.")
+
+ endpoint = _raw("PUT", f"/runtimes/{rid}/runtime-endpoints", {"name": "ep1"})
+ check(endpoint, "createdAt", where="CreateAgentRuntimeEndpoint.")
+ check(_raw("GET", f"/runtimes/{rid}/runtime-endpoints/ep1"),
+ "createdAt", "lastUpdatedAt", where="GetAgentRuntimeEndpoint.")
+ eps = _raw("POST", f"/runtimes/{rid}/runtime-endpoints?maxResults=10", {})
+ check(eps["runtimeEndpoints"][0], "createdAt", "lastUpdatedAt",
+ where="ListAgentRuntimeEndpoints.")
+ finally:
+ ctl.delete_agent_runtime(agentRuntimeId=rid)
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index d02d13e8..639d3306 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -5335,7 +5335,8 @@ def test_cfn_wafv2_web_acl_uses_canonical_arn(
},
},
"Outputs": {
- "AclId": {"Value": {"Ref": "Acl"}},
+ "AclRef": {"Value": {"Ref": "Acl"}},
+ "AclId": {"Value": {"Fn::GetAtt": ["Acl", "Id"]}},
"AclArn": {"Value": {"Fn::GetAtt": ["Acl", "Arn"]}},
},
}
@@ -5349,6 +5350,8 @@ def test_cfn_wafv2_web_acl_uses_canonical_arn(
f"arn:aws:wafv2:{arn_region}:000000000000:"
f"{arn_segment}/webacl/{acl_name}/{outputs['AclId']}"
)
+ # Ref is name|id|scope, not the bare id.
+ assert outputs["AclRef"] == f"{acl_name}|{outputs['AclId']}|{scope}"
acls = wafv2.list_web_acls(Scope=scope)["WebACLs"]
assert outputs["AclArn"] in {acl["ARN"] for acl in acls}
tags = wafv2.list_tags_for_resource(ResourceARN=outputs["AclArn"])
@@ -6520,6 +6523,7 @@ def _cfn_web_acl_template(uid, description, scope="REGIONAL", metric="cfnacl"):
},
"Outputs": {
"AclRef": {"Value": {"Ref": "Acl"}},
+ "AclId": {"Value": {"Fn::GetAtt": ["Acl", "Id"]}},
"AclArn": {"Value": {"Fn::GetAtt": ["Acl", "Arn"]}},
},
})
@@ -6538,14 +6542,16 @@ def test_cfn_wafv2_web_acl_update_keeps_its_id_and_arn(cfn, wafv2):
try:
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
- acl_id = _output(stack, "AclRef")
+ acl_id = _output(stack, "AclId")
+ acl_ref = _output(stack, "AclRef")
acl_arn = _output(stack, "AclArn")
cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_web_acl_template(
uid, "after", metric="cfnaclrenamed"))
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
- assert _output(stack, "AclRef") == acl_id
+ assert _output(stack, "AclRef") == acl_ref
+ assert _output(stack, "AclId") == acl_id
assert _output(stack, "AclArn") == acl_arn
acl = wafv2.get_web_acl(Name=f"cfn-acl-{uid}", Scope="REGIONAL",
Id=acl_id)["WebACL"]
@@ -7037,7 +7043,7 @@ def test_cfn_replacing_change_under_custom_name_fails_loudly(
_cfn_web_acl_template(uid, "d"),
_cfn_web_acl_template(uid, "d", scope="CLOUDFRONT"),
lambda st: [a["Id"] for a in wafv2.list_web_acls(Scope="REGIONAL")["WebACLs"]
- if a["Name"] == f"cfn-acl-{uid}"] == [_output(st, "AclRef")],
+ if a["Name"] == f"cfn-acl-{uid}"] == [_output(st, "AclId")],
True),
"vault_key": (
_cfn_backup_template(uid, 1, "a"),
@@ -7107,6 +7113,7 @@ def _cfn_auto_named_template(uid, *, lb_type="application", port=80,
"LbRef": {"Value": {"Ref": "LB"}},
"TgRef": {"Value": {"Ref": "TG"}},
"AclRef": {"Value": {"Ref": "Acl"}},
+ "AclId": {"Value": {"Fn::GetAtt": ["Acl", "Id"]}},
},
})
@@ -7127,7 +7134,7 @@ def test_cfn_replacing_property_replaces_an_auto_named_resource(
assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
lb_arn = _output(stack, "LbRef")
tg_arn = _output(stack, "TgRef")
- acl_id = _output(stack, "AclRef")
+ acl_id = _output(stack, "AclId")
cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_auto_named_template(
uid, lb_type="network", port=8080, scope="CLOUDFRONT"))
@@ -7135,7 +7142,7 @@ def test_cfn_replacing_property_replaces_an_auto_named_resource(
assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
new_lb = _output(stack, "LbRef")
new_tg = _output(stack, "TgRef")
- new_acl = _output(stack, "AclRef")
+ new_acl = _output(stack, "AclId")
assert new_lb != lb_arn
assert new_tg != tg_arn
assert new_acl != acl_id
@@ -22898,8 +22905,11 @@ def test_cfn_rules_cdk_check_bootstrap_version(cfn, ssm):
def test_cfn_rules_condition_and_list_functions(cfn):
"""A rule whose RuleCondition is false is skipped; Fn::Contains,
Fn::EachMemberEquals and Fn::EachMemberIn see a CommaDelimitedList
- parameter as a list of trimmed members; Fn::And, Fn::Or, Fn::Equals and
- Fn::If nest; the pseudo parameters resolve."""
+ parameter as a list of trimmed members; Fn::And, Fn::Or and Fn::Equals
+ nest; the pseudo parameters resolve. Fn::If is deliberately absent: a real
+ account refuses it in the Rules block ("Following functions are not
+ supported in the Rules block of the template: [Fn::If]", us-east-1
+ 2026-09-19), even though the resource reference lists it."""
uid = _uuid_mod.uuid4().hex[:8]
params = {
"Env": {"Type": "String", "Default": "test"},
@@ -22924,9 +22934,7 @@ def test_cfn_rules_condition_and_list_functions(cfn):
{"Fn::Or": [{"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]},
{"Fn::Equals": [{"Ref": "AWS::AccountId"}, "000000000000"]}]},
{"Fn::Not": [{"Fn::Equals": [{"Ref": "AWS::Partition"}, "aws-cn"]}]},
- {"Fn::Contains": [{"Ref": "Zones"},
- {"Fn::If": [{"Fn::Equals": [{"Ref": "Env"}, "test"]},
- "us-east-1b", "us-east-1z"]}]},
+ {"Fn::Contains": [{"Ref": "Zones"}, "us-east-1b"]},
]}}]},
}
body = _rules_template(rules, params)
@@ -23954,3 +23962,57 @@ def test_cfn_language_extensions_condition_from_an_intrinsic(cfn, ssm):
ssm.get_parameter(Name=prefix + "/beta")
finally:
_delete_cfn_test_stack(cfn, name)
+
+
+def test_cfn_s3_bucket_lambda_notification_reads_back(cfn, s3, lam):
+ """An AWS::S3::Bucket NotificationConfiguration with a LambdaConfigurations
+ entry has to be readable through GetBucketNotificationConfiguration. The CFN
+ property names differ from the API's (Function, singular Event), and the wire
+ element names differ again -- the S3 model spells the lambda list
+ CloudFunctionConfiguration -- so a config could be stored and delivered yet
+ come back empty to every SDK."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-s3-notif-{uid}"
+ bucket = f"cfn-s3-notif-{uid}"
+ fn_name = f"cfn-s3-notif-{uid}"
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", "def handler(event, context):\n return {}\n")
+ lam.create_function(
+ FunctionName=fn_name, Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/test-role", Handler="index.handler",
+ Code={"ZipFile": buf.getvalue()},
+ )
+ template = json.dumps({"Resources": {
+ "Permission": {"Type": "AWS::Lambda::Permission", "Properties": {
+ "FunctionName": fn_name, "Action": "lambda:InvokeFunction",
+ "Principal": "s3.amazonaws.com",
+ "SourceAccount": {"Ref": "AWS::AccountId"}}},
+ "Bucket": {"Type": "AWS::S3::Bucket", "Properties": {
+ "BucketName": bucket,
+ "NotificationConfiguration": {"LambdaConfigurations": [{
+ "Function": {"Fn::Sub":
+ "arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:"
+ f"function:{fn_name}"},
+ "Event": "s3:ObjectCreated:*",
+ "Filter": {"S3Key": {"Rules": [{"Name": "prefix", "Value": "in/"}]}},
+ }]}}},
+ }})
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ configs = s3.get_bucket_notification_configuration(
+ Bucket=bucket)["LambdaFunctionConfigurations"]
+ assert len(configs) == 1, configs
+ assert configs[0]["LambdaFunctionArn"].endswith(f"function:{fn_name}")
+ assert configs[0]["Events"] == ["s3:ObjectCreated:*"]
+ assert configs[0]["Id"]
+ assert configs[0]["Filter"]["Key"]["FilterRules"] == [
+ {"Name": "prefix", "Value": "in/"}]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ try:
+ lam.delete_function(FunctionName=fn_name)
+ except ClientError:
+ pass
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index f475f294..0f556f31 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -8419,3 +8419,45 @@ def test_cognito_presignup_trigger_fires_on_plain_signup(cognito_idp, lam):
cognito_idp.delete_user_pool(UserPoolId=pid)
lam.delete_function(FunctionName=fname)
+
+
+def test_cognito_discovery_document_is_self_consistent_at_the_issuer_host():
+ """OIDC discovery requires the document's issuer to equal the URL it was
+ fetched from. Routing the AWS hostname to MiniStack satisfies that, and
+ behind a TLS terminator every URL has to be https or it disagrees with the
+ https issuer."""
+ import json as _json
+ import urllib.request
+
+ from conftest import make_client
+ cognito = make_client("cognito-idp")
+ pool_id = cognito.create_user_pool(PoolName="oidc-consistent")["UserPool"]["Id"]
+ aws_host = "cognito-idp.us-east-1.amazonaws.com"
+ endpoints = ("jwks_uri", "authorization_endpoint", "token_endpoint",
+ "userinfo_endpoint", "end_session_endpoint")
+
+ def fetch(host, forwarded_proto=None):
+ req = urllib.request.Request(
+ f"{ENDPOINT}/{pool_id}/.well-known/openid-configuration")
+ req.add_header("Host", host)
+ if forwarded_proto:
+ req.add_header("X-Forwarded-Proto", forwarded_proto)
+ with urllib.request.urlopen(req) as r:
+ return _json.loads(r.read())
+
+ # The issuer keeps the AWS form, so it still matches the JWT iss claim.
+ plain = fetch(aws_host)
+ assert plain["issuer"] == f"https://{aws_host}/{pool_id}"
+ assert all(plain[name].startswith(f"http://{aws_host}") for name in endpoints)
+
+ secured = fetch(aws_host, "https")
+ origin = f"https://{aws_host}"
+ assert secured["issuer"] == f"{origin}/{pool_id}"
+ for name in endpoints:
+ assert secured[name].startswith(origin), name
+
+ # The keys are really served at that host, so discovery can follow jwks_uri.
+ keys = urllib.request.Request(f"{ENDPOINT}/{pool_id}/.well-known/jwks.json")
+ keys.add_header("Host", aws_host)
+ with urllib.request.urlopen(keys) as r:
+ assert "keys" in _json.loads(r.read())
diff --git a/tests/test_health.py b/tests/test_health.py
index ab65145b..6576beac 100644
--- a/tests/test_health.py
+++ b/tests/test_health.py
@@ -1,7 +1,6 @@
import json
import os
-
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 0bf8ffff..78c3003b 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -30,6 +30,7 @@ from ministack.core.iam_evaluator import (
evaluate_trust_policy,
find_iam_access_key_account,
fnmatch_iam,
+ fnmatch_iam_cs,
parse_policy_document,
resolve_credential,
resolve_principal,
@@ -37,7 +38,8 @@ from ministack.core.iam_evaluator import (
)
# ---------------------------------------------------------------------------
-# Wildcard matching (IAM spec: case-insensitive, * = any, ? = single char)
+# Wildcard matching. Action/NotAction is case-insensitive; Resource/NotResource,
+# StringLike and the Arn operators are case-sensitive.
# ---------------------------------------------------------------------------
class TestFnmatchIam:
@@ -74,6 +76,73 @@ class TestFnmatchIam:
assert not fnmatch_iam("something", "")
+class TestFnmatchIamCaseSensitive:
+ """"In the Resource element, the IAM user name is case sensitive."
+ (reference_policies_elements_resource)"""
+
+ @pytest.mark.parametrize("pattern", ("*", "arn:aws:iam::1:user/Bob", "arn:aws:iam::1:user/B*",
+ "arn:aws:iam::1:user/Bo?"))
+ def test_matching_case_matches(self, pattern):
+ assert fnmatch_iam_cs("arn:aws:iam::1:user/Bob", pattern)
+
+ @pytest.mark.parametrize("pattern", ("arn:aws:iam::1:user/bob", "arn:aws:iam::1:user/BOB",
+ "arn:aws:iam::1:user/b*", "ARN:AWS:IAM::1:USER/Bob"))
+ def test_wrong_case_does_not_match(self, pattern):
+ assert not fnmatch_iam_cs("arn:aws:iam::1:user/Bob", pattern)
+
+ def test_the_two_matchers_disagree_only_on_case(self):
+ value, pattern = "arn:aws:s3:::MyBucket/Key", "arn:aws:s3:::mybucket/*"
+ assert fnmatch_iam(value, pattern)
+ assert not fnmatch_iam_cs(value, pattern)
+
+ def test_action_matching_stays_case_insensitive(self):
+ assert fnmatch_iam("s3:PutObject", "s3:putobject")
+
+
+class TestResourceAndConditionCaseSensitivity:
+ def _decide(self, resource, request_arn="arn:aws:rds-db:us-east-1:1:dbuser:db-X/AppUser",
+ condition=None):
+ stmt = {"Effect": "Allow", "Action": "rds-db:connect", "Resource": resource}
+ if condition:
+ stmt["Condition"] = condition
+ doc = {"Version": "2012-10-17", "Statement": [stmt]}
+ return evaluate(EvalContext(
+ principal_arn="arn:aws:iam::1:user/u", principal_type="user",
+ principal_account="1", action="rds-db:connect",
+ resource_arn=request_arn, region="us-east-1",
+ service_context={"tag": "Prod", "arn": "arn:aws:sns:us-east-1:1:Topic"},
+ ), [parse_policy_document(json.dumps(doc))]).decision
+
+ def test_resource_case_decides_the_outcome(self):
+ assert self._decide("arn:aws:rds-db:us-east-1:1:dbuser:db-X/AppUser") == "Allow"
+ assert self._decide("arn:aws:rds-db:us-east-1:1:dbuser:db-X/appuser") == "ImplicitDeny"
+
+ def test_not_resource_case_decides_the_outcome(self):
+ doc = {"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Action": "rds-db:connect",
+ "NotResource": "arn:aws:rds-db:us-east-1:1:dbuser:db-X/appuser"}]}
+ assert evaluate(EvalContext(
+ principal_arn="arn:aws:iam::1:user/u", principal_type="user",
+ principal_account="1", action="rds-db:connect",
+ resource_arn="arn:aws:rds-db:us-east-1:1:dbuser:db-X/AppUser",
+ region="us-east-1",
+ ), [parse_policy_document(json.dumps(doc))]).decision == "Allow"
+
+ @pytest.mark.parametrize("pattern,expected", (("Prod*", "Allow"), ("prod*", "ImplicitDeny")))
+ def test_string_like_is_case_sensitive(self, pattern, expected):
+ """"Case-sensitive matching" (reference_policies_elements_condition_operators)."""
+ assert self._decide(
+ "*", condition={"StringLike": {"tag": pattern}}) == expected
+
+ @pytest.mark.parametrize("value,expected", (
+ ("arn:aws:sns:us-east-1:1:Topic", "Allow"),
+ ("arn:aws:sns:us-east-1:1:topic", "ImplicitDeny"),
+ ))
+ def test_arn_like_is_case_sensitive(self, value, expected):
+ """"Case-sensitive matching of the ARN" (same page)."""
+ assert self._decide("*", condition={"ArnLike": {"arn": value}}) == expected
+
+
# ---------------------------------------------------------------------------
# Policy parsing
# ---------------------------------------------------------------------------
diff --git a/tests/test_iot.py b/tests/test_iot.py
index 401b9ca1..5f923e5b 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -4009,17 +4009,16 @@ def test_rule_event_replace_of_missing_or_nonstring_is_omitted():
assert event == {}
-def test_rule_event_clientid_resolves_for_mqtt_and_is_omitted_for_http():
+def test_rule_event_clientid_resolves_for_mqtt_and_is_n_a_for_http():
from ministack.services.iot import _rule_event
sql = "SELECT clientid() AS cid, temp FROM 't'"
# MQTT publish: the broker threads the publishing client's id through.
event = _rule_event(sql, "t", b'{"temp": 22}', client_id="sensor-7")
assert event == {"cid": "sensor-7", "temp": 22}
- # HTTP publish: no MQTT client exists — AWS resolves clientid() to
- # Undefined, so the field is omitted from the projection.
+ # HTTP publish: documented as "n/a", so the field is projected, not dropped.
event = _rule_event(sql, "t", b'{"temp": 22}')
- assert event == {"temp": 22}
+ assert event == {"cid": "n/a", "temp": 22}
def test_rule_event_replace_handles_escaped_quotes():
@@ -4068,14 +4067,17 @@ def test_eval_where_clientid_reaches_every_leaf_form():
("isUndefined(clientid())", False),
):
assert _eval_where(pred, "t", raw, message, "sensor-7") is expected
- # An HTTP publish carries no client id, so every one of them fails closed.
+ # An HTTP publish carries no client id, so every comparison fails closed —
+ # clientid() is the literal "n/a" there, which matches none of them.
for pred in (
"clientid() = 'sensor-7'",
"clientid() IN ('sensor-7')",
"clientid() LIKE 'sensor-%'",
):
assert _eval_where(pred, "t", raw, message) is False
- assert _eval_where("isUndefined(clientid())", "t", raw, message) is True
+ # ...but "n/a" is a value, so the function is never Undefined.
+ assert _eval_where("isUndefined(clientid())", "t", raw, message) is False
+ assert _eval_where("clientid() = 'n/a'", "t", raw, message) is True
def test_broker_publish_threads_client_id_into_rule_projection(monkeypatch):
@@ -4112,12 +4114,12 @@ def test_broker_publish_threads_client_id_into_rule_projection(monkeypatch):
PKT_PUBLISH, 0, _encode_string("sensors/door") + b'{"n": 1}'
)
await session.cleanup()
- # ...while the HTTP publish path passes none.
+ # ...while the HTTP publish path passes none, so clientid() is "n/a".
await publish(account_id, "sensors/door", b'{"n": 2}')
try:
asyncio.run(_run())
- assert dispatched == [{"cid": "sensor-7"}, {}]
+ assert dispatched == [{"cid": "sensor-7"}, {"cid": "n/a"}]
finally:
iot_module._topic_rules.clear()
reset()
@@ -4149,15 +4151,15 @@ def test_rule_where_clause_extraction(sql, expected):
@pytest.mark.parametrize(
("pred", "payload", "expected"),
[
- # equality (both spellings) on strings and numbers
+ # equality on strings and numbers. `==` and `!=` are deliberately
+ # absent: AWS refuses both ("Unexpected character '!'", "Unexpected
+ # token, 'EQ'"), captured eu-north-1 2026-09-19.
("state = 'on'", {"state": "on"}, True),
- ("state == 'on'", {"state": "on"}, True),
("state = 'on'", {"state": "off"}, False),
("temp = 22", {"temp": 22}, True),
("temp = 22", {"temp": 23}, False),
- # inequality (both spellings)
+ # inequality
("state <> 'on'", {"state": "off"}, True),
- ("state != 'on'", {"state": "on"}, False),
# a predicate over a missing attribute is Undefined → never matches,
# not even for <> (fail closed, as on AWS)
("absent = 'x'", {"state": "on"}, False),
@@ -4802,6 +4804,45 @@ def test_rule_sns_action_writes_a_full_sns_message_record():
reset()
+def test_iot_jobs_in_progress_timeout_reaches_timed_out():
+ """timeoutConfig.inProgressTimeoutInMinutes: "whenever a job execution
+ remains in the IN_PROGRESS status for longer than this interval, the job
+ execution will fail and switch to the terminal TIMED_OUT status". Evaluated
+ on read, like the broker's session expiry, so no timer runs."""
+ from ministack.core.responses import request_scope
+ from ministack.services import iot as iot_module
+
+ reset()
+ with request_scope("123456789012", _TEST_REGION):
+ iot_module._things["t1"] = {"thingName": "t1"}
+ iot_module._jobs["j1"] = {
+ "jobId": "j1",
+ "targets": ["arn:aws:iot:%s:123456789012:thing/t1" % _TEST_REGION],
+ "targetSelection": "SNAPSHOT", "status": "IN_PROGRESS",
+ "document": "{}", "snapshotted": True,
+ "timeoutConfig": {"inProgressTimeoutInMinutes": 1},
+ }
+ now = iot_module._jobs_now_ms()
+ execution = {
+ "jobId": "j1", "thingName": "t1", "status": "IN_PROGRESS",
+ "statusDetails": {}, "queuedAt": now, "startedAt": now,
+ "lastUpdatedAt": now, "executionNumber": 1, "versionNumber": 2,
+ }
+ iot_module._job_executions[("t1", "j1")] = execution
+
+ # Inside the interval: still running, and the device plane reports the
+ # remaining seconds.
+ assert iot_module._jobs_apply_timeout(dict(execution))["status"] == "IN_PROGRESS"
+ assert iot_module._jobs_seconds_before_timeout(execution) == 60
+
+ # Past it: terminal, and the job completes with it.
+ execution["startedAt"] = now - 61_000
+ assert iot_module._jobs_apply_timeout(execution)["status"] == "TIMED_OUT"
+ assert iot_module._jobs["j1"]["status"] == "COMPLETED"
+ assert iot_module._jobs_seconds_before_timeout(execution) is None
+ reset()
+
+
def test_rule_error_action_runs_when_an_action_fails(monkeypatch):
"""AWS invokes the rule's errorAction when an action fails, with the failure
document — without it the only trace of a broken pipeline is a local log
@@ -4843,9 +4884,13 @@ def test_rule_error_action_runs_when_an_action_fails(monkeypatch):
doc = received[0]
assert doc["ruleName"] == "err_rule"
assert doc["topic"] == "err/topic"
+ # AWS reports the publisher's IP (captured eu-north-1 2026-09-19).
+ assert doc["sourceIp"] == "127.0.0.1"
+ assert doc["clientId"] == "N/A"
assert base64.b64decode(doc["base64OriginalPayload"]) == b'{"n": 1}'
assert doc["failures"] == [
- {"action": "dynamoDBv2", "errorMessage": "RuntimeError: dispatch blew up"}
+ {"failedAction": "DynamoDBv2Action", "failedResource": "absent",
+ "errorMessage": "RuntimeError: dispatch blew up"}
]
finally:
iot_module._topic_rules.clear()
@@ -4911,7 +4956,7 @@ def test_rule_error_action_runs_on_an_undeliverable_destination(
assert base64.b64decode(doc["base64OriginalPayload"]) == b'{"n": 1}'
assert len(doc["failures"]) == 1
failure = doc["failures"][0]
- assert failure["action"] == action_type
+ assert failure["failedAction"] == iot_module._rule_action_name(action_type)
assert error_fragment in failure["errorMessage"]
finally:
iot_module._topic_rules.clear()
diff --git a/tests/test_iot_data.py b/tests/test_iot_data.py
index 1e9b41f3..078ab48c 100644
--- a/tests/test_iot_data.py
+++ b/tests/test_iot_data.py
@@ -26,12 +26,12 @@ import urllib.request
import uuid
import zipfile as _zipfile
from urllib.parse import quote, urlparse
-from conftest import patch_endpoint_dns
import boto3
import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
+from conftest import patch_endpoint_dns
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
@@ -1527,7 +1527,7 @@ def test_iot_rule_sqs_action_missing_queue_does_not_stop_the_rule(
doc = json.loads(_poll_body(sqs, dlq))
assert doc["ruleName"] == rule
assert doc["topic"] == "sensors/a1/telemetry"
- assert [f["action"] for f in doc["failures"]] == ["sqs"]
+ assert [f["failedAction"] for f in doc["failures"]] == ["SqsAction"]
assert "QueueDoesNotExist" in doc["failures"][0]["errorMessage"]
iot_client.delete_topic_rule(ruleName=rule)
@@ -3054,7 +3054,9 @@ def _spawn(env_extra: dict, port: int, log_path=None) -> subprocess.Popen:
sink.close()
-def _wait_health(url: str, timeout: float = 30.0) -> None:
+def _wait_ready(url: str, timeout: float = 30.0) -> None:
+ """Poll until 200. /_ministack/ready answers 503 while the mTLS listener is
+ still binding, so this covers the MQTT port too."""
deadline = time.time() + timeout
last = None
while time.time() < deadline:
@@ -3119,7 +3121,7 @@ def broker(tmp_path_factory):
{"IOT_MTLS_ENABLED": "1", "IOT_MTLS_PORT": str(mqtt_port)}, http_port, log_path=log_path
)
try:
- _wait_health(f"http://127.0.0.1:{http_port}/_ministack/health")
+ _wait_ready(f"http://127.0.0.1:{http_port}/_ministack/ready")
yield _Broker(http_port, mqtt_port, log_path)
finally:
_terminate(proc)
@@ -3299,7 +3301,7 @@ def test_mtls_on_by_default(tmp_path):
http_port = _free_port()
proc = _spawn({"LOG_LEVEL": "INFO", "IOT_MTLS_ENABLED": None}, http_port, log_path=log)
try:
- _wait_health(f"http://127.0.0.1:{http_port}/_ministack/health")
+ _wait_ready(f"http://127.0.0.1:{http_port}/_ministack/ready")
text = log.read_text(errors="replace")
listening = "MQTT listening on port 8883" in text
degraded = "failed to bind port 8883" in text
@@ -3319,7 +3321,7 @@ def test_mtls_disabled_by_env(tmp_path):
http_port = _free_port()
proc = _spawn({"LOG_LEVEL": "DEBUG"}, http_port, log_path=log)
try:
- _wait_health(f"http://127.0.0.1:{http_port}/_ministack/health")
+ _wait_ready(f"http://127.0.0.1:{http_port}/_ministack/ready")
text = log.read_text(errors="replace")
assert "skipping iot module import" in text, f"no opt-out line in the log:\n{text}"
assert "MQTT listening on port" not in text
@@ -3781,7 +3783,7 @@ def test_mtls_shutdown_completes_with_a_device_connected(tmp_path):
proc = _spawn({"IOT_MTLS_ENABLED": "1", "IOT_MTLS_PORT": str(mqtt_port)}, http_port)
peer = None
try:
- _wait_health(f"http://127.0.0.1:{http_port}/_ministack/health")
+ _wait_ready(f"http://127.0.0.1:{http_port}/_ministack/ready")
private = _Broker(http_port, mqtt_port)
_cert_id, cert_pem, key_pem = _new_cert(private)
peer = _Peer(_mtls_connect(private, cert_pem, key_pem, tmp_path))
diff --git a/tests/test_iot_jobs.py b/tests/test_iot_jobs.py
index 411325dd..8f4f6156 100644
--- a/tests/test_iot_jobs.py
+++ b/tests/test_iot_jobs.py
@@ -308,7 +308,8 @@ def test_iot_jobs_update_rejects_service_side_statuses(
):
"""A device may only report IN_PROGRESS / SUCCEEDED / FAILED / REJECTED;
the service-side statuses (CANCELED, TIMED_OUT, REMOVED) must be rejected
- with InvalidRequestException (400), as on AWS."""
+ with InvalidStateTransitionException (409) and the message "The status of job
+ execution cannot be changed to be X" — captured eu-north-1 2026-09-19."""
thing = _unique("jobs-thing")
job_id = _unique("job")
try:
@@ -321,10 +322,11 @@ def test_iot_jobs_update_rejects_service_side_statuses(
jobId=job_id, thingName=thing, status=status
)
error = ei.value.response["Error"]
- assert error["Code"] == "InvalidRequestException", status
+ assert error["Code"] == "InvalidStateTransitionException", status
assert (
- ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409
), status
+ assert f"cannot be changed to be {status}" in error["Message"], status
# The rejected updates must not have touched the execution.
execution = iot_jobs_data.describe_job_execution(
@@ -447,6 +449,38 @@ def test_iot_jobs_fleet_completes_only_when_every_execution_is_terminal(
# ---------------------------------------------------------------------------
+def test_iot_jobs_update_rejects_a_mismatched_execution_number(
+ iot_client, iot_jobs_data
+):
+ """UpdateJobExecution's executionNumber identifies one execution on the
+ device. Nothing re-queues here, so only number 1 exists and any other
+ number is ResourceNotFoundException, as the describe path already answers."""
+ thing = _unique("jobs-thing")
+ job_id = _unique("job")
+ try:
+ thing_arn = _create_thing(iot_client, thing)
+ iot_client.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT)
+
+ with pytest.raises(ClientError) as ei:
+ iot_jobs_data.update_job_execution(
+ jobId=job_id, thingName=thing, status="IN_PROGRESS",
+ executionNumber=7,
+ )
+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+ # Number 1 is the one that exists.
+ iot_jobs_data.update_job_execution(
+ jobId=job_id, thingName=thing, status="IN_PROGRESS", executionNumber=1,
+ )
+ finally:
+ _cleanup(iot_client, jobs=[job_id], things=[thing])
+
+
+def test_iot_jobs_describe_job_steady_state_shape(iot_client):
+ """Captured eu-north-1 2026-09-19 across QUEUED, IN_PROGRESS and SUCCEEDED
+ executions: isConcurrent is false throughout, processingTargets is null
+ throughout, and timeoutConfig/schedulingConfig come back as {} while
+ abortConfig is omitted."""
def test_iot_jobs_endpoint_host_reaches_the_data_plane(iot_client):
"""A request carrying the jobs endpoint Host `{prefix}.jobs.iot.{region}`
must land on the jobs data plane. Routed to the `iot` control plane
@@ -457,7 +491,44 @@ def test_iot_jobs_endpoint_host_reaches_the_data_plane(iot_client):
try:
thing_arn = _create_thing(iot_client, thing)
iot_client.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT)
+ job = iot_client.describe_job(jobId=job_id)["job"]
+ assert job["isConcurrent"] is False
+ assert "processingTargets" not in job["jobProcessDetails"]
+ assert job["timeoutConfig"] == {}
+ assert job["schedulingConfig"] == {}
+ assert "abortConfig" not in job
+ finally:
+ _cleanup(iot_client, jobs=[job_id], things=[thing])
+
+def test_iot_jobs_endpoint_type_is_retired(iot_client):
+ """AWS retired `iot:Jobs`: DescribeEndpoint answers InvalidRequestException
+ and points at iot:Data-ATS (captured eu-north-1 2026-09-19). Jobs and
+ Commands are served from the Data-ATS endpoint, where the `iot-jobs-data`
+ signing scope selects the data plane."""
+ with pytest.raises(ClientError) as exc:
+ iot_client.describe_endpoint(endpointType="iot:Jobs")
+ assert exc.value.response["Error"]["Code"] == "InvalidRequestException"
+ assert "iot:Data-ATS" in exc.value.response["Error"]["Message"]
+
+
+def test_iot_jobs_data_plane_reachable_on_the_data_ats_endpoint(
+ iot_client, iot_jobs_data
+):
+ """The replacement flow: the Data-ATS endpoint serves the jobs data plane.
+ A request signed with the `iot-jobs-data` scope must answer the
+ GetPendingJobExecutions envelope, not the control plane's
+ `executionSummaries`."""
+ thing = _unique("jobs-thing")
+ job_id = _unique("job")
+ try:
+ thing_arn = _create_thing(iot_client, thing)
+ iot_client.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT)
+
+ endpoint = iot_client.describe_endpoint(endpointType="iot:Data-ATS")[
+ "endpointAddress"
+ ]
+ assert ".jobs.iot." not in endpoint
endpoint = "a1b2c3.jobs.iot.us-east-1.localhost"
request = urllib.request.Request(
f"{ENDPOINT}/things/{quote(thing)}/jobs",
@@ -467,7 +538,7 @@ def test_iot_jobs_endpoint_host_reaches_the_data_plane(iot_client):
with urllib.request.urlopen(request, timeout=5) as resp:
body = json.loads(resp.read())
- # The GetPendingJobExecutions envelope — not `executionSummaries`.
+ body = iot_jobs_data.get_pending_job_executions(thingName=thing)
assert [q["jobId"] for q in body["queuedJobs"]] == [job_id]
assert body["inProgressJobs"] == []
finally:
diff --git a/tests/test_kms.py b/tests/test_kms.py
index 0fd36954..51408aa7 100644
--- a/tests/test_kms.py
+++ b/tests/test_kms.py
@@ -1,4 +1,5 @@
import base64
+import datetime as _dt
import json
import os
import time
@@ -2128,3 +2129,184 @@ def test_kms_primary_with_replicas_waits_on_deletion():
west.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)
assert east.describe_key(KeyId=key_id)["KeyMetadata"]["KeyState"] == "PendingDeletion"
+
+
+# ---------------------------------------------------------------------------
+# Imported key material (BYOK): Origin EXTERNAL, GetParametersForImport,
+# ImportKeyMaterial, DeleteImportedKeyMaterial.
+# ---------------------------------------------------------------------------
+
+_BYOK_MATERIAL = bytes(range(32))
+_NO_EXPIRY = "KEY_MATERIAL_DOES_NOT_EXPIRE"
+
+
+def _wrap_material(public_key_der, algorithm, material=_BYOK_MATERIAL):
+ """Wrap key material the way a caller does, per WrappingAlgorithm."""
+ keywrap = pytest.importorskip("cryptography.hazmat.primitives.keywrap")
+ from cryptography.hazmat.primitives import hashes, serialization
+ from cryptography.hazmat.primitives.asymmetric import padding
+
+ public_key = serialization.load_der_public_key(public_key_der)
+ if algorithm == "RSAES_PKCS1_V1_5":
+ return public_key.encrypt(material, padding.PKCS1v15())
+ digest = hashes.SHA1() if algorithm.endswith("SHA_1") else hashes.SHA256()
+ oaep = padding.OAEP(mgf=padding.MGF1(algorithm=digest), algorithm=digest, label=None)
+ if algorithm.startswith("RSAES_OAEP"):
+ return public_key.encrypt(material, oaep)
+ ephemeral = os.urandom(32)
+ return (public_key.encrypt(ephemeral, oaep)
+ + keywrap.aes_key_wrap_with_padding(ephemeral, material))
+
+
+def _import_external_key(kms, algorithm="RSAES_OAEP_SHA_256", material=_BYOK_MATERIAL,
+ expiration=_NO_EXPIRY, valid_to=None):
+ key_id = kms.create_key(Origin="EXTERNAL")["KeyMetadata"]["KeyId"]
+ params = kms.get_parameters_for_import(
+ KeyId=key_id, WrappingAlgorithm=algorithm, WrappingKeySpec="RSA_2048")
+ kwargs = {"ExpirationModel": expiration}
+ if valid_to is not None:
+ kwargs["ValidTo"] = valid_to
+ kms.import_key_material(
+ KeyId=key_id, ImportToken=params["ImportToken"],
+ EncryptedKeyMaterial=_wrap_material(params["PublicKey"], algorithm, material),
+ **kwargs)
+ return key_id, params
+
+
+def test_kms_external_key_starts_pending_import_and_refuses_use():
+ """An EXTERNAL key has no material until it is imported, so it starts
+ PendingImport and every cryptographic operation is refused."""
+ pytest.importorskip("cryptography")
+ kms = _regional_kms("us-east-1")
+ metadata = kms.create_key(Origin="EXTERNAL")["KeyMetadata"]
+ assert metadata["Origin"] == "EXTERNAL"
+ assert metadata["KeyState"] == "PendingImport"
+ assert metadata["Enabled"] is False
+ with pytest.raises(ClientError) as exc:
+ kms.encrypt(KeyId=metadata["KeyId"], Plaintext=b"x")
+ assert exc.value.response["Error"]["Code"] == "KMSInvalidStateException"
+
+
[email protected]("algorithm", [
+ "RSAES_PKCS1_V1_5", "RSAES_OAEP_SHA_1", "RSAES_OAEP_SHA_256",
+ "RSA_AES_KEY_WRAP_SHA_1", "RSA_AES_KEY_WRAP_SHA_256",
+])
+def test_kms_import_key_material_every_wrapping_algorithm(algorithm):
+ """Each WrappingAlgorithm in the enum unwraps, and the key then encrypts
+ and decrypts with the caller's own material."""
+ pytest.importorskip("cryptography")
+ kms = _regional_kms("us-east-1")
+ key_id, params = _import_external_key(kms, algorithm)
+ assert params["KeyId"].endswith(key_id)
+ assert params["ParametersValidTo"]
+ metadata = kms.describe_key(KeyId=key_id)["KeyMetadata"]
+ assert metadata["KeyState"] == "Enabled"
+ assert metadata["Enabled"] is True
+ assert metadata["ExpirationModel"] == _NO_EXPIRY
+ assert "ValidTo" not in metadata
+ ciphertext = kms.encrypt(KeyId=key_id, Plaintext=b"hello byok")["CiphertextBlob"]
+ assert kms.decrypt(CiphertextBlob=ciphertext)["Plaintext"] == b"hello byok"
+
+
+def test_kms_imported_material_is_the_callers_own_bytes():
+ """The point of BYOK: two keys given the same material are interchangeable,
+ so a fixture can pin the key bytes a test depends on."""
+ pytest.importorskip("cryptography")
+ kms = _regional_kms("us-east-1")
+ first, _ = _import_external_key(kms)
+ second, _ = _import_external_key(kms)
+ ciphertext = kms.encrypt(KeyId=first, Plaintext=b"same material")["CiphertextBlob"]
+ assert kms.decrypt(CiphertextBlob=ciphertext, KeyId=second)["Plaintext"] \
+ == b"same material"
+
+
+def test_kms_import_expiring_material_reports_valid_to():
+ pytest.importorskip("cryptography")
+ kms = _regional_kms("us-east-1")
+ valid_to = _dt.datetime(2030, 1, 1, tzinfo=_dt.timezone.utc)
+ key_id, _ = _import_external_key(
+ kms, expiration="KEY_MATERIAL_EXPIRES", valid_to=valid_to)
+ metadata = kms.describe_key(KeyId=key_id)["KeyMetadata"]
+ assert metadata["ExpirationModel"] == "KEY_MATERIAL_EXPIRES"
+ assert metadata["ValidTo"] == valid_to
+
+
+def test_kms_delete_imported_key_material_returns_the_key_to_pending_import():
+ pytest.importorskip("cryptography")
+ kms = _regional_kms("us-east-1")
+ key_id, _ = _import_external_key(kms)
+ kms.delete_imported_key_material(KeyId=key_id)
+ metadata = kms.describe_key(KeyId=key_id)["KeyMetadata"]
+ assert metadata["KeyState"] == "PendingImport"
+ assert metadata["Enabled"] is False
+ assert "ValidTo" not in metadata
+ with pytest.raises(ClientError) as exc:
+ kms.encrypt(KeyId=key_id, Plaintext=b"x")
+ assert exc.value.response["Error"]["Code"] == "KMSInvalidStateException"
+
+
+def test_kms_import_rejects_a_bad_token_wrong_material_and_reuse():
+ pytest.importorskip("cryptography")
+ kms = _regional_kms("us-east-1")
+ key_id = kms.create_key(Origin="EXTERNAL")["KeyMetadata"]["KeyId"]
+ params = kms.get_parameters_for_import(
+ KeyId=key_id, WrappingAlgorithm="RSAES_OAEP_SHA_256",
+ WrappingKeySpec="RSA_2048")
+ wrapped = _wrap_material(params["PublicKey"], "RSAES_OAEP_SHA_256")
+
+ def fails_with(code, **kwargs):
+ with pytest.raises(ClientError) as exc:
+ kms.import_key_material(KeyId=key_id, ExpirationModel=_NO_EXPIRY, **kwargs)
+ assert exc.value.response["Error"]["Code"] == code
+
+ fails_with("InvalidImportTokenException",
+ ImportToken=b"nope", EncryptedKeyMaterial=wrapped)
+ fails_with("InvalidCiphertextException",
+ ImportToken=params["ImportToken"], EncryptedKeyMaterial=b"x" * 256)
+ fails_with("IncorrectKeyMaterialException",
+ ImportToken=params["ImportToken"],
+ EncryptedKeyMaterial=_wrap_material(
+ params["PublicKey"], "RSAES_OAEP_SHA_256", b"tooshort"))
+ # ValidTo is required when the material expires.
+ with pytest.raises(ClientError) as exc:
+ kms.import_key_material(
+ KeyId=key_id, ImportToken=params["ImportToken"],
+ EncryptedKeyMaterial=wrapped, ExpirationModel="KEY_MATERIAL_EXPIRES")
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+
+ kms.import_key_material(
+ KeyId=key_id, ImportToken=params["ImportToken"],
+ EncryptedKeyMaterial=wrapped, ExpirationModel=_NO_EXPIRY)
+ # The token is single-use.
+ fails_with("InvalidImportTokenException",
+ ImportToken=params["ImportToken"], EncryptedKeyMaterial=wrapped)
+
+
+def test_kms_import_flow_refuses_a_non_external_key():
+ """GetParametersForImport, ImportKeyMaterial and DeleteImportedKeyMaterial
+ all require Origin EXTERNAL."""
+ pytest.importorskip("cryptography")
+ kms = _regional_kms("us-east-1")
+ key_id = kms.create_key()["KeyMetadata"]["KeyId"]
+ with pytest.raises(ClientError) as exc:
+ kms.get_parameters_for_import(
+ KeyId=key_id, WrappingAlgorithm="RSAES_OAEP_SHA_256",
+ WrappingKeySpec="RSA_2048")
+ assert exc.value.response["Error"]["Code"] == "UnsupportedOperationException"
+ with pytest.raises(ClientError) as exc:
+ kms.delete_imported_key_material(KeyId=key_id)
+ assert exc.value.response["Error"]["Code"] == "UnsupportedOperationException"
+
+
+def test_kms_external_origin_is_symmetric_only_and_specs_are_validated():
+ pytest.importorskip("cryptography")
+ kms = _regional_kms("us-east-1")
+ with pytest.raises(ClientError) as exc:
+ kms.create_key(Origin="EXTERNAL", KeySpec="RSA_2048")
+ assert exc.value.response["Error"]["Code"] == "UnsupportedOperationException"
+ key_id = kms.create_key(Origin="EXTERNAL")["KeyMetadata"]["KeyId"]
+ with pytest.raises(ClientError) as exc:
+ kms.get_parameters_for_import(
+ KeyId=key_id, WrappingAlgorithm="RSAES_OAEP_SHA_256",
+ WrappingKeySpec="SM2")
+ assert exc.value.response["Error"]["Code"] == "UnsupportedOperationException"
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 211b545e..a7358a9f 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -25,6 +25,7 @@ from conftest import (
LoopProbe,
concurrent_burst,
make_probe_lambda,
+ patch_endpoint_dns,
)
_endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
@@ -1704,8 +1705,11 @@ def test_lambda_warm_start(lam, apigw):
req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
return _urlreq.urlopen(req).read().decode()
- t1 = call() # cold start — spawns worker, imports module
- t2 = call() # warm — reuses worker, same module state
+ # The generated execute-api subdomain is not in DNS; only the literal
+ # endpoint host is. patch_endpoint_dns maps *.{host} onto it.
+ with patch_endpoint_dns():
+ t1 = call() # cold start — spawns worker, imports module
+ t2 = call() # warm — reuses worker, same module state
assert t1 == t2, f"Warm worker should reuse module state: {t1} != {t2}"
apigw.delete_api(ApiId=api_id)
@@ -4130,7 +4134,8 @@ def test_apigwv2_nodejs_lambda_proxy(lam, apigw):
method="GET",
)
req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
- resp = _urlreq.urlopen(req).read().decode()
+ with patch_endpoint_dns():
+ resp = _urlreq.urlopen(req).read().decode()
body = json.loads(resp)
assert body.get("route") == "GET /test", f"Expected handler result, got: {resp}"
@@ -4782,7 +4787,14 @@ _DENIED = "AccessDeniedException"
pytest.param("granted-elsewhere", "111111111111", None, _DENIED, _DENIED, id="grant-to-another-account"),
pytest.param("partly-seeded", "*", _foreign_arn("partly-seeded", 35), _DENIED, _DENIED,
id="missing-version-of-known-layer"),
- pytest.param(None, None, _AWS_MANAGED_LAYER, _DENIED, _DENIED, id="unknown-foreign-layer"),
+ # A name AWS does not publish, under the same account: the gate is the layer
+ # NAME, so this is still denied.
+ pytest.param(None, None, _foreign_arn("not-an-aws-extension", 38), _DENIED, _DENIED,
+ id="unknown-foreign-layer"),
+ # An extension AWS publishes itself carries a public grant on AWS, so a
+ # template referencing it deploys there. It resolves here too; the bytes are
+ # not available offline, so CodeSize is 0 and the extension does not run.
+ pytest.param(None, None, _AWS_MANAGED_LAYER, None, None, id="aws-published-extension"),
pytest.param(None, None, _OTHER_REGION_LAYER, _DENIED, _DENIED, id="another-region"),
pytest.param(None, None, _foreign_arn("nope-not-here", 1, _CALLER_ACCOUNT),
"InvalidParameterValueException", "ResourceNotFoundException", id="own-account-layer-missing"),
@@ -4803,7 +4815,8 @@ def test_lambda_cross_account_layer_verdicts(layer_name, granted_to, arn, attach
if attach_error is None:
assert version_config["Content"]["CodeSize"] == (_FOREIGN_CODE_SIZE if layer_name else 0)
if read_error is None:
- assert (payload["LayerVersionArn"], payload["Content"]["CodeSize"]) == (arn, _FOREIGN_CODE_SIZE)
+ expected_size = _FOREIGN_CODE_SIZE if layer_name else 0
+ assert (payload["LayerVersionArn"], payload["Content"]["CodeSize"]) == (arn, expected_size)
assert not [key for key in payload if key.startswith("_")]
diff --git a/tests/test_rds.py b/tests/test_rds.py
index 43cdea83..2172dca7 100644
--- a/tests/test_rds.py
+++ b/tests/test_rds.py
@@ -15771,3 +15771,100 @@ def test_rds_cluster_reader_alias_skipped_under_pg_replication(monkeypatch):
assert rds_service._cluster_endpoint_aliases(
{"Endpoint": name, "Engine": "aurora-mysql"}) == [
name, "mydb.cluster-ro-abc123.us-east-2.rds.amazonaws.com"]
+
+
+def _rds_ca_pem(tmp_path):
+ """The CA that signs DB server certificates, written where libpq can read it."""
+ import urllib.request
+ path = tmp_path / "ministack-rds-ca.pem"
+ with urllib.request.urlopen(f"{ENDPOINT}/_ministack/rds/ca.pem", timeout=10) as response:
+ assert response.status == 200
+ path.write_bytes(response.read())
+ return str(path)
+
+
[email protected]("engine", ("postgres", "aurora-postgresql"))
+def test_rds_postgres_serves_verified_tls(rds, tmp_path, engine):
+ """AWS installs the DB server certificate itself and every instance we
+ report carries CACertificateIdentifier, so TLS is on without asking: a
+ client using our CA connects, and plaintext still works as it does on AWS
+ without rds.force_ssl."""
+ psycopg2 = pytest.importorskip("psycopg2")
+ db_id = f"tls-{engine.split('-')[-1]}-{_uuid_mod.uuid4().hex[:8]}"
+ cluster_id = f"{db_id}-c"
+ try:
+ if engine == "aurora-postgresql":
+ rds.create_db_cluster(
+ DBClusterIdentifier=cluster_id, Engine=engine,
+ MasterUsername="admin", MasterUserPassword="password",
+ DatabaseName="appdb",
+ )
+ rds.create_db_instance(
+ DBInstanceIdentifier=db_id, DBClusterIdentifier=cluster_id,
+ DBInstanceClass="db.r6g.large", Engine=engine,
+ )
+ else:
+ rds.create_db_instance(
+ DBInstanceIdentifier=db_id, DBInstanceClass="db.t3.micro",
+ Engine=engine, MasterUsername="admin",
+ MasterUserPassword="password", DBName="appdb",
+ AllocatedStorage=20,
+ )
+ endpoint = None
+ for _ in range(90):
+ detail = rds.describe_db_instances(DBInstanceIdentifier=db_id)["DBInstances"][0]
+ if detail["DBInstanceStatus"] == "available" and detail.get("Endpoint"):
+ endpoint = detail["Endpoint"]
+ break
+ time.sleep(2)
+ if endpoint is None:
+ pytest.skip("no backing container available in this environment")
+ assert detail["CACertificateIdentifier"] == "rds-ca-rsa2048-g1"
+
+ ca = _rds_ca_pem(tmp_path)
+
+ def connect(sslmode):
+ connection = psycopg2.connect(
+ host=endpoint["Address"], port=endpoint["Port"], user="admin",
+ password="password", dbname="appdb", sslmode=sslmode,
+ sslrootcert=ca, connect_timeout=15,
+ )
+ try:
+ cursor = connection.cursor()
+ cursor.execute(
+ "SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()")
+ return cursor.fetchone()[0]
+ finally:
+ connection.close()
+
+ # verify-full also pins the hostname, so the SAN has to cover the
+ # endpoint the API advertises.
+ for sslmode in ("require", "verify-ca", "verify-full"):
+ assert connect(sslmode) is True, sslmode
+ assert connect("disable") is False
+ finally:
+ try:
+ rds.delete_db_instance(DBInstanceIdentifier=db_id, SkipFinalSnapshot=True)
+ except ClientError:
+ pass
+ if engine == "aurora-postgresql":
+ try:
+ rds.delete_db_cluster(DBClusterIdentifier=cluster_id, SkipFinalSnapshot=True)
+ except ClientError:
+ pass
+
+
+def test_rds_ca_endpoint_serves_one_stable_ca(tmp_path):
+ """The CA is minted once and served as PEM, the local stand-in for AWS's
+ certificate bundle."""
+ pytest.importorskip("cryptography")
+ from cryptography import x509
+
+ again = tmp_path / "again"
+ again.mkdir()
+ first = open(_rds_ca_pem(tmp_path), "rb").read()
+ second = open(_rds_ca_pem(again), "rb").read()
+ assert first == second, "the CA must not be re-minted per request"
+ cert = x509.load_pem_x509_certificate(first)
+ assert cert.issuer == cert.subject
+ assert "Ministack RDS Root CA" in cert.subject.rfc4514_string()
diff --git a/tests/test_rds_data.py b/tests/test_rds_data.py
index d7e158c4..ca6ff142 100644
--- a/tests/test_rds_data.py
+++ b/tests/test_rds_data.py
@@ -11,6 +11,8 @@ import json
import os
import urllib.request
import uuid
+from types import SimpleNamespace
+from unittest.mock import Mock
import boto3
import pytest
@@ -1465,3 +1467,98 @@ def test_rds_data_stub_state_is_region_isolated():
rd._stub_databases.pop("iso-cluster", None)
set_request_account_id(original_account)
set_request_region(original_region)
+
+
+# ---------------------------------------------------------------------------
+# numberOfRecordsUpdated: PostgreSQL reports returned rows in cursor.rowcount
+# for SELECT, so the command tag decides. Measured on PostgreSQL 16:
+# "SELECT 3" for a 3-row select, "INSERT 0 1" even with RETURNING.
+# ---------------------------------------------------------------------------
+
+_PG_ENGINES = ("postgres", "aurora-postgresql")
+_MYSQL_ENGINES = ("mysql", "aurora-mysql", "mariadb")
+
+
+def _execute_with_cursor(monkeypatch, engine, rowcount, status=None, rows=None,
+ sql="SELECT 1", with_status=True):
+ """Run _execute_statement against a stubbed driver cursor."""
+ from ministack.services import rds_data
+
+ cursor = SimpleNamespace(
+ rowcount=rowcount,
+ description=([("value", 23, None, None, None, None, None)]
+ if rows is not None else None),
+ execute=Mock(), fetchall=Mock(return_value=rows), close=Mock(),
+ )
+ if with_status:
+ cursor.statusmessage = status
+ connection = Mock()
+ connection.cursor.return_value = cursor
+
+ monkeypatch.setattr(rds_data, "_resolve_target",
+ lambda _arn: ({"DBInstanceIdentifier": "unit"}, engine, {}))
+ monkeypatch.setattr(rds_data, "_validate_http_endpoint_enabled", lambda *_a, **_k: None)
+ monkeypatch.setattr(rds_data, "_require_secret_credentials",
+ lambda _arn: ("user", "password", None))
+ monkeypatch.setattr(rds_data, "_has_real_endpoint", lambda *_a, **_k: True)
+ monkeypatch.setattr(rds_data, "_connect", lambda *_a, **_k: connection)
+
+ status_code, _headers, body = rds_data._execute_statement({
+ "resourceArn": "resource", "secretArn": "secret", "sql": sql,
+ "includeResultMetadata": True,
+ })
+ assert status_code == 200, body
+ cursor.execute.assert_called_once_with(sql, None)
+ cursor.close.assert_called_once()
+ connection.close.assert_called_once()
+ return json.loads(body)
+
+
[email protected]("engine", _PG_ENGINES)
[email protected]("rows", ([], [(1,)], [(1,), (2,)]), ids=("none", "one", "two"))
+def test_rds_data_pg_select_reports_no_updated_records(monkeypatch, engine, rows):
+ """A SELECT updates nothing, whatever psycopg2 puts in rowcount."""
+ result = _execute_with_cursor(
+ monkeypatch, engine, len(rows), f"SELECT {len(rows)}", rows,
+ sql="/* comment */ WITH x AS (SELECT 1) SELECT * FROM x")
+ assert result["numberOfRecordsUpdated"] == 0
+ assert result["records"] == [[{"longValue": row[0]}] for row in rows]
+ assert result["columnMetadata"][0]["name"] == "value"
+
+
[email protected]("command", ("INSERT", "UPDATE", "DELETE"))
[email protected]("count", (0, 2))
[email protected]("returning", (False, True), ids=("plain", "returning"))
+def test_rds_data_pg_dml_keeps_its_count(monkeypatch, command, count, returning):
+ """DML keeps its count, RETURNING included: the tag stays INSERT/UPDATE/DELETE."""
+ rows = [(1,)] * count if returning else None
+ tag = f"INSERT 0 {count}" if command == "INSERT" else f"{command} {count}"
+ result = _execute_with_cursor(monkeypatch, "postgres", count, tag, rows)
+ assert result["numberOfRecordsUpdated"] == count
+ assert len(result["records"]) == (count if returning else 0)
+
+
[email protected]("status", (
+ None, "", " ", 123, b"SELECT 2", "SELECTED 2", "select 2",
+ "CREATE TABLE AS", "FETCH 2",
+))
+def test_rds_data_pg_unrecognised_tag_preserves_the_count(monkeypatch, status):
+ assert _execute_with_cursor(
+ monkeypatch, "postgres", 2, status)["numberOfRecordsUpdated"] == 2
+
+
+def test_rds_data_pg_missing_statusmessage_preserves_the_count(monkeypatch):
+ assert _execute_with_cursor(
+ monkeypatch, "postgres", 2, with_status=False)["numberOfRecordsUpdated"] == 2
+
+
[email protected]("engine", _PG_ENGINES + ("mysql",))
+def test_rds_data_negative_rowcount_is_clamped(monkeypatch, engine):
+ assert _execute_with_cursor(monkeypatch, engine, -1)["numberOfRecordsUpdated"] == 0
+
+
[email protected]("engine", _MYSQL_ENGINES)
+def test_rds_data_mysql_row_counts_are_unchanged(monkeypatch, engine):
+ """pymysql has no statusmessage, so the MySQL path is untouched."""
+ assert _execute_with_cursor(
+ monkeypatch, engine, 2, "SELECT 2", [(1,), (2,)])["numberOfRecordsUpdated"] == 2
diff --git a/tests/test_rds_data_row_counts.py b/tests/test_rds_data_row_counts.py
deleted file mode 100644
index dbb736ab..00000000
--- a/tests/test_rds_data_row_counts.py
+++ /dev/null
@@ -1,76 +0,0 @@
-# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
-"""Pure unit tests; run with unittest to avoid the integration reset fixture."""
-
-import json
-import unittest
-from types import SimpleNamespace
-from unittest.mock import Mock, patch
-
-from ministack.services import rds_data
-
-
-class ExecuteStatementRowCountsTest(unittest.TestCase):
- def execute(self, engine, count, status=None, rows=None, sql="SELECT 1",
- missing_status=False):
- cursor = SimpleNamespace(
- rowcount=count,
- description=[("value", 23, None, None, None, None, None)] if rows is not None else None,
- execute=Mock(), fetchall=Mock(return_value=rows), close=Mock(),
- )
- if not missing_status:
- cursor.statusmessage = status
- conn = Mock()
- conn.cursor.return_value = cursor
- with patch.object(rds_data, "_resolve_target", return_value=({"DBInstanceIdentifier": "unit"}, engine, {})), \
- patch.object(rds_data, "_validate_http_endpoint_enabled", return_value=None), \
- patch.object(rds_data, "_require_secret_credentials", return_value=("user", "password", None)), \
- patch.object(rds_data, "_has_real_endpoint", return_value=True), \
- patch.object(rds_data, "_connect", return_value=conn):
- code, _, body = rds_data._execute_statement({
- "resourceArn": "resource", "secretArn": "secret", "sql": sql,
- "includeResultMetadata": True,
- })
- self.assertEqual(code, 200, body)
- cursor.execute.assert_called_once_with(sql, None)
- cursor.close.assert_called_once()
- conn.close.assert_called_once()
- return json.loads(body)
-
- def test_select(self):
- for engine in ("postgres", "aurora-postgresql"):
- for rows in ([], [(1,)], [(1,), (2,)]):
- with self.subTest(engine=engine, rows=rows):
- result = self.execute(engine, len(rows), f"SELECT {len(rows)}", rows,
- sql="/* comment */ WITH x AS (SELECT 1) SELECT * FROM x")
- self.assertEqual(result["numberOfRecordsUpdated"], 0)
- self.assertEqual(result["records"], [[{"longValue": row[0]}] for row in rows])
- self.assertEqual(result["columnMetadata"][0]["name"], "value")
-
- def test_dml_with_and_without_returning(self):
- for command in ("INSERT", "UPDATE", "DELETE"):
- for count in (0, 2):
- for returning in (False, True):
- with self.subTest(command=command, count=count, returning=returning):
- rows = [(1,)] * count if returning else None
- tag = f"INSERT 0 {count}" if command == "INSERT" else f"{command} {count}"
- result = self.execute("postgres", count, tag, rows)
- self.assertEqual(result["numberOfRecordsUpdated"], count)
- self.assertEqual(len(result["records"]), count if returning else 0)
-
- def test_unknown_missing_and_malformed_tags_preserve_count(self):
- for status in (None, "", " ", 123, b"SELECT 2", "SELECTED 2", "select 2", "CREATE TABLE AS", "FETCH 2"):
- with self.subTest(status=status):
- self.assertEqual(self.execute("postgres", 2, status)["numberOfRecordsUpdated"], 2)
- self.assertEqual(self.execute("postgres", 2, missing_status=True)["numberOfRecordsUpdated"], 2)
-
- def test_negative_rowcount_is_clamped(self):
- for engine in ("postgres", "aurora-postgresql", "mysql"):
- self.assertEqual(self.execute(engine, -1)["numberOfRecordsUpdated"], 0)
-
- def test_mysql_is_unchanged(self):
- for engine in ("mysql", "aurora-mysql", "mariadb"):
- self.assertEqual(self.execute(engine, 2, "SELECT 2", [(1,), (2,)])["numberOfRecordsUpdated"], 2)
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/test_rds_iam.py b/tests/test_rds_iam.py
index 8fdc327c..78b5596c 100644
--- a/tests/test_rds_iam.py
+++ b/tests/test_rds_iam.py
@@ -3,6 +3,7 @@
"""Offline RDS tokens signed by boto3/botocore, not the verifier's helpers."""
import datetime as dt
+import time
from types import SimpleNamespace
from urllib.parse import parse_qsl, urlencode, urlsplit
@@ -13,9 +14,21 @@ from botocore.awsrequest import AWSRequest
from botocore.credentials import Credentials
from ministack.core import rds_iam
-from ministack.core.rds_iam import RdsIamTokenError, VerifiedRdsToken, verify_rds_iam_token
-from ministack.core.responses import get_account_id
-from ministack.services import iam, sts
+from ministack.core.rds_iam import (
+ AuthorizedRdsConnection,
+ RdsIamTokenError,
+ VerifiedRdsToken,
+ authorize_rds_iam_token,
+ verify_rds_iam_token,
+)
+from ministack.core.responses import (
+ AccountRegionScopedDict,
+ AccountScopedDict,
+ get_account_id,
+ get_region,
+ request_scope,
+)
+from ministack.services import iam, rds, sts
ACCOUNT = "123456789012"
KEY = "AKIARDSVERIFIERTEST"
@@ -257,3 +270,236 @@ def test_verifier_is_strict_independently_of_auth_setting(clock, monkeypatch, au
monkeypatch.setenv("AUTH", auth)
assert isinstance(verify_rds_iam_token(sdk_token(), **TARGET), VerifiedRdsToken)
assert isinstance(verify_rds_iam_token(sdk_token(secret="wrong"), **TARGET), RdsIamTokenError)
+
+
+# Stage 5 of #1744: resource-bound authorization.
+
+OTHER_ACCOUNT = "210987654321"
+AUTHZ_KEY = "test-rds-authorization-key"
+AUTHZ_SECRET = "authorization-test-secret"
+AUTHZ_USER = "AppUser"
+AUTHZ_HOST = "db.example.com"
+AUTHZ_ARN = f"arn:aws:rds-db:{REGION}:{ACCOUNT}:dbuser:db-TEST/{AUTHZ_USER}"
+AUTHZ_ARGS = dict(account_id=ACCOUNT, region=REGION, resource_kind="instance",
+ resource_identifier="database", db_user=AUTHZ_USER)
+
+
+def _authz_policy(resource=AUTHZ_ARN, effect="Allow", **extra):
+ return {"Statement": [{"Effect": effect, "Action": "rds-db:connect", "Resource": resource, **extra}]}
+
+
+def _authz_token(*, host=AUTHZ_HOST, port=3306, user=AUTHZ_USER, key=AUTHZ_KEY, secret=AUTHZ_SECRET, session_token=None):
+ return boto3.client("rds", region_name=REGION, aws_access_key_id=key,
+ aws_secret_access_key=secret, aws_session_token=session_token).generate_db_auth_token(
+ DBHostname=host, Port=port, DBUsername=user,
+ )
+
+
+class TestResourceBoundAuthorization:
+ @pytest.fixture(autouse=True)
+ def state(self, monkeypatch):
+ for name in ("_users", "_access_keys", "_user_inline_policies", "_roles", "_groups",
+ "_group_inline_policies", "_policies"):
+ monkeypatch.setattr(iam, name, AccountScopedDict())
+ monkeypatch.setattr(rds, "_instances", AccountRegionScopedDict())
+ monkeypatch.setattr(rds, "_clusters", AccountRegionScopedDict())
+ monkeypatch.setattr(sts, "_sessions", {})
+ monkeypatch.setenv("AWS_ACCESS_KEY_ID", "test")
+ monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "root-secret")
+ monkeypatch.delenv("AWS_SESSION_TOKEN", raising=False)
+ iam._users.set_scoped(ACCOUNT, None, "alice", {
+ "UserName": "alice", "Arn": f"arn:aws:iam::{ACCOUNT}:user/alice",
+ })
+ iam._access_keys.set_scoped(ACCOUNT, None, AUTHZ_KEY, {
+ "UserName": "alice", "Status": "Active", "SecretAccessKey": AUTHZ_SECRET,
+ })
+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"connect": _authz_policy()})
+ instance = dict(Engine="mysql", DbiResourceId="db-TEST", IAMDatabaseAuthenticationEnabled=True,
+ Endpoint={"Address": AUTHZ_HOST, "Port": 3306})
+ rds._instances.set_scoped(ACCOUNT, REGION, "database", instance)
+ return instance
+
+
+ @pytest.mark.parametrize("auth", [None, "false", "true"])
+ @pytest.mark.parametrize("enabled", [False, True])
+ def test_strict_primitive_independent_of_auth(self, state, monkeypatch, auth, enabled):
+ if auth is None:
+ monkeypatch.delenv("AUTH", raising=False)
+ else:
+ monkeypatch.setenv("AUTH", auth)
+ state["IAMDatabaseAuthenticationEnabled"] = enabled
+ with request_scope(OTHER_ACCOUNT, "eu-west-1"):
+ result = authorize_rds_iam_token(_authz_token(), **AUTHZ_ARGS)
+ assert (get_account_id(), get_region()) == (OTHER_ACCOUNT, "eu-west-1")
+ if enabled:
+ assert isinstance(result, AuthorizedRdsConnection)
+ assert result.resource_arn == AUTHZ_ARN
+ assert AUTHZ_SECRET not in repr(result)
+ else:
+ assert result.code == "IAMDatabaseAuthenticationDisabled"
+
+
+ @pytest.mark.parametrize("resource", [AUTHZ_ARN, AUTHZ_ARN.replace(AUTHZ_USER, "*"), "*"])
+ def test_exact_and_wildcard_grants(self, resource):
+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"grant": _authz_policy(resource)})
+ assert isinstance(authorize_rds_iam_token(_authz_token(), **AUTHZ_ARGS), AuthorizedRdsConnection)
+
+
+ @pytest.mark.parametrize("resource", [AUTHZ_ARN.replace(AUTHZ_USER, AUTHZ_USER.lower()), AUTHZ_ARN.replace("db-TEST", "db-OTHER_ACCOUNT"),
+ AUTHZ_ARN.replace(ACCOUNT, OTHER_ACCOUNT), AUTHZ_ARN.replace(REGION, "eu-west-1"),
+ AUTHZ_ARN.replace("db-TEST", "database")])
+ def test_wrong_policy_resource_is_denied(self, resource):
+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"grant": _authz_policy(resource)})
+ assert authorize_rds_iam_token(_authz_token(), **AUTHZ_ARGS).code == "ImplicitDeny"
+
+
+ def test_explicit_deny_overrides_allow(self):
+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"allow": _authz_policy("*"), "deny": _authz_policy(effect="Deny")})
+ assert authorize_rds_iam_token(_authz_token(), **AUTHZ_ARGS).code == "Deny"
+
+
+ @pytest.mark.parametrize("exception,allowed", [(AUTHZ_ARN, True), (AUTHZ_ARN.replace(AUTHZ_USER, AUTHZ_USER.lower()), False)])
+ def test_not_resource_respects_case(self, exception, allowed):
+ deny = {"Statement": [{"Effect": "Deny", "Action": "rds-db:connect", "NotResource": exception}]}
+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"allow": _authz_policy("*"), "deny": deny})
+ result = authorize_rds_iam_token(_authz_token(), **AUTHZ_ARGS)
+ assert isinstance(result, AuthorizedRdsConnection) is allowed
+
+
+ def test_missing_policy_and_wrong_action_deny(self):
+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {})
+ assert authorize_rds_iam_token(_authz_token(), **AUTHZ_ARGS).code == "ImplicitDeny"
+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"rds": _authz_policy(Action="rds:*")})
+ assert authorize_rds_iam_token(_authz_token(), **AUTHZ_ARGS).code == "ImplicitDeny"
+
+
+ @pytest.mark.parametrize("kind", ["group", "managed"])
+ def test_policies_use_explicit_account_and_restore_context(self, kind):
+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {})
+ iam._user_inline_policies.set_scoped(OTHER_ACCOUNT, None, "alice", {"deny": _authz_policy("*", "Deny")})
+ if kind == "group":
+ iam._groups.set_scoped(ACCOUNT, None, "team", {"Users": ["alice"]})
+ iam._group_inline_policies.set_scoped(ACCOUNT, None, "team", {"grant": _authz_policy()})
+ else:
+ arn = f"arn:aws:iam::{ACCOUNT}:policy/connect"
+ iam._users.get_scoped(ACCOUNT, None, "alice")["AttachedPolicies"] = [arn]
+ iam._policies.set_scoped(ACCOUNT, None, "connect", {
+ "Arn": arn, "DefaultVersionId": "v1", "Versions": {"v1": {"Document": _authz_policy()}},
+ })
+ with request_scope(OTHER_ACCOUNT, "eu-west-1"):
+ assert isinstance(authorize_rds_iam_token(_authz_token(), **AUTHZ_ARGS), AuthorizedRdsConnection)
+ assert (get_account_id(), get_region()) == (OTHER_ACCOUNT, "eu-west-1")
+
+
+ @pytest.mark.parametrize("override", [dict(host="other.example.com"), dict(port=3307), dict(user="appuser"),
+ dict(secret="wrong"), dict(key="unknown")])
+ def test_invalid_token_never_reaches_allow(self, override):
+ assert not isinstance(authorize_rds_iam_token(_authz_token(**override), **AUTHZ_ARGS), AuthorizedRdsConnection)
+
+
+ def test_inactive_key(self):
+ iam._access_keys.get_scoped(ACCOUNT, None, AUTHZ_KEY)["Status"] = "Inactive"
+ assert authorize_rds_iam_token(_authz_token(), **AUTHZ_ARGS).code == "InvalidCredentials"
+
+
+ @pytest.mark.parametrize("field,value", [("account_id", OTHER_ACCOUNT), ("region", "eu-west-1"),
+ ("resource_identifier", "missing")])
+ def test_resource_lookup_does_not_fall_back_to_ambient_tenant(self, field, value):
+ with request_scope(ACCOUNT, REGION):
+ assert authorize_rds_iam_token(_authz_token(), **{**AUTHZ_ARGS, field: value}).code == "ResourceNotFound"
+
+
+ @pytest.mark.parametrize("field,value", [("DbiResourceId", ""), ("DbiResourceId", "db-TEST/*"),
+ ("Endpoint", {}), ("Endpoint", {"Address": AUTHZ_HOST})])
+ def test_incomplete_resource_fails_closed(self, state, field, value):
+ state[field] = value
+ assert not isinstance(authorize_rds_iam_token(_authz_token(), **AUTHZ_ARGS), AuthorizedRdsConnection)
+
+
+ @pytest.mark.parametrize("kind", ["instance", "cluster"])
+ def test_unsupported_engine(self, state, kind):
+ state["Engine"] = "postgres"
+ rds._clusters.set_scoped(ACCOUNT, REGION, "database", state)
+ assert authorize_rds_iam_token(_authz_token(), **{**AUTHZ_ARGS, "resource_kind": kind}).code == "UnsupportedEngine"
+
+
+ @pytest.mark.parametrize("kind,reader", [("instance", False), ("cluster", False), ("cluster", True)])
+ @pytest.mark.parametrize("enabled", [False, True])
+ def test_aurora_uses_cluster_resource_and_flag(self, state, kind, reader, enabled):
+ state.update(Engine="aurora-mysql", DBClusterIdentifier="database", IAMDatabaseAuthenticationEnabled=not enabled)
+ cluster_arn = AUTHZ_ARN.replace("db-TEST", "cluster-TEST")
+ rds._clusters.set_scoped(ACCOUNT, REGION, "database", {
+ "Engine": "aurora-mysql", "DbClusterResourceId": "cluster-TEST",
+ "IAMDatabaseAuthenticationEnabled": enabled, "Endpoint": AUTHZ_HOST,
+ "ReaderEndpoint": "reader.example.com", "Port": 3306,
+ })
+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"grant": _authz_policy(cluster_arn)})
+ result = authorize_rds_iam_token(_authz_token(host="reader.example.com" if reader else AUTHZ_HOST),
+ **{**AUTHZ_ARGS, "resource_kind": kind}, reader_endpoint=reader)
+ if enabled:
+ assert result.resource_arn == cluster_arn
+ else:
+ assert result.code == "IAMDatabaseAuthenticationDisabled"
+
+
+ def test_missing_parent_cluster_is_not_standalone(self, state):
+ state.update(Engine="aurora-mysql", DBClusterIdentifier="missing")
+ assert authorize_rds_iam_token(_authz_token(), **AUTHZ_ARGS).code == "ResourceNotFound"
+
+
+ @pytest.mark.parametrize("session_account", [ACCOUNT, OTHER_ACCOUNT])
+ def test_role_session_must_belong_to_resource_account(self, session_account):
+ key = "test-rds-authorization-session-key"
+ sts._sessions[key] = dict(Arn=f"arn:aws:sts::{session_account}:assumed-role/db-role/session",
+ AccountId=session_account, SecretAccessKey=AUTHZ_SECRET, SessionToken="session-token",
+ Expiration=time.time() + 600, PrincipalType="AssumedRole")
+ iam._roles.set_scoped(session_account, None, "db-role", {"InlinePolicies": {"grant": _authz_policy()}})
+ result = authorize_rds_iam_token(_authz_token(key=key, session_token="session-token"), **AUTHZ_ARGS)
+ assert isinstance(result, AuthorizedRdsConnection) is (session_account == ACCOUNT)
+
+
+ def test_root_still_requires_enabled_resource(self, state):
+ signed = _authz_token(key="test", secret="root-secret")
+ assert isinstance(authorize_rds_iam_token(signed, **AUTHZ_ARGS), AuthorizedRdsConnection)
+ state["IAMDatabaseAuthenticationEnabled"] = False
+ assert authorize_rds_iam_token(signed, **AUTHZ_ARGS).code == "IAMDatabaseAuthenticationDisabled"
+
+
+ def test_ambient_policy_cannot_grant_access(self):
+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {})
+ iam._user_inline_policies.set_scoped(OTHER_ACCOUNT, None, "alice", {"grant": _authz_policy("*")})
+ with request_scope(OTHER_ACCOUNT, "eu-west-1"):
+ assert authorize_rds_iam_token(_authz_token(), **AUTHZ_ARGS).code == "ImplicitDeny"
+ assert (get_account_id(), get_region()) == (OTHER_ACCOUNT, "eu-west-1")
+
+
+ @pytest.mark.parametrize("region,allowed", [(REGION, True), ("eu-west-1", False)])
+ def test_policy_conditions_use_target_region(self, region, allowed):
+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {
+ "grant": _authz_policy(Condition={"StringEquals": {"aws:RequestedRegion": region}}),
+ })
+ assert isinstance(authorize_rds_iam_token(_authz_token(), **AUTHZ_ARGS), AuthorizedRdsConnection) is allowed
+
+
+ def test_cluster_dictionary_endpoint_uses_advertised_port(self):
+ rds._clusters.set_scoped(ACCOUNT, REGION, "database", {
+ "Engine": "aurora-mysql", "DbClusterResourceId": "cluster-TEST",
+ "IAMDatabaseAuthenticationEnabled": True, "Endpoint": {"Address": AUTHZ_HOST, "Port": 13306},
+ "Port": 3306,
+ })
+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"grant": _authz_policy(AUTHZ_ARN.replace("db-", "cluster-"))})
+ args = {**AUTHZ_ARGS, "resource_kind": "cluster"}
+ assert isinstance(authorize_rds_iam_token(_authz_token(port=13306), **args), AuthorizedRdsConnection)
+ assert not isinstance(authorize_rds_iam_token(_authz_token(), **args), AuthorizedRdsConnection)
+
+
+ def test_aurora_without_parent_cannot_use_instance_arn(self, state):
+ state["Engine"] = "aurora-mysql"
+ assert authorize_rds_iam_token(_authz_token(), **AUTHZ_ARGS).code == "InvalidTarget"
+
+
+ @pytest.mark.parametrize("override", [dict(account_id=""), dict(region=""), dict(resource_kind="proxy"),
+ dict(resource_identifier=""), dict(reader_endpoint=True),
+ dict(reader_endpoint="false")])
+ def test_invalid_target(self, override):
+ assert authorize_rds_iam_token(_authz_token(), **{**AUTHZ_ARGS, **override}).code == "InvalidTarget"
diff --git a/tests/test_rds_iam_authorization.py b/tests/test_rds_iam_authorization.py
deleted file mode 100644
index e9468471..00000000
--- a/tests/test_rds_iam_authorization.py
+++ /dev/null
@@ -1,249 +0,0 @@
-# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
-# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).
-"""Offline stage-5 authorization using SDK tokens and real scoped policy stores."""
-
-import time
-
-import boto3
-import pytest
-
-from ministack.core.rds_iam_authorization import AuthorizedRdsConnection, authorize_rds_iam_token
-from ministack.core.responses import (
- AccountRegionScopedDict,
- AccountScopedDict,
- get_account_id,
- get_region,
- request_scope,
-)
-from ministack.services import iam, rds, sts
-
-ACCOUNT = "123456789012"
-OTHER = "210987654321"
-REGION = "us-east-1"
-KEY = "test-rds-authorization-key"
-SECRET = "authorization-test-secret"
-USER = "AppUser"
-HOST = "db.example.com"
-ARN = f"arn:aws:rds-db:{REGION}:{ACCOUNT}:dbuser:db-TEST/{USER}"
-ARGS = dict(account_id=ACCOUNT, region=REGION, resource_kind="instance",
- resource_identifier="database", db_user=USER)
-
-
-def policy(resource=ARN, effect="Allow", **extra):
- return {"Statement": [{"Effect": effect, "Action": "rds-db:connect", "Resource": resource, **extra}]}
-
-
-def token(*, host=HOST, port=3306, user=USER, key=KEY, secret=SECRET, session_token=None):
- return boto3.client("rds", region_name=REGION, aws_access_key_id=key,
- aws_secret_access_key=secret, aws_session_token=session_token).generate_db_auth_token(
- DBHostname=host, Port=port, DBUsername=user,
- )
-
-
[email protected](autouse=True)
-def state(monkeypatch):
- for name in ("_users", "_access_keys", "_user_inline_policies", "_roles", "_groups",
- "_group_inline_policies", "_policies"):
- monkeypatch.setattr(iam, name, AccountScopedDict())
- monkeypatch.setattr(rds, "_instances", AccountRegionScopedDict())
- monkeypatch.setattr(rds, "_clusters", AccountRegionScopedDict())
- monkeypatch.setattr(sts, "_sessions", {})
- monkeypatch.setenv("AWS_ACCESS_KEY_ID", "test")
- monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "root-secret")
- monkeypatch.delenv("AWS_SESSION_TOKEN", raising=False)
- iam._users.set_scoped(ACCOUNT, None, "alice", {
- "UserName": "alice", "Arn": f"arn:aws:iam::{ACCOUNT}:user/alice",
- })
- iam._access_keys.set_scoped(ACCOUNT, None, KEY, {
- "UserName": "alice", "Status": "Active", "SecretAccessKey": SECRET,
- })
- iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"connect": policy()})
- instance = dict(Engine="mysql", DbiResourceId="db-TEST", IAMDatabaseAuthenticationEnabled=True,
- Endpoint={"Address": HOST, "Port": 3306})
- rds._instances.set_scoped(ACCOUNT, REGION, "database", instance)
- return instance
-
-
[email protected]("auth", [None, "false", "true"])
[email protected]("enabled", [False, True])
-def test_strict_primitive_independent_of_auth(state, monkeypatch, auth, enabled):
- if auth is None:
- monkeypatch.delenv("AUTH", raising=False)
- else:
- monkeypatch.setenv("AUTH", auth)
- state["IAMDatabaseAuthenticationEnabled"] = enabled
- with request_scope(OTHER, "eu-west-1"):
- result = authorize_rds_iam_token(token(), **ARGS)
- assert (get_account_id(), get_region()) == (OTHER, "eu-west-1")
- if enabled:
- assert isinstance(result, AuthorizedRdsConnection)
- assert result.resource_arn == ARN
- assert SECRET not in repr(result)
- else:
- assert result.code == "IAMDatabaseAuthenticationDisabled"
-
-
[email protected]("resource", [ARN, ARN.replace(USER, "*"), "*"])
-def test_exact_and_wildcard_grants(resource):
- iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"grant": policy(resource)})
- assert isinstance(authorize_rds_iam_token(token(), **ARGS), AuthorizedRdsConnection)
-
-
[email protected]("resource", [ARN.replace(USER, USER.lower()), ARN.replace("db-TEST", "db-OTHER"),
- ARN.replace(ACCOUNT, OTHER), ARN.replace(REGION, "eu-west-1"),
- ARN.replace("db-TEST", "database")])
-def test_wrong_policy_resource_is_denied(resource):
- iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"grant": policy(resource)})
- assert authorize_rds_iam_token(token(), **ARGS).code == "ImplicitDeny"
-
-
-def test_explicit_deny_overrides_allow():
- iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"allow": policy("*"), "deny": policy(effect="Deny")})
- assert authorize_rds_iam_token(token(), **ARGS).code == "Deny"
-
-
[email protected]("exception,allowed", [(ARN, True), (ARN.replace(USER, USER.lower()), False)])
-def test_not_resource_respects_case(exception, allowed):
- deny = {"Statement": [{"Effect": "Deny", "Action": "rds-db:connect", "NotResource": exception}]}
- iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"allow": policy("*"), "deny": deny})
- result = authorize_rds_iam_token(token(), **ARGS)
- assert isinstance(result, AuthorizedRdsConnection) is allowed
-
-
-def test_missing_policy_and_wrong_action_deny():
- iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {})
- assert authorize_rds_iam_token(token(), **ARGS).code == "ImplicitDeny"
- iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"rds": policy(Action="rds:*")})
- assert authorize_rds_iam_token(token(), **ARGS).code == "ImplicitDeny"
-
-
[email protected]("kind", ["group", "managed"])
-def test_policies_use_explicit_account_and_restore_context(kind):
- iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {})
- iam._user_inline_policies.set_scoped(OTHER, None, "alice", {"deny": policy("*", "Deny")})
- if kind == "group":
- iam._groups.set_scoped(ACCOUNT, None, "team", {"Users": ["alice"]})
- iam._group_inline_policies.set_scoped(ACCOUNT, None, "team", {"grant": policy()})
- else:
- arn = f"arn:aws:iam::{ACCOUNT}:policy/connect"
- iam._users.get_scoped(ACCOUNT, None, "alice")["AttachedPolicies"] = [arn]
- iam._policies.set_scoped(ACCOUNT, None, "connect", {
- "Arn": arn, "DefaultVersionId": "v1", "Versions": {"v1": {"Document": policy()}},
- })
- with request_scope(OTHER, "eu-west-1"):
- assert isinstance(authorize_rds_iam_token(token(), **ARGS), AuthorizedRdsConnection)
- assert (get_account_id(), get_region()) == (OTHER, "eu-west-1")
-
-
[email protected]("override", [dict(host="other.example.com"), dict(port=3307), dict(user="appuser"),
- dict(secret="wrong"), dict(key="unknown")])
-def test_invalid_token_never_reaches_allow(override):
- assert not isinstance(authorize_rds_iam_token(token(**override), **ARGS), AuthorizedRdsConnection)
-
-
-def test_inactive_key():
- iam._access_keys.get_scoped(ACCOUNT, None, KEY)["Status"] = "Inactive"
- assert authorize_rds_iam_token(token(), **ARGS).code == "InvalidCredentials"
-
-
[email protected]("field,value", [("account_id", OTHER), ("region", "eu-west-1"),
- ("resource_identifier", "missing")])
-def test_resource_lookup_does_not_fall_back_to_ambient_tenant(field, value):
- with request_scope(ACCOUNT, REGION):
- assert authorize_rds_iam_token(token(), **{**ARGS, field: value}).code == "ResourceNotFound"
-
-
[email protected]("field,value", [("DbiResourceId", ""), ("DbiResourceId", "db-TEST/*"),
- ("Endpoint", {}), ("Endpoint", {"Address": HOST})])
-def test_incomplete_resource_fails_closed(state, field, value):
- state[field] = value
- assert not isinstance(authorize_rds_iam_token(token(), **ARGS), AuthorizedRdsConnection)
-
-
[email protected]("kind", ["instance", "cluster"])
-def test_unsupported_engine(state, kind):
- state["Engine"] = "postgres"
- rds._clusters.set_scoped(ACCOUNT, REGION, "database", state)
- assert authorize_rds_iam_token(token(), **{**ARGS, "resource_kind": kind}).code == "UnsupportedEngine"
-
-
[email protected]("kind,reader", [("instance", False), ("cluster", False), ("cluster", True)])
[email protected]("enabled", [False, True])
-def test_aurora_uses_cluster_resource_and_flag(state, kind, reader, enabled):
- state.update(Engine="aurora-mysql", DBClusterIdentifier="database", IAMDatabaseAuthenticationEnabled=not enabled)
- cluster_arn = ARN.replace("db-TEST", "cluster-TEST")
- rds._clusters.set_scoped(ACCOUNT, REGION, "database", {
- "Engine": "aurora-mysql", "DbClusterResourceId": "cluster-TEST",
- "IAMDatabaseAuthenticationEnabled": enabled, "Endpoint": HOST,
- "ReaderEndpoint": "reader.example.com", "Port": 3306,
- })
- iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"grant": policy(cluster_arn)})
- result = authorize_rds_iam_token(token(host="reader.example.com" if reader else HOST),
- **{**ARGS, "resource_kind": kind}, reader_endpoint=reader)
- if enabled:
- assert result.resource_arn == cluster_arn
- else:
- assert result.code == "IAMDatabaseAuthenticationDisabled"
-
-
-def test_missing_parent_cluster_is_not_standalone(state):
- state.update(Engine="aurora-mysql", DBClusterIdentifier="missing")
- assert authorize_rds_iam_token(token(), **ARGS).code == "ResourceNotFound"
-
-
[email protected]("session_account", [ACCOUNT, OTHER])
-def test_role_session_must_belong_to_resource_account(session_account):
- key = "test-rds-authorization-session-key"
- sts._sessions[key] = dict(Arn=f"arn:aws:sts::{session_account}:assumed-role/db-role/session",
- AccountId=session_account, SecretAccessKey=SECRET, SessionToken="session-token",
- Expiration=time.time() + 600, PrincipalType="AssumedRole")
- iam._roles.set_scoped(session_account, None, "db-role", {"InlinePolicies": {"grant": policy()}})
- result = authorize_rds_iam_token(token(key=key, session_token="session-token"), **ARGS)
- assert isinstance(result, AuthorizedRdsConnection) is (session_account == ACCOUNT)
-
-
-def test_root_still_requires_enabled_resource(state):
- signed = token(key="test", secret="root-secret")
- assert isinstance(authorize_rds_iam_token(signed, **ARGS), AuthorizedRdsConnection)
- state["IAMDatabaseAuthenticationEnabled"] = False
- assert authorize_rds_iam_token(signed, **ARGS).code == "IAMDatabaseAuthenticationDisabled"
-
-
-def test_ambient_policy_cannot_grant_access():
- iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {})
- iam._user_inline_policies.set_scoped(OTHER, None, "alice", {"grant": policy("*")})
- with request_scope(OTHER, "eu-west-1"):
- assert authorize_rds_iam_token(token(), **ARGS).code == "ImplicitDeny"
- assert (get_account_id(), get_region()) == (OTHER, "eu-west-1")
-
-
[email protected]("region,allowed", [(REGION, True), ("eu-west-1", False)])
-def test_policy_conditions_use_target_region(region, allowed):
- iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {
- "grant": policy(Condition={"StringEquals": {"aws:RequestedRegion": region}}),
- })
- assert isinstance(authorize_rds_iam_token(token(), **ARGS), AuthorizedRdsConnection) is allowed
-
-
-def test_cluster_dictionary_endpoint_uses_advertised_port():
- rds._clusters.set_scoped(ACCOUNT, REGION, "database", {
- "Engine": "aurora-mysql", "DbClusterResourceId": "cluster-TEST",
- "IAMDatabaseAuthenticationEnabled": True, "Endpoint": {"Address": HOST, "Port": 13306},
- "Port": 3306,
- })
- iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"grant": policy(ARN.replace("db-", "cluster-"))})
- args = {**ARGS, "resource_kind": "cluster"}
- assert isinstance(authorize_rds_iam_token(token(port=13306), **args), AuthorizedRdsConnection)
- assert not isinstance(authorize_rds_iam_token(token(), **args), AuthorizedRdsConnection)
-
-
-def test_aurora_without_parent_cannot_use_instance_arn(state):
- state["Engine"] = "aurora-mysql"
- assert authorize_rds_iam_token(token(), **ARGS).code == "InvalidTarget"
-
-
[email protected]("override", [dict(account_id=""), dict(region=""), dict(resource_kind="proxy"),
- dict(resource_identifier=""), dict(reader_endpoint=True),
- dict(reader_endpoint="false")])
-def test_invalid_target(override):
- assert authorize_rds_iam_token(token(), **{**ARGS, **override}).code == "InvalidTarget"
diff --git a/tests/test_s3.py b/tests/test_s3.py
index 7f3c6525..d7d98225 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -6666,3 +6666,74 @@ def test_s3_mrap_cleared_by_reset(cfn, s3):
with pytest.raises(urllib.error.HTTPError) as ei:
_mrap_get(alias, "who.txt")
assert ei.value.code in (403, 404)
+
+
+def _s3_lambda_arn(name="s3-notify-target"):
+ return f"arn:aws:lambda:us-east-1:000000000000:function:{name}"
+
+
+def test_s3_notification_is_stored_in_the_sdk_wire_form(s3):
+ """Stored as the wire spells it, so any SDK reads back what another wrote."""
+ import urllib.request
+
+ bucket = f"notif-wire-{_uuid_mod.uuid4().hex[:8]}"
+ s3.create_bucket(Bucket=bucket)
+ arn = _s3_lambda_arn()
+ xml = (
+ '<NotificationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'
+ "<LambdaFunctionConfiguration>"
+ f"<LambdaFunctionArn>{arn}</LambdaFunctionArn>"
+ "<Event>s3:ObjectCreated:*</Event>"
+ "</LambdaFunctionConfiguration></NotificationConfiguration>"
+ )
+ request = urllib.request.Request(
+ f"{ENDPOINT}/{bucket}?notification", data=xml.encode(), method="PUT")
+ with urllib.request.urlopen(request) as response:
+ assert response.status == 200
+
+ configs = s3.get_bucket_notification_configuration(
+ Bucket=bucket)["LambdaFunctionConfigurations"]
+ assert [c["LambdaFunctionArn"] for c in configs] == [arn]
+ assert configs[0]["Events"] == ["s3:ObjectCreated:*"]
+
+
+def test_s3_notification_auto_generates_a_base64_uuid_id(s3, sqs):
+ """An omitted Id is base64 of a UUID (captured us-east-1 2026-09-20)."""
+ import base64 as _b64
+
+ bucket = f"notif-id-{_uuid_mod.uuid4().hex[:8]}"
+ s3.create_bucket(Bucket=bucket)
+ queue = sqs.create_queue(QueueName=f"notif-id-{_uuid_mod.uuid4().hex[:8]}")["QueueUrl"]
+ queue_arn = sqs.get_queue_attributes(
+ QueueUrl=queue, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ s3.put_bucket_notification_configuration(
+ Bucket=bucket,
+ NotificationConfiguration={"QueueConfigurations": [
+ {"QueueArn": queue_arn, "Events": ["s3:ObjectCreated:*"]}]},
+ )
+ config = s3.get_bucket_notification_configuration(
+ Bucket=bucket)["QueueConfigurations"][0]
+ generated = config["Id"]
+ assert generated, "AWS auto-generates an Id when the caller omits one"
+ # base64 of a 36-char UUID: 48 chars, no padding.
+ assert len(generated) == 48
+ decoded = _b64.b64decode(generated + "==").decode()
+ assert _uuid_mod.UUID(decoded)
+ # It is stable across reads, not minted per GET.
+ assert s3.get_bucket_notification_configuration(
+ Bucket=bucket)["QueueConfigurations"][0]["Id"] == generated
+
+
+def test_s3_notification_keeps_an_explicit_id(s3, sqs):
+ bucket = f"notif-expl-{_uuid_mod.uuid4().hex[:8]}"
+ s3.create_bucket(Bucket=bucket)
+ queue = sqs.create_queue(QueueName=f"notif-expl-{_uuid_mod.uuid4().hex[:8]}")["QueueUrl"]
+ queue_arn = sqs.get_queue_attributes(
+ QueueUrl=queue, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ s3.put_bucket_notification_configuration(
+ Bucket=bucket,
+ NotificationConfiguration={"QueueConfigurations": [
+ {"Id": "mine", "QueueArn": queue_arn, "Events": ["s3:ObjectCreated:*"]}]},
+ )
+ assert s3.get_bucket_notification_configuration(
+ Bucket=bucket)["QueueConfigurations"][0]["Id"] == "mine"
diff --git a/tests/test_sqs.py b/tests/test_sqs.py
index a503953d..712855c7 100644
--- a/tests/test_sqs.py
+++ b/tests/test_sqs.py
@@ -656,7 +656,7 @@ def test_sqs_send_message_batch_rejects_oversized_aggregate(sqs):
"""
url = sqs.create_queue(
QueueName="intg-sqs-batch-too-long",
- Attributes={"MaximumMessageSize": "262144"}, # default
+ Attributes={"MaximumMessageSize": "262144"}, # below the 1 MiB default
)["QueueUrl"]
# 10 × 150 KiB → 1.5 MiB total. Each individual entry is within the queue's
@@ -1060,12 +1060,13 @@ def test_sqs_localstack_queue_path_alias(sqs):
def test_sqs_send_message_rejects_oversized_body(sqs):
"""SendMessage must reject bodies exceeding the queue's MaximumMessageSize
attribute with InvalidParameterValue (400). MaximumMessageSize defaults to
- 262144 (256 KiB) per AWS. Before this fix MS silently accepted oversized
- messages locally while real AWS rejected — masking client bugs."""
+ 1048576 (1 MiB) — captured eu-north-1 2026-09-19; AWS raised it from 256 KiB.
+ Before this fix MS silently accepted oversized messages locally while real
+ AWS rejected — masking client bugs."""
import pytest as _pytest
q = sqs.create_queue(QueueName="intg-sqs-size-default")["QueueUrl"]
- body = "x" * (262144 + 1)
+ body = "x" * (1048576 + 1)
with _pytest.raises(ClientError) as exc:
sqs.send_message(QueueUrl=q, MessageBody=body)
assert exc.value.response["Error"]["Code"] == "InvalidParameterValue"
@@ -1073,7 +1074,7 @@ def test_sqs_send_message_rejects_oversized_body(sqs):
def test_sqs_send_message_respects_configured_maximum_message_size(sqs):
"""A queue with a tighter MaximumMessageSize must reject bodies that fit
- in the default 262144 but exceed the configured value."""
+ in the default 1048576 but exceed the configured value."""
import pytest as _pytest
q = sqs.create_queue(
diff --git a/tests/test_waf.py b/tests/test_waf.py
index f8eef4c5..5ac9076f 100644
--- a/tests/test_waf.py
+++ b/tests/test_waf.py
@@ -764,7 +764,7 @@ def test_wafv2_restore_legacy_state_canonicalizes_cloudfront_arns_direct(direct_
def test_wafv2_cloudformation_uses_canonical_web_acl_records_direct(direct_waf_scope):
set_request_region("us-west-2")
- uid, attrs = cfn_provisioners._waf_web_acl_create(
+ physical_id, attrs = cfn_provisioners._waf_web_acl_create(
"Acl",
{
"Name": "cfn-cf-acl",
@@ -779,6 +779,8 @@ def test_wafv2_cloudformation_uses_canonical_web_acl_records_direct(direct_waf_s
},
"stack",
)
+ uid = attrs["Id"]
+ assert physical_id == f"cfn-cf-acl|{uid}|CLOUDFRONT"
assert attrs["Arn"] == (
f"arn:aws:wafv2:us-east-1:000000000000:global/webacl/cfn-cf-acl/{uid}"
)
@@ -787,7 +789,7 @@ def test_wafv2_cloudformation_uses_canonical_web_acl_records_direct(direct_waf_s
] == attrs["Arn"]
assert waf_service._waf_tags[attrs["Arn"]] == [{"Key": "from", "Value": "cfn"}]
- cfn_provisioners._waf_web_acl_delete(uid, {"Scope": "CLOUDFRONT"})
+ cfn_provisioners._waf_web_acl_delete(physical_id, {"Scope": "CLOUDFRONT"})
assert waf_service._web_acls.get_scoped("000000000000", "us-east-1", uid) is None
assert attrs["Arn"] not in waf_service._waf_tags