Skip to content

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

feat(amplify): update for cognito 6.15 (#1172)

Nahuel Nucera241671342c73
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index fd4bd6bc..25741739 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -1495,6 +1495,7 @@ async def _dispatch_idp(action: str, data: dict):
"AdminInitiateAuth": _admin_initiate_auth,
"AdminRespondToAuthChallenge": _admin_respond_to_auth_challenge,
"InitiateAuth": _initiate_auth,
+ "GetTokensFromRefreshToken": _get_tokens_from_refresh_token,
"RespondToAuthChallenge": _respond_to_auth_challenge,
"GlobalSignOut": _global_sign_out,
"RevokeToken": _revoke_token,
@@ -2857,6 +2858,62 @@ def _admin_respond_to_auth_challenge(data):
return error_response_json("InvalidParameterException", f"Unsupported challenge: {challenge_name}", 400)
+def _pool_for_client(cid):
+ """Return (pool, pool_id) for the client id, or (None, None)."""
+ for p_id, p in _user_pools.items():
+ if cid in p["_clients"]:
+ return p, p_id
+ return None, None
+
+
+def _refresh_auth_result(pool, pid, cid, refresh_token):
+ """Shared REFRESH_TOKEN_AUTH core. Returns (auth_result_dict, error_response);
+ exactly one is non-None. Used by InitiateAuth's REFRESH_TOKEN_AUTH branch and
+ by GetTokensFromRefreshToken so both mint tokens identically."""
+ if not refresh_token:
+ return None, error_response_json("NotAuthorizedException", "Refresh token is missing.", 400)
+ # Decode stub token to find the correct user by sub.
+ user = _user_from_token(refresh_token, pool)
+ if not user:
+ users = list(pool["_users"].values())
+ if not users:
+ return None, error_response_json("NotAuthorizedException", "No users in pool.", 400)
+ user = users[0]
+ if _refresh_token_revoked(refresh_token, user):
+ return None, error_response_json("NotAuthorizedException",
+ "Refresh Token has been revoked", 400)
+ result = _build_auth_result(pid, cid, user, trigger_source="TokenGeneration_RefreshTokens")
+ result.pop("RefreshToken", None) # AWS doesn't return a new refresh token here
+ return result, None
+
+
+def _get_tokens_from_refresh_token(data):
+ """GetTokensFromRefreshToken — the only session-refresh path aws-amplify
+ v6.15+ uses (added by AWS in 2025 alongside refresh token rotation). Accepts
+ a top-level ``RefreshToken``/``ClientId`` and reuses the REFRESH_TOKEN_AUTH
+ core, returning the same ``AuthenticationResult`` shape.
+
+ Refresh token rotation (reissuing the RefreshToken and the
+ ``RefreshTokenReuseException`` grace period) is not modeled; with rotation
+ disabled — the pool default — AWS returns no new refresh token here, so the
+ result carries AccessToken/IdToken/ExpiresIn/TokenType only."""
+ cid = data.get("ClientId")
+ refresh_token = data.get("RefreshToken")
+ if not cid:
+ return error_response_json("InvalidParameterException",
+ "Missing required parameter ClientId", 400)
+ if not refresh_token:
+ return error_response_json("InvalidParameterException",
+ "Missing required parameter RefreshToken", 400)
+ pool, pid = _pool_for_client(cid)
+ if not pool:
+ return error_response_json("ResourceNotFoundException", f"Client {cid} not found.", 400)
+ result, err = _refresh_auth_result(pool, pid, cid, refresh_token)
+ if err:
+ return err
+ return json_response({"AuthenticationResult": result})
+
+
def _initiate_auth(data):
"""Public InitiateAuth — same logic as AdminInitiateAuth but no UserPoolId required."""
cid = data.get("ClientId")
@@ -2901,22 +2958,9 @@ def _initiate_auth(data):
return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})
if auth_flow in ("REFRESH_TOKEN_AUTH", "REFRESH_TOKEN"):
- refresh_token = auth_params.get("REFRESH_TOKEN", "")
- if not refresh_token:
- return error_response_json("NotAuthorizedException", "Refresh token is missing.", 400)
- # Decode stub token to find the correct user by sub
- user = _user_from_token(refresh_token, pool)
- if not user:
- users = list(pool["_users"].values())
- 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,
- trigger_source="TokenGeneration_RefreshTokens")
- result.pop("RefreshToken", None) # AWS doesn't return a new refresh token here
+ result, err = _refresh_auth_result(pool, pid, cid, auth_params.get("REFRESH_TOKEN", ""))
+ if err:
+ return err
return json_response({"AuthenticationResult": result})
# USER_SRP_AUTH — return SRP challenge stub
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 65fa9154..f38f87b8 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -3399,6 +3399,100 @@ Outputs:
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+def test_cfn_cognito_user_pool_lambda_config(cfn, cognito_idp):
+ """AWS::Cognito::UserPool's LambdaConfig property is honored when the pool
+ is provisioned via CloudFormation, not just via the raw CreateUserPool API.
+
+ _cognito_user_pool_create previously built the pool's state dict without
+ ever reading props["LambdaConfig"], so a CFN-provisioned pool's Lambda
+ triggers (PreTokenGeneration here, but the gap applied to all of them)
+ were silently dropped — the trigger Lambda was never invoked and tokens
+ were issued unmodified, even though the identical raw API call already
+ honored LambdaConfig correctly.
+ """
+ template = """
+AWSTemplateFormatVersion: '2010-09-09'
+Resources:
+ TriggerRole:
+ Type: AWS::IAM::Role
+ Properties:
+ AssumeRolePolicyDocument:
+ Version: '2012-10-17'
+ Statement:
+ - Effect: Allow
+ Principal:
+ Service: lambda.amazonaws.com
+ Action: sts:AssumeRole
+ TriggerFn:
+ Type: AWS::Lambda::Function
+ Properties:
+ Runtime: python3.12
+ Handler: index.handler
+ Role: !GetAtt TriggerRole.Arn
+ Code:
+ ZipFile: |
+ def handler(event, context):
+ event['response']['claimsOverrideDetails'] = {
+ 'claimsToAddOrOverride': {'injected_claim': 'from-cfn-trigger'},
+ }
+ return event
+ Pool:
+ Type: AWS::Cognito::UserPool
+ Properties:
+ UserPoolName: cfn-pretoken-pool
+ LambdaConfig:
+ PreTokenGeneration: !GetAtt TriggerFn.Arn
+ Client:
+ Type: AWS::Cognito::UserPoolClient
+ Properties:
+ UserPoolId: !Ref Pool
+ ExplicitAuthFlows:
+ - ALLOW_USER_PASSWORD_AUTH
+Outputs:
+ PoolId:
+ Value: !Ref Pool
+ ClientId:
+ Value: !Ref Client
+"""
+ stack_name = "cfn-cognito-pretoken"
+ try:
+ cfn.delete_stack(StackName=stack_name)
+ except Exception:
+ pass
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ _wait_stack(cfn, stack_name)
+
+ stack = cfn.describe_stacks(StackName=stack_name)["Stacks"][0]
+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}
+ pool_id, client_id = outputs["PoolId"], outputs["ClientId"]
+
+ desc = cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"]
+ assert desc["LambdaConfig"]["PreTokenGeneration"]
+
+ cognito_idp.admin_create_user(
+ UserPoolId=pool_id, Username="pretoken-user",
+ TemporaryPassword="Temp1234!", MessageAction="SUPPRESS",
+ )
+ cognito_idp.admin_set_user_password(
+ UserPoolId=pool_id, Username="pretoken-user", Password="Pwd1234!", Permanent=True,
+ )
+ tok = cognito_idp.initiate_auth(
+ ClientId=client_id, AuthFlow="USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "pretoken-user", "PASSWORD": "Pwd1234!"},
+ )["AuthenticationResult"]
+
+ id_payload = tok["IdToken"].split(".")[1]
+ id_payload += "=" * (-len(id_payload) % 4)
+ id_claims = json.loads(base64.urlsafe_b64decode(id_payload))
+ assert id_claims.get("injected_claim") == "from-cfn-trigger"
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.describe_user_pool(UserPoolId=pool_id)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
# ---------------------------------------------------------------------------
# ApiGatewayV2 Integration + Route provisioners
# ---------------------------------------------------------------------------
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index c7305f20..223df23b 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -518,6 +518,62 @@ def test_cognito_global_sign_out(cognito_idp):
AuthParameters={"REFRESH_TOKEN": refresh_token},
)
+
+def test_cognito_get_tokens_from_refresh_token(cognito_idp):
+ """aws-amplify v6.15+ refreshes sessions only via GetTokensFromRefreshToken;
+ it returns the same AuthenticationResult shape as REFRESH_TOKEN_AUTH."""
+ pid = cognito_idp.create_user_pool(PoolName="GTFRTPool")["UserPool"]["Id"]
+ cid = cognito_idp.create_user_pool_client(
+ UserPoolId=pid, ClientName="GTFRTApp",
+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
+ )["UserPoolClient"]["ClientId"]
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="ada")
+ cognito_idp.admin_set_user_password(
+ UserPoolId=pid, Username="ada", Password="AdaPass1!", Permanent=True)
+ auth = cognito_idp.initiate_auth(
+ ClientId=cid, AuthFlow="USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "ada", "PASSWORD": "AdaPass1!"},
+ )["AuthenticationResult"]
+
+ result = cognito_idp.get_tokens_from_refresh_token(
+ ClientId=cid, RefreshToken=auth["RefreshToken"],
+ )["AuthenticationResult"]
+ assert result["AccessToken"]
+ assert result["IdToken"]
+ assert result["TokenType"] == "Bearer"
+ assert result["ExpiresIn"] > 0
+ # With rotation disabled (the pool default) AWS returns no new refresh token.
+ assert "RefreshToken" not in result
+ # The refreshed access token is usable.
+ assert cognito_idp.get_user(AccessToken=result["AccessToken"])["Username"] == "ada"
+
+
+def test_cognito_get_tokens_from_refresh_token_unknown_client(cognito_idp):
+ with pytest.raises(cognito_idp.exceptions.ResourceNotFoundException):
+ cognito_idp.get_tokens_from_refresh_token(ClientId="nonexistent", RefreshToken="dummy")
+
+
+def test_cognito_get_tokens_from_refresh_token_revoked(cognito_idp):
+ """A globally-signed-out refresh token is rejected, matching REFRESH_TOKEN_AUTH."""
+ pid = cognito_idp.create_user_pool(PoolName="GTFRTRevokePool")["UserPool"]["Id"]
+ cid = cognito_idp.create_user_pool_client(
+ UserPoolId=pid, ClientName="GTFRTRevokeApp",
+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
+ )["UserPoolClient"]["ClientId"]
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="grace")
+ cognito_idp.admin_set_user_password(
+ UserPoolId=pid, Username="grace", Password="GracePass1!", Permanent=True)
+ auth = cognito_idp.initiate_auth(
+ ClientId=cid, AuthFlow="USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "grace", "PASSWORD": "GracePass1!"},
+ )["AuthenticationResult"]
+ time.sleep(1.1)
+ cognito_idp.global_sign_out(AccessToken=auth["AccessToken"])
+ with pytest.raises(cognito_idp.exceptions.NotAuthorizedException):
+ cognito_idp.get_tokens_from_refresh_token(
+ ClientId=cid, RefreshToken=auth["RefreshToken"])
+
+
def test_cognito_admin_confirm_signup(cognito_idp):
pid = cognito_idp.create_user_pool(PoolName="AdminConfirmPool")["UserPool"]["Id"]
cid = cognito_idp.create_user_pool_client(UserPoolId=pid, ClientName="AdminConfirmApp")["UserPoolClient"][