Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
AWS parity gaps + fixes
Nahuel9902d692fb98cc0
diff --git a/ministack/services/athena.py b/ministack/services/athena.pyindex 19a0e2fc..fdf48335 100644--- a/ministack/services/athena.py+++ b/ministack/services/athena.py@@ -976,27 +976,49 @@ def _list_prepared_statements(data):# ---- Table Metadata (stubs) ----+def _glue_col(c):+ col = {"Name": c.get("Name", ""), "Type": c.get("Type", "string")}+ if c.get("Comment"):+ col["Comment"] = c["Comment"]+ return col+++def _glue_table_to_metadata(t):+ # Athena tables are Glue Data Catalog tables; surface the real columns and+ # partition keys rather than empty lists.+ sd = t.get("StorageDescriptor", {}) or {}+ return {+ "Name": t.get("Name", ""),+ "CreateTime": int(time.time()),+ "LastAccessTime": int(time.time()),+ "TableType": t.get("TableType", "EXTERNAL_TABLE"),+ "Columns": [_glue_col(c) for c in sd.get("Columns", [])],+ "PartitionKeys": [_glue_col(c) for c in t.get("PartitionKeys", [])],+ "Parameters": t.get("Parameters", {}) or {"classification": "csv"},+ }++def _get_table_metadata(data):- catalog = data.get("CatalogName", "AwsDataCatalog")+ from ministack.services import glue as glue_svcdb = data.get("DatabaseName", "default")table = data.get("TableName", "")- return json_response(- {- "TableMetadata": {- "Name": table,- "CreateTime": int(time.time()),- "LastAccessTime": int(time.time()),- "TableType": "EXTERNAL_TABLE",- "Columns": [],- "PartitionKeys": [],- "Parameters": {"classification": "csv"},- }- }- )+ t = glue_svc._tables.get(f"{db}/{table}")+ if t:+ return json_response({"TableMetadata": _glue_table_to_metadata(t)})+ # Unknown table — keep the prior lenient empty shape.+ return json_response({"TableMetadata": {+ "Name": table, "CreateTime": int(time.time()),+ "LastAccessTime": int(time.time()), "TableType": "EXTERNAL_TABLE",+ "Columns": [], "PartitionKeys": [], "Parameters": {"classification": "csv"},+ }})def _list_table_metadata(data):- return json_response({"TableMetadataList": []})+ from ministack.services import glue as glue_svc+ db = data.get("DatabaseName", "default")+ tables = [_glue_table_to_metadata(t) for k, t in glue_svc._tables.items()+ if k.startswith(f"{db}/")]+ return json_response({"TableMetadataList": tables})# ---- Tags ----diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.pyindex cbaa1d4c..4c7a68d7 100644--- a/ministack/services/cloudformation/changesets.py+++ b/ministack/services/cloudformation/changesets.py@@ -139,7 +139,8 @@ def _create_change_set(params):return _error("ValidationError", f"Template format error: {e}")try:- param_values = _resolve_parameters(template, provided_params)+ param_values = _resolve_parameters(+ template, provided_params, stack.get("_resolved_params", {}))except ValueError as exc:return _error("ValidationError", str(exc))diff --git a/ministack/services/cloudformation/engine.py b/ministack/services/cloudformation/engine.pyindex 90ddc694..83771445 100644--- a/ministack/services/cloudformation/engine.py+++ b/ministack/services/cloudformation/engine.py@@ -128,21 +128,38 @@ _AWS_SPECIFIC_TYPES = {}-def _resolve_parameters(template: dict, provided_params: list[dict]) -> dict:+def _resolve_parameters(template: dict, provided_params: list[dict],+ previous_params: dict | None = None) -> dict:"""Resolve template parameters with provided values and defaults.+ ``previous_params`` (a prior {name: {Value, NoEcho}} map) is consulted for+ parameters sent with ``UsePreviousValue=true`` — which is how+ ``aws cloudformation deploy`` re-sends existing parameters when no+ ``--parameter-overrides`` are given.+Returns dict of param_name -> {Value, NoEcho}."""param_defs = template.get("Parameters", {})- provided_map = {p["Key"]: p["Value"] for p in provided_params if "Key" in p}+ provided_map = {p["Key"]: p for p in provided_params if "Key" in p}+ previous_params = previous_params or {}resolved = {}for name, defn in param_defs.items():ptype = defn.get("Type", "String")no_echo = str(defn.get("NoEcho", "false")).lower() == "true"- if name in provided_map:- value = provided_map[name]+ entry = provided_map.get(name)+ if entry is not None and entry.get("UsePreviousValue"):+ prev = previous_params.get(name)+ if prev is not None:+ value = prev["Value"] if isinstance(prev, dict) else prev+ elif "Default" in defn:+ value = defn["Default"]+ else:+ raise ValueError(+ f"Parameter '{name}' has no previous value and no Default")+ elif entry is not None:+ value = entry.get("Value", "")elif "Default" in defn:value = defn["Default"]else:diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.pyindex d0b2762a..007e0224 100644--- a/ministack/services/cloudformation/handlers.py+++ b/ministack/services/cloudformation/handlers.py@@ -481,7 +481,8 @@ def _update_stack(params):disable_rollback = _p(params, "DisableRollback", "false").lower() == "true"try:- param_values = _resolve_parameters(template, provided_params)+ param_values = _resolve_parameters(+ template, provided_params, stack.get("_resolved_params", {}))except ValueError as exc:return _error("ValidationError", str(exc))diff --git a/ministack/services/cloudformation/helpers.py b/ministack/services/cloudformation/helpers.pyindex 94e67b30..2a833c0c 100644--- a/ministack/services/cloudformation/helpers.py+++ b/ministack/services/cloudformation/helpers.py@@ -54,7 +54,9 @@ def _extract_members(params, prefix):breakvalue = (_p(params, f"{prefix}.member.{i}.ParameterValue")or _p(params, f"{prefix}.member.{i}.Value"))- result.append({"Key": key, "Value": value or ""})+ use_prev = _p(params, f"{prefix}.member.{i}.UsePreviousValue")+ result.append({"Key": key, "Value": value or "",+ "UsePreviousValue": str(use_prev).lower() == "true"})i += 1return resultdiff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 4162c1c2..4bbd34a0 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -233,6 +233,7 @@ _pool_domain_map = AccountScopedDict() # domain -> pool_id_authorization_codes: dict[str, dict] = {} # code -> {client_id, pool_id, redirect_uri, scope, username, nonce, expires_at, code_challenge, code_challenge_method}_refresh_tokens: dict[str, dict] = {} # refresh_token_value -> {pool_id, client_id, username, scope}+_revoked_tokens: set = set() # refresh-token values invalidated by RevokeToken# ---------------------------------------------------------------------------# In-memory state — Identity Pools (cognito-identity)@@ -309,6 +310,7 @@ def get_state():"identity_tags": copy.deepcopy(_identity_tags),"authorization_codes": copy.deepcopy(_authorization_codes),"refresh_tokens": copy.deepcopy(_refresh_tokens),+ "revoked_tokens": list(_revoked_tokens),"auth_codes": copy.deepcopy(_auth_codes),"challenge_sessions": copy.deepcopy(_challenge_sessions),}@@ -322,6 +324,7 @@ def restore_state(data):_identity_tags.update(data.get("identity_tags", {}))_authorization_codes.update(data.get("authorization_codes", {}))_refresh_tokens.update(data.get("refresh_tokens", {}))+ _revoked_tokens.update(data.get("revoked_tokens", []))_auth_codes.update(data.get("auth_codes", {}))_challenge_sessions.update(data.get("challenge_sessions", {}))@@ -2114,7 +2117,13 @@ def _admin_user_global_sign_out(data):user, err = _resolve_user(pool, username)if err:return err- user["_tokens"] = []+ # Invalidate every token issued before now (checked by REFRESH_TOKEN_AUTH)+ # and drop the user's OAuth-flow refresh tokens.+ user["_signout_at"] = _now_epoch()+ uname = user.get("Username", username)+ for tok in [t for t, e in _refresh_tokens.items()+ if e.get("username") == uname and e.get("pool_id") == pid]:+ del _refresh_tokens[tok]return json_response({})@@ -2277,6 +2286,9 @@ def _admin_initiate_auth(data):if not users:return error_response_json("NotAuthorizedException", "No users in pool.", 400)user = users[0]+ if _refresh_token_revoked(refresh_token, user):+ return error_response_json("NotAuthorizedException",+ "Refresh Token has been revoked", 400)result = _build_auth_result(pid, cid, user)result.pop("RefreshToken", None) # AWS doesn't return a new refresh token herereturn json_response({"AuthenticationResult": result})@@ -2605,6 +2617,9 @@ def _initiate_auth(data):if not users:return error_response_json("NotAuthorizedException", "No users in pool.", 400)user = users[0]+ if _refresh_token_revoked(refresh_token, user):+ return error_response_json("NotAuthorizedException",+ "Refresh Token has been revoked", 400)result = _build_auth_result(pid, cid, user)result.pop("RefreshToken", None) # AWS doesn't return a new refresh token herereturn json_response({"AuthenticationResult": result})@@ -2883,12 +2898,55 @@ def _respond_to_auth_challenge(data):return error_response_json("InvalidParameterException", f"Unsupported challenge: {challenge_name}", 400)+def _refresh_token_revoked(refresh_token: str, user: dict | None) -> bool:+ """True if a refresh token has been revoked (RevokeToken) or invalidated by a+ GlobalSignOut that happened after the token was issued."""+ if refresh_token in _revoked_tokens:+ return True+ signout_at = (user or {}).get("_signout_at", 0)+ if signout_at:+ try:+ payload = json.loads(+ base64.urlsafe_b64decode(refresh_token.split(".")[1] + "=="))+ if int(payload.get("iat", 0)) < int(signout_at):+ return True+ except Exception:+ pass+ return False++def _global_sign_out(data):- # Access token is opaque to us — accept and succeed+ # AWS invalidates every token issued to the user before the sign-out. Mark+ # the user with a sign-out timestamp (checked by REFRESH_TOKEN_AUTH) and drop+ # any OAuth-flow refresh tokens so /oauth2/token can't mint new ones either.+ access_token = data.get("AccessToken", "")+ try:+ payload = json.loads(+ base64.urlsafe_b64decode(access_token.split(".")[1] + "=="))+ except Exception:+ return json_response({})+ username = payload.get("username", "")+ iss = payload.get("iss", "")+ pool_id = iss.rsplit("/", 1)[-1] if iss else ""+ pool = _user_pools.get(pool_id)+ if pool and username:+ user = pool["_users"].get(username)+ if user:+ user["_signout_at"] = _now_epoch()+ if username and pool_id:+ for tok in [t for t, e in _refresh_tokens.items()+ if e.get("username") == username and e.get("pool_id") == pool_id]:+ del _refresh_tokens[tok]return json_response({})def _revoke_token(data):+ # AWS revokes the supplied refresh token (and tokens derived from it). Record+ # it as revoked (checked by REFRESH_TOKEN_AUTH) and drop the OAuth-flow entry.+ token = data.get("Token", "")+ if token:+ _revoked_tokens.add(token)+ _refresh_tokens.pop(token, None)return json_response({})diff --git a/ministack/services/rds.py b/ministack/services/rds.pyindex 16d97f3f..908a0b2c 100644--- a/ministack/services/rds.py+++ b/ministack/services/rds.py@@ -767,7 +767,14 @@ def _create_db_instance(p):logger.warning("RDS: Docker failed for %s: %s", db_id, e)cluster_id = _p(p, "DBClusterIdentifier")- param_group_name = _p(p, "DBParameterGroupName") or f"default.{engine}{engine_version.split('.')[0]}"+ explicit_pg = _p(p, "DBParameterGroupName")+ # AWS rejects a reference to a parameter group that doesn't exist. Validate+ # custom names against the store; AWS-managed `default.*` groups are implicit+ # and not tracked here, so they're accepted as-is.+ if explicit_pg and not explicit_pg.startswith("default.") and explicit_pg not in _param_groups:+ return _error("DBParameterGroupNotFound",+ f"DBParameterGroup {explicit_pg} not found.", 404)+ param_group_name = explicit_pg or f"default.{engine}{engine_version.split('.')[0]}"now_ts = time.time()vpc_sgs = _parse_member_list(p, "VpcSecurityGroupIds")@@ -1296,6 +1303,12 @@ def _create_db_cluster(p):return _error("DBClusterAlreadyExistsFault",f"DB cluster {cluster_id} already exists.", 400)+ explicit_cpg = _p(p, "DBClusterParameterGroupName")+ if (explicit_cpg and not explicit_cpg.startswith("default.")+ and explicit_cpg not in _db_cluster_param_groups):+ return _error("DBClusterParameterGroupNotFound",+ f"DBClusterParameterGroup {explicit_cpg} not found.", 404)+engine = _p(p, "Engine") or "aurora-postgresql"engine_version = _p(p, "EngineVersion") or _default_engine_version(engine)port = int(_p(p, "Port") or _default_port(engine))diff --git a/ministack/services/rds_data.py b/ministack/services/rds_data.pyindex 8644f968..a7c253e5 100644--- a/ministack/services/rds_data.py+++ b/ministack/services/rds_data.py@@ -324,16 +324,28 @@ def _connect(instance, engine, database=None, password=None,else:try:import psycopg2+ import psycopg2.extrasexcept ImportError:raise ImportError("psycopg2 is required for PostgreSQL/Aurora PostgreSQL rds-data support. ""Install with: pip install psycopg2-binary")pg_user = username or instance.get("MasterUsername", "admin")- return psycopg2.connect(+ conn = psycopg2.connect(host=host, port=int(port), user=pg_user,password=pw, dbname=db or "postgres",)+ # Parity with the pymysql branch: a non-transactional ExecuteStatement+ # must commit, otherwise psycopg2's implicit transaction is rolled back+ # when the connection closes and the write is lost.+ conn.autocommit = True+ # Aurora Data API returns json/jsonb as its stored JSON *text*. Stop+ # psycopg2 from auto-parsing it into a dict/list (which _field_value+ # would then emit as an invalid single-quoted Python repr). Scoped to+ # this connection so other psycopg2 users are unaffected.+ psycopg2.extras.register_default_json(conn_or_curs=conn, loads=lambda x: x)+ psycopg2.extras.register_default_jsonb(conn_or_curs=conn, loads=lambda x: x)+ return conndef _field_value(val, type_name=None):@@ -462,7 +474,8 @@ def _execute_statement(data):params = _convert_parameters(parameters)exec_sql = sqlif params:- for name in params:+ # Replace longest names first so ":1" doesn't clobber ":10"/":18" etc.+ for name in sorted(params, key=len, reverse=True):exec_sql = exec_sql.replace(f":{name}", f"%({name})s")own_conn = False@@ -642,7 +655,8 @@ def _batch_execute_statement(data):exec_sql = sqlif parameter_sets:sample = _convert_parameters(parameter_sets[0])- for name in sample:+ # Longest names first so ":1" doesn't clobber ":10"/":18" etc.+ for name in sorted(sample, key=len, reverse=True):exec_sql = exec_sql.replace(f":{name}", f"%({name})s")for param_set in parameter_sets:diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.pyindex e7d95c79..8205b6e8 100644--- a/ministack/services/stepfunctions.py+++ b/ministack/services/stepfunctions.py@@ -1570,6 +1570,24 @@ def _invoke_with_callback(resource, input_data, token, state_def):_call_lambda(func_name, input_data)except _ExecutionError:pass+ else:+ # Non-Lambda service integrations (sqs:sendMessage, sns:publish, …) must+ # actually perform the call — delivering the payload that carries the+ # task token — before we block for the callback. Without this the task is+ # scheduled but nothing is ever sent and the execution hangs forever+ # (#959). A failed integration fails the task (propagates) rather than+ # hanging.+ try:+ for prefix, handler in _SERVICE_DISPATCH.items():+ if clean_resource.startswith(prefix):+ handler(clean_resource, input_data)+ break+ else:+ if "aws-sdk:" in clean_resource:+ _invoke_aws_sdk_integration(clean_resource, input_data)+ except _ExecutionError:+ _task_tokens.pop(token, None)+ raisetimeout = state_def.get("TimeoutSeconds", 99999)if not evt.wait(timeout=timeout):@@ -3831,7 +3849,13 @@ def _invoke_sqs_send_message(resource, input_data):return input_datatry:url = input_data.get("QueueUrl", "")- result = sqs._act_send_message(input_data, url)+ payload = dict(input_data)+ body = payload.get("MessageBody")+ if isinstance(body, (dict, list)):+ # SFN serialises an object MessageBody to JSON text before calling+ # SQS (which requires a string body).+ payload["MessageBody"] = json.dumps(body)+ result = sqs._act_send_message(payload, url)return resultexcept sqs._Err as e:raise _ExecutionError(f"SQS.{e.code}", e.message)diff --git a/tests/test_athena.py b/tests/test_athena.pyindex c5fceaf6..2ff1d209 100644--- a/tests/test_athena.py+++ b/tests/test_athena.py@@ -303,6 +303,27 @@ def test_athena_engine_mock_via_config(athena):urllib.request.urlopen(req2, timeout=5)+def test_athena_table_metadata_includes_partition_keys(athena, glue):+ """GetTableMetadata / ListTableMetadata surface the Glue table's real columns+ and partition keys rather than empty stubs (#1423)."""+ glue.create_database(DatabaseInput={"Name": "md_db"})+ glue.create_table(DatabaseName="md_db", TableInput={+ "Name": "events",+ "StorageDescriptor": {"Columns": [{"Name": "id", "Type": "bigint"}]},+ "PartitionKeys": [{"Name": "dt", "Type": "string"}],+ })+ md = athena.get_table_metadata(+ CatalogName="AwsDataCatalog", DatabaseName="md_db",+ TableName="events")["TableMetadata"]+ assert [c["Name"] for c in md["Columns"]] == ["id"]+ assert [p["Name"] for p in md["PartitionKeys"]] == ["dt"]+ lst = athena.list_table_metadata(+ CatalogName="AwsDataCatalog", DatabaseName="md_db")["TableMetadataList"]+ assert any(+ t["Name"] == "events" and [p["Name"] for p in t["PartitionKeys"]] == ["dt"]+ for t in lst)++def test_athena_mixed_glue_and_s3_uri(athena, glue, monkeypatch, tmp_path):bucket_name = "athena-results"db_name = "test_db_athena_glue_s3"diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 24307960..7ea57a2f 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -170,6 +170,40 @@ def test_cfn_stack_with_parameters(cfn, sqs):urls = sqs.list_queues(QueueNamePrefix="cfn-t02-custom").get("QueueUrls", [])assert any("cfn-t02-custom" in u for u in urls)+def test_cfn_change_set_use_previous_value_updates_resource(cfn, ssm):+ """A change set created with UsePreviousValue (the `aws cloudformation deploy`+ no-`--parameter-overrides` path) must resolve the parameter to its stored+ value, so a parameter-driven resource still updates rather than resolving to+ an empty value and missing the real resource (#897)."""+ def template(value):+ return json.dumps({+ "AWSTemplateFormatVersion": "2010-09-09",+ "Parameters": {"Prefix": {"Type": "String", "Default": "demo"}},+ "Resources": {"P": {+ "Type": "AWS::SSM::Parameter",+ "Properties": {+ "Name": {"Fn::Sub": "/${Prefix}/config"},+ "Type": "String",+ "Value": value,+ },+ }},+ })++ cfn.create_stack(StackName="cfn-upv", TemplateBody=template("v1"))+ _wait_stack(cfn, "cfn-upv")+ assert ssm.get_parameter(Name="/demo/config")["Parameter"]["Value"] == "v1"++ # Change set re-sends Prefix as UsePreviousValue (what `deploy` does without+ # --parameter-overrides). Prefix must resolve to "demo", not "".+ cfn.create_change_set(+ StackName="cfn-upv", ChangeSetName="cs2", TemplateBody=template("v2"),+ Parameters=[{"ParameterKey": "Prefix", "UsePreviousValue": True}],+ )+ cfn.execute_change_set(StackName="cfn-upv", ChangeSetName="cs2")+ _wait_stack(cfn, "cfn-upv")++ assert ssm.get_parameter(Name="/demo/config")["Parameter"]["Value"] == "v2"+def test_cfn_intrinsic_ref_getatt(cfn, ssm):template = {"AWSTemplateFormatVersion": "2010-09-09",diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 69e4c593..d2b41034 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -366,7 +366,15 @@ def test_cognito_global_sign_out(cognito_idp):AuthParameters={"USERNAME": "noah", "PASSWORD": "NoahPass1!"},)access_token = auth["AuthenticationResult"]["AccessToken"]- cognito_idp.global_sign_out(AccessToken=access_token) # must not raise+ refresh_token = auth["AuthenticationResult"]["RefreshToken"]+ time.sleep(1.1) # sign-out invalidates tokens issued before now (1s granularity)+ cognito_idp.global_sign_out(AccessToken=access_token)+ # every refresh token issued before the sign-out must be invalidated (#1395)+ with pytest.raises(cognito_idp.exceptions.NotAuthorizedException):+ cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid, AuthFlow="REFRESH_TOKEN_AUTH",+ AuthParameters={"REFRESH_TOKEN": refresh_token},+ )def test_cognito_admin_confirm_signup(cognito_idp):pid = cognito_idp.create_user_pool(PoolName="AdminConfirmPool")["UserPool"]["Id"]@@ -717,8 +725,26 @@ def test_cognito_admin_reset_user_password(cognito_idp):def test_cognito_admin_user_global_sign_out(cognito_idp):pid = cognito_idp.create_user_pool(PoolName="GlobalSignOutAdminPool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="AdminSignOutApp",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]cognito_idp.admin_create_user(UserPoolId=pid, Username="signoutuser")+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="signoutuser", Password="SignOut1!", Permanent=True)+ auth = cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid, AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "signoutuser", "PASSWORD": "SignOut1!"},+ )+ refresh_token = auth["AuthenticationResult"]["RefreshToken"]+ time.sleep(1.1) # sign-out invalidates tokens issued before now (1s granularity)cognito_idp.admin_user_global_sign_out(UserPoolId=pid, Username="signoutuser")+ # the user's refresh tokens must be invalidated (#1395)+ with pytest.raises(cognito_idp.exceptions.NotAuthorizedException):+ cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid, AuthFlow="REFRESH_TOKEN_AUTH",+ AuthParameters={"REFRESH_TOKEN": refresh_token},+ )def test_cognito_revoke_token(cognito_idp):pid = cognito_idp.create_user_pool(PoolName="RevokePool")["UserPool"]["Id"]@@ -736,7 +762,18 @@ def test_cognito_revoke_token(cognito_idp):AuthParameters={"USERNAME": "revokeuser", "PASSWORD": "RevokePass1!"},)refresh_token = auth["AuthenticationResult"]["RefreshToken"]+ # baseline: the refresh token authenticates before revocation+ cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid, AuthFlow="REFRESH_TOKEN_AUTH",+ AuthParameters={"REFRESH_TOKEN": refresh_token},+ )cognito_idp.revoke_token(Token=refresh_token, ClientId=cid)+ # after RevokeToken it must no longer mint new tokens (#1395)+ with pytest.raises(cognito_idp.exceptions.NotAuthorizedException):+ cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid, AuthFlow="REFRESH_TOKEN_AUTH",+ AuthParameters={"REFRESH_TOKEN": refresh_token},+ )def test_cognito_describe_identity(cognito_identity):resp = cognito_identity.create_identity_pool(diff --git a/tests/test_rds.py b/tests/test_rds.pyindex f70503a6..0e99ff2a 100644--- a/tests/test_rds.py+++ b/tests/test_rds.py@@ -28,6 +28,31 @@ def test_rds_create(rds):assert instances[0]["Engine"] == "postgres"assert "Address" in instances[0]["Endpoint"]+def test_rds_create_rejects_unknown_parameter_group(rds):+ """CreateDBInstance / CreateDBCluster reject a reference to a parameter group+ that doesn't exist; a created group (or a default.* group) is accepted (#1278)."""+ import botocore+ with pytest.raises(botocore.exceptions.ClientError) as ei:+ rds.create_db_instance(+ DBInstanceIdentifier="pg-missing-db", DBInstanceClass="db.t3.micro",+ Engine="postgres", DBParameterGroupName="nope-not-here",+ MasterUsername="u", MasterUserPassword="Passw0rd!23", AllocatedStorage=20)+ assert ei.value.response["Error"]["Code"] == "DBParameterGroupNotFound"++ rds.create_db_parameter_group(+ DBParameterGroupName="pg-real", DBParameterGroupFamily="postgres15", Description="x")+ rds.create_db_instance(+ DBInstanceIdentifier="pg-real-db", DBInstanceClass="db.t3.micro",+ Engine="postgres", DBParameterGroupName="pg-real",+ MasterUsername="u", MasterUserPassword="Passw0rd!23", AllocatedStorage=20)++ with pytest.raises(botocore.exceptions.ClientError) as ec:+ rds.create_db_cluster(+ DBClusterIdentifier="pg-missing-cl", Engine="aurora-postgresql",+ DBClusterParameterGroupName="nope-cluster",+ MasterUsername="u", MasterUserPassword="Passw0rd!23")+ assert ec.value.response["Error"]["Code"] == "DBClusterParameterGroupNotFound"+def test_rds_engines(rds):resp = rds.describe_db_engine_versions(Engine="postgres")assert len(resp["DBEngineVersions"]) > 0diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.pyindex ab7354c6..8d453ac6 100644--- a/tests/test_stepfunctions.py+++ b/tests/test_stepfunctions.py@@ -1531,6 +1531,56 @@ def test_sfn_integration_sqs_send_message(sfn, sqs):assert len(msgs.get("Messages", [])) == 1assert msgs["Messages"][0]["Body"] == "hello from sfn"+def test_sfn_integration_sqs_send_message_wait_for_task_token(sfn, sqs):+ """sqs:sendMessage.waitForTaskToken must actually deliver the message+ (carrying the task token, serialised to JSON) and resume on+ SendTaskSuccess. Previously the task was scheduled but nothing was sent and+ the execution hung forever (#959)."""+ import time++ queue_url = sqs.create_queue(QueueName="sfn-sqs-wfett")["QueueUrl"]++ definition = json.dumps(+ {+ "StartAt": "Send",+ "States": {+ "Send": {+ "Type": "Task",+ "Resource": "arn:aws:states:::sqs:sendMessage.waitForTaskToken",+ "Parameters": {+ "QueueUrl": queue_url,+ "MessageBody": {"task_token.$": "$$.Task.Token"},+ },+ "End": True,+ },+ },+ }+ )+ sm = sfn.create_state_machine(+ name="sfn-sqs-wfett",+ definition=definition,+ roleArn="arn:aws:iam::000000000000:role/R",+ )+ ex = sfn.start_execution(stateMachineArn=sm["stateMachineArn"], input="{}")++ # The integration must fire so a worker can read the token off the queue.+ body = None+ for _ in range(40):+ msgs = sqs.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=1)+ if msgs.get("Messages"):+ body = msgs["Messages"][0]["Body"]+ break+ time.sleep(0.25)+ assert body is not None, "no SQS message delivered — task hung (#959)"+ parsed = json.loads(body) # object MessageBody must be valid JSON, not a repr+ assert parsed["task_token"]++ # The execution is paused at the task; SendTaskSuccess resumes it.+ sfn.send_task_success(+ taskToken=parsed["task_token"], output=json.dumps({"ok": True}))+ desc = _wait_sfn(sfn, ex["executionArn"])+ assert desc["status"] == "SUCCEEDED"+def test_sfn_integration_sns_publish(sfn, sns):"""Task state publishes to SNS via arn:aws:states:::sns:publish."""topic = sns.create_topic(Name="sfn-integ-sns-test")