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
fix(aws parity tests): apply from AWS to merged PRs (#1543)
Nahuel Nuceraca096583e628
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex d26003a6..16fc74bc 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -2142,6 +2142,17 @@ def _create_user_pool(data):if not name:return error_response_json("InvalidParameterException", "PoolName is required.", 400)+ # "You can't require that users provide a value for the attribute" — a+ # custom (or developer-only) schema entry with Required=true is a pool+ # real Cognito refuses to create.+ for raw in data.get("Schema") or []:+ if (isinstance(raw, dict) and raw.get("Required")+ and _schema_attribute_name(raw).startswith(+ (_ATTRIBUTE_CUSTOM_PREFIX, _ATTRIBUTE_DEV_PREFIX))):+ return error_response_json(+ "InvalidParameterException",+ "Required custom attributes are not supported.", 400)+pid = _pool_id()now = _now_epoch()pool = {@@ -2300,6 +2311,10 @@ def _add_custom_attributes(data):return error_response_json("InvalidParameterException",f"{attr['Name']}: Attribute already exists in the schema.", 400)+ if attr.get("Required"):+ return error_response_json(+ "InvalidParameterException",+ "Required custom attributes are not supported.", 400)existing.add(attr["Name"])additions.append(attr)@@ -3227,6 +3242,9 @@ def _admin_initiate_auth(data):return _errif not user.get("Enabled", True):return error_response_json("NotAuthorizedException", "User is disabled.", 400)+ refused = _password_signin_refused(user)+ if refused:+ return refusedif user.get("_password") and user["_password"] != password:return error_response_json("NotAuthorizedException", "Incorrect username or password.", 400)if user.get("UserStatus") == "FORCE_CHANGE_PASSWORD":@@ -3402,6 +3420,9 @@ def _admin_respond_to_auth_challenge(data):if err:del _challenge_sessions[token]return err+ refused = _password_signin_refused(user)+ if refused:+ return refused_append_challenge_to_session(session, "PASSWORD_VERIFIER", True, None, {}, {})session["pending_builtin_challenge"] = Noneuser_attrs = _attr_list_to_dict(user.get("Attributes", []))@@ -3424,6 +3445,9 @@ def _admin_respond_to_auth_challenge(data):user, _err = _resolve_user(pool, username)if _err:return _err+ refused = _password_signin_refused(user)+ if refused:+ return refusedif new_password:user["_password"] = new_passworduser["UserStatus"] = "CONFIRMED"@@ -3544,6 +3568,9 @@ def _initiate_auth(data):return _errif not user.get("Enabled", True):return error_response_json("NotAuthorizedException", "User is disabled.", 400)+ refused = _password_signin_refused(user)+ if refused:+ return refusedif user.get("_password") and user["_password"] != password:return error_response_json("NotAuthorizedException", "Incorrect username or password.", 400)if user.get("UserStatus") == "FORCE_CHANGE_PASSWORD":@@ -3725,6 +3752,9 @@ def _respond_to_auth_challenge(data):if err:del _challenge_sessions[token]return err+ refused = _password_signin_refused(user)+ if refused:+ return refused# Emulator parity with USER_SRP_AUTH: accept Amplify's PASSWORD_CLAIM_* without# full SRP math._append_challenge_to_session(session, "PASSWORD_VERIFIER", True, None, {}, {})@@ -3746,6 +3776,9 @@ def _respond_to_auth_challenge(data):user, _err = _resolve_user(pool, username)if _err:return _err+ refused = _password_signin_refused(user)+ if refused:+ return refusedif new_password:user["_password"] = new_passworduser["UserStatus"] = "CONFIRMED"@@ -3760,6 +3793,9 @@ def _respond_to_auth_challenge(data):user, _err = _resolve_user(pool, username)if _err:return _err+ refused = _password_signin_refused(user)+ if refused:+ return refusedif new_password:user["_password"] = new_passworduser["UserStatus"] = "CONFIRMED"@@ -4568,6 +4604,19 @@ def _admin_link_provider_for_user(data):return json_response({})+def _password_signin_refused(user):+ """The refusal a password sign-in draws for a provider-deactivated local user.++ AdminDisableProviderForUser with ProviderName=Cognito: "they can't use+ their password to sign in", while the profile itself stays (AdminGetUser,+ tokens already issued, and non-password flows are untouched).+ """+ if user.get("_provider_disabled"):+ return error_response_json(+ "NotAuthorizedException", "Incorrect username or password.", 400)+ return None++def _admin_disable_provider_for_user(data):pid = data.get("UserPoolId")pool, err = _resolve_pool(pid)@@ -4578,6 +4627,18 @@ def _admin_disable_provider_for_user(data):if err:return err+ # "To deactivate a local user, set ProviderName to Cognito and the+ # ProviderAttributeName to Cognito_Subject. The ProviderAttributeValue+ # must be user's local username." The user keeps existing but can no+ # longer sign in with their password.+ if user_identifier["ProviderName"] == "Cognito":+ user, err = _resolve_user(pool, user_identifier["ProviderAttributeValue"])+ if err:+ return err+ user["_provider_disabled"] = True+ user["UserLastModifiedDate"] = _now_epoch()+ return json_response({})+links = _provider_links(pool)key = _provider_link_key(user_identifier["ProviderName"],@@ -5550,6 +5611,8 @@ def _authenticate_hosted_ui_user(pool, username, password):status_error = _hosted_ui_user_status_error(user)if status_error:return None, status_error+ if _password_signin_refused(user) is not None:+ return None, "Incorrect username or password."if user.get("_password") != password:return None, "Incorrect username or password."return user, ""diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.pyindex 79febcd9..3c331da4 100644--- a/ministack/services/stepfunctions.py+++ b/ministack/services/stepfunctions.py@@ -325,7 +325,15 @@ def _create_state_machine(data):and data.get("loggingConfiguration",{"level": "OFF", "includeExecutionData": False})== existing["loggingConfiguration"]- and publishes == bool(existing.get("createVersionArn"))):+ and publishes == bool(existing.get("createVersionArn"))+ # AWS's idempotency check also covers versionDescription: a+ # publishing re-create carrying a different description is a+ # different machine, not a retry.+ and (not publishes+ or data.get("versionDescription", "")+ == _state_machine_versions.get(+ existing.get("createVersionArn") or "", {}+ ).get("description", ""))):response = {"stateMachineArn": arn, "creationDate": existing["creationDate"]}if publishes:response["stateMachineVersionArn"] = existing["createVersionArn"]@@ -408,11 +416,17 @@ def _delete_state_machine(data):return json_response({})+# Bookkeeping the machine record carries that is NOT part of AWS's+# DescribeStateMachine response shape and must never reach a caller.+_SM_INTERNAL_KEYS = frozenset({"createVersionArn", "lastVersionNumber"})++def _describe_state_machine(data):arn = data.get("stateMachineArn")sm = _state_machines.get(arn)if sm:- return json_response(sm)+ return json_response({k: v for k, v in sm.items()+ if k not in _SM_INTERNAL_KEYS})# AWS's DescribeStateMachine also accepts a qualified version ARN# (arn:...:stateMachine:<name>:<N>) and returns the snapshot# captured at publish time, with stateMachineArn echoing thediff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex c2b3695b..037b063c 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -7731,3 +7731,66 @@ def test_cognito_admin_link_provider_rejects_an_already_signed_in_user("ProviderAttributeName": "Cognito_Subject","ProviderAttributeValue": "[email protected]"})assert exc_info.value.response["Error"]["Code"] == "AliasExistsException"+++def test_cognito_admin_disable_provider_deactivates_native_user(cognito_idp):+ """"To deactivate a local user, set ProviderName to Cognito and the+ ProviderAttributeName to Cognito_Subject. The ProviderAttributeValue must+ be user's local username." The user then cannot sign in with a password."""+ pid = cognito_idp.create_user_pool(PoolName="NativeDisablePool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="c",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="gina", MessageAction="SUPPRESS")+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="gina", Password="Passw0rd!", Permanent=True)++ cognito_idp.initiate_auth(+ ClientId=cid, AuthFlow="USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "gina", "PASSWORD": "Passw0rd!"})++ cognito_idp.admin_disable_provider_for_user(+ UserPoolId=pid,+ User={"ProviderName": "Cognito", "ProviderAttributeName": "Cognito_Subject",+ "ProviderAttributeValue": "gina"})++ with pytest.raises(ClientError) as exc:+ cognito_idp.initiate_auth(+ ClientId=cid, AuthFlow="USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "gina", "PASSWORD": "Passw0rd!"})+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"++ # SRP is password sign-in too: answering PASSWORD_VERIFIER must refuse.+ chal = cognito_idp.initiate_auth(+ ClientId=cid, AuthFlow="USER_SRP_AUTH",+ AuthParameters={"USERNAME": "gina", "SRP_A": "1" * 16})+ with pytest.raises(ClientError) as exc:+ cognito_idp.respond_to_auth_challenge(+ ClientId=cid, ChallengeName="PASSWORD_VERIFIER",+ Session=chal["Session"],+ ChallengeResponses={"USERNAME": "gina",+ "PASSWORD_CLAIM_SIGNATURE": "sig",+ "PASSWORD_CLAIM_SECRET_BLOCK": "blk",+ "TIMESTAMP": "now"})+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"+++def test_cognito_required_custom_attribute_is_refused(cognito_idp):+ """"You can't require that users provide a value for the attribute" — a+ Required custom attribute is refused at CreateUserPool and at+ AddCustomAttributes, as real Cognito refuses it."""+ with pytest.raises(ClientError) as exc:+ cognito_idp.create_user_pool(+ PoolName="ReqCustomPool",+ Schema=[{"Name": "tenant", "AttributeDataType": "String",+ "Required": True}])+ assert exc.value.response["Error"]["Code"] == "InvalidParameterException"++ pid = cognito_idp.create_user_pool(PoolName="ReqCustomPool2")["UserPool"]["Id"]+ with pytest.raises(ClientError) as exc:+ cognito_idp.add_custom_attributes(+ UserPoolId=pid,+ CustomAttributes=[{"Name": "tenant", "AttributeDataType": "String",+ "Required": True}])+ assert exc.value.response["Error"]["Code"] == "InvalidParameterException"diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.pyindex 729923d6..db410d94 100644--- a/tests/test_stepfunctions.py+++ b/tests/test_stepfunctions.py@@ -4952,6 +4952,45 @@ def test_sfn_create_duplicate_name(sfn):)assert exc.value.response["Error"]["Code"] == "StateMachineAlreadyExists"+def test_sfn_describe_carries_no_internal_bookkeeping(sfn):+ """DescribeStateMachine must not leak createVersionArn / lastVersionNumber,+ which are MiniStack bookkeeping, not AWS response fields."""+ defn = json.dumps({"StartAt": "X", "States": {"X": {"Type": "Pass", "End": True}}})+ arn = sfn.create_state_machine(+ name="sfn-desc-shape-test", definition=defn,+ roleArn="arn:aws:iam::000000000000:role/R", publish=True,+ )["stateMachineArn"]+ desc = sfn.describe_state_machine(stateMachineArn=arn)+ assert "createVersionArn" not in desc+ assert "lastVersionNumber" not in desc+++def test_sfn_create_idempotency_covers_version_description(sfn):+ """AWS's idempotency check includes versionDescription: a publishing+ re-create with a different description raises StateMachineAlreadyExists,+ while the same description answers idempotently."""+ defn = json.dumps({"StartAt": "X", "States": {"X": {"Type": "Pass", "End": True}}})+ first = sfn.create_state_machine(+ name="sfn-dup-verdesc-test", definition=defn,+ roleArn="arn:aws:iam::000000000000:role/R",+ publish=True, versionDescription="v-one",+ )+ again = sfn.create_state_machine(+ name="sfn-dup-verdesc-test", definition=defn,+ roleArn="arn:aws:iam::000000000000:role/R",+ publish=True, versionDescription="v-one",+ )+ assert again["stateMachineArn"] == first["stateMachineArn"]+ assert again["stateMachineVersionArn"] == first["stateMachineVersionArn"]+ with pytest.raises(ClientError) as exc:+ sfn.create_state_machine(+ name="sfn-dup-verdesc-test", definition=defn,+ roleArn="arn:aws:iam::000000000000:role/R",+ publish=True, versionDescription="v-two",+ )+ assert exc.value.response["Error"]["Code"] == "StateMachineAlreadyExists"++def test_sfn_describe_not_found(sfn):"""DescribeStateMachine on non-existent ARN should fail."""with pytest.raises(ClientError) as exc: