Skip to content

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

fix(cognito): refuse refresh tokens not issued to the pool and client (#1880)

iot-rocket6e0515a18f11
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 549824d1..e4c19406 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,24 +7,24 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+
+- **IoT — `DescribeEventConfigurations` and `UpdateEventConfigurations`** — both answered `Unsupported IoT path`; they now store the registry event switches per account and region, every type starting disabled, an update changing only the types it names, and `creationDate` / `lastModifiedDate` set from the first update on, as on AWS. Contributed by @iot-rocket.
+
### Fixed
- **Cognito — `USER_SRP_AUTH` checks the password** — `PASSWORD_VERIFIER` answered random `SALT` and `SRP_B` values and accepted any response, so a wrong password, a missing `TIMESTAMP` or a disabled or unconfirmed user all got tokens. The challenge now carries SRP-6a parameters with a stable salt per user, and the response is refused with `NotAuthorizedException` unless its signature proves the stored password. `TIMESTAMP` must read `EEE MMM d HH:mm:ss z yyyy` with `UTC` or `GMT` as the zone, the signature is computed over its canonical form, `PASSWORD_CLAIM_SIGNATURE` must be base64, and a temporary password leads to `NEW_PASSWORD_REQUIRED`. A client without `ALLOW_USER_SRP_AUTH`, an unknown user under `LEGACY`, a disabled and an unconfirmed user are refused at `InitiateAuth`. The built-in `PASSWORD_VERIFIER` step of `CUSTOM_WITH_SRP` gets the same check. Contributed by @iot-rocket.
+- **Cognito — refresh tokens are checked against the pool and client** — `REFRESH_TOKEN_AUTH` (`InitiateAuth`, `AdminInitiateAuth`) and `GetTokensFromRefreshToken` issued tokens for the first user in the pool when the refresh token was malformed, from another pool or of a deleted user, and accepted a token issued to another client; they now answer `NotAuthorizedException` with the message AWS gives for each case, and the refresh token from a SAML or OIDC federated sign-in now refreshes the federated user's session. Contributed by @iot-rocket.
+
+- **RDS — `DescribeGlobalClusters` lists clusters as `GlobalClusterMember`** — each cluster was a `<GlobalCluster>` element, so SDKs that match the list member name, such as aws-sdk-go-v2, found none. Contributed by @IamYipi.
+- **Amazon MQ — `DescribeBrokerInstanceOptions` returns `supportedEngineVersions` as strings** — they were `{"name": ...}` objects, which aws-sdk-go-v2 could not deserialize. Contributed by @IamYipi.
+- **EventBridge — `UpdateEventBus` returns the bus** — it answered `EventBusArn` and `LastModifiedTime`, which are not response members, so SDKs returned nothing; it now returns `Arn`, `Name` and the bus's `Description`, `KmsKeyIdentifier`, `DeadLetterConfig` and `LogConfig`. Contributed by @IamYipi.
+- **CloudFormation — `AWS::CodeBuild::Project` stores `Source`, `Artifacts` and `Environment` under CodeBuild API names** — the template's PascalCase members and `BuildSpec` were stored as written, so `BatchGetProjects` dropped them and a build of a stack's project found no buildspec, image or environment variables. Contributed by @IamYipi.
+- **Inspector2 — responses aws-sdk-go-v2 can read** — timestamps are epoch seconds, `ListFilters` returns `criteria`, `ownerId`, `createdAt` and `updatedAt`, `CreateFilter` returns `arn`, and coverage `scanStatus` is `{statusCode, reason}`. Saved state is converted on restore. Contributed by @IamYipi.
+- **EventBridge — `PutEvents` refuses `aws.*` sources** — an entry whose `Source` starts with `aws.` fails with `NotAuthorizedForSourceException` (`Not authorized for the source.`) in its result entry and counts in `FailedEntryCount`, while the rest of the batch is delivered, as on AWS. Events published with an `aws.*` source through `PutEvents` to simulate AWS services now get this error. Contributed by @iot-rocket.
+- **SQS — `QueueUrl` matches the gateway's TLS scheme (`USE_SSL=1`)** — `CreateQueue`/`GetQueueUrl`/`ListQueues` always returned `http://` URLs, and the AWS SDK v3 uses the QueueUrl itself as the request endpoint (`useQueueUrlAsEndpoint` defaults true), so a client handed that URL left the TLS-only gateway. The `AWS::SQS::Queue` CloudFormation provisioner built the same hardcoded scheme and now reuses the shared helper. Contributed by @skialpine.
+- **API Gateway v2 (HTTP API) — a request no stage or route matches answers AWS's exact 404 body** — an unmatched route answered `{"message": "No route found"}` and an unknown stage `{"message": "Stage '…' not found"}`; both now answer `{"message":"Not Found"}` (compact JSON), as AWS does. Contributed by @skialpine.
+- **API Gateway v2 — `apiEndpoint` follows the gateway's TLS scheme** — with `USE_SSL=1` the gateway listener serves only HTTPS, but CreateApi and the `AWS::ApiGatewayV2::Api` CloudFormation resource always returned an `http://` `apiEndpoint`, which nothing answers. They now return `https://`, or `wss://` for a WebSocket API, as AWS does. Without `USE_SSL` the endpoint keeps `http://`. Contributed by @skialpine.
-- **EventBridge — `PutEvents` refuses `aws.*` sources** — an entry whose `Source` starts with `aws.` now fails with `NotAuthorizedForSourceException` in its result entry and counts in `FailedEntryCount`, while the other entries of the batch are still delivered; previously it was dispatched to rules and archives like a custom event.
-- **Bedrock AgentCore — `InvokeAgentRuntime` enforces IAM policies** — with `AUTH=true`, runtime invocations now resolve to `bedrock-agentcore:InvokeAgentRuntime` and authorize against the ARN in the request path, so a policy can allow one runtime and deny another. Previously, the action was not extracted and the request bypassed identity-policy evaluation.
-- **IAM — a negated condition operator is true when its key is absent** — the evaluator treated an absent key as a failed condition for every operator, so a `Deny` guarded by `StringNotEquals`, `StringNotLike`, `ArnNotLike`, `NotIpAddress` or another negated operator never applied to a request without that key. AWS evaluates such a condition as true and denies. The single-valued negated operators now do the same, while `ForAnyValue` and the affirmative operators still fail on an absent key. Contributed by @iot-rocket.
-- **KMS — `GenerateDataKey` returns `KeyMaterialId`** — requests without `Recipient` now include the identifier of the wrapping key material. The identifier remains stable across requests and persistence reloads, and changes when the wrapping material changes. Fixes #1853.
-- **Secrets Manager — `BatchGetSecretValue` returns only the secrets the caller may read** — under `AUTH=true` a grant on `secretsmanager:BatchGetSecretValue` alone returned every secret in the request, and `Filters` were ignored, so a filtered call returned the whole store. Each secret now needs `secretsmanager:GetSecretValue` and lands in `Errors` as `AccessDeniedException` without it, a call by `Filters` also needs `secretsmanager:ListSecrets`, and the filters select the secrets as in `ListSecrets`. Contributed by @iot-rocket.
-- **CloudFormation — change set members follow the action** — `Add` and `Remove` changes carried `Replacement: False`, a `Remove` had no physical id, `PolicyAction` was never sent and a `Metadata` or policy detail had no `RequiresRecreation`. `Remove` and `Modify` now name the physical resource, a `Remove` answers `PolicyAction: Delete` and a replacing `Modify` `ReplaceAndDelete` unless the resource retains or snapshots, and attribute details answer `Never`. Contributed by @iot-rocket.
-- **CloudFormation — `AWS::SQS::Queue` applies every queue property** — `RedrivePolicy`, `RedriveAllowPolicy`, `KmsMasterKeyId`, `KmsDataKeyReusePeriodSeconds`, `SqsManagedSseEnabled`, `DeduplicationScope` and `FifoThroughputLimit` were dropped on create and update, so a dead-letter queue declared in a template never received messages, and a value SQS refuses now fails the resource instead of being stored. Contributed by @iot-rocket.
-- **Lambda — Docker executor honors timeouts above 300 seconds** — pass the configured `Timeout` to AWS RIE through `AWS_LAMBDA_FUNCTION_TIMEOUT`, preventing its default 300-second limit from ending longer invocations early. Timeout updates recycle warm containers so the RIE deadline follows the new configuration (#1844).
-- **KMS — `GenerateDataKey` returns `KeyMaterialId`** — requests without `Recipient` now include the identifier of the wrapping key material. The identifier remains stable across requests and persistence reloads, and changes when the wrapping material changes. Fixes #1853.
-- **CloudFormation — a nested stack's update deletes the resources its template drops** — a resource removed from the child template, or created by a failed child update that was rolled back, stayed in its service and in the nested stack's resource list. Contributed by @iot-rocket.
-- **SQS — `QueueUrl` matches the gateway's TLS scheme (`USE_SSL=1`)** — `CreateQueue`/`GetQueueUrl`/`ListQueues` always returned `http://` URLs, and the AWS SDK v3 uses the QueueUrl itself as the request endpoint (`useQueueUrlAsEndpoint` defaults true), so a client handed that URL left the TLS-only gateway. The `AWS::SQS::Queue` CloudFormation provisioner built the same hardcoded scheme and now reuses the shared helper.
-- **API Gateway v2 (HTTP API) — an unmatched route answers AWS's exact 404 body** — a request with no matching route answered `{"message": "No route found"}`; AWS answers `{"message":"Not Found"}` (compact JSON, no space after the colon). REST API (v1) is unaffected — it already answers a route miss with its own `403 MISSING_AUTHENTICATION_TOKEN` gateway response, not this literal.
-- **API Gateway v2 — `apiEndpoint` follows the gateway's TLS scheme** — with `USE_SSL=1` the gateway listener serves only HTTPS, but CreateApi and the `AWS::ApiGatewayV2::Api` CloudFormation resource always returned an `http://` `apiEndpoint`, which nothing answers. They now return `https://`, or `wss://` for a WebSocket API, as AWS does. Without `USE_SSL` the endpoint keeps `http://`.
-
-- **IoT — `DescribeEventConfigurations` and `UpdateEventConfigurations`** — both answered `Unsupported IoT path`; they now store the registry event switches per account and region, every type starting disabled, an update changing only the types it names, and `creationDate` / `lastModifiedDate` set from the first update on, as on AWS.
## [1.5.19] — 2026-09-30
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 2acc86d3..2b3e3f9e 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -3655,22 +3655,9 @@ def _admin_initiate_auth(data):
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:
- # Fall back to first user if token can't be decoded (e.g. externally issued token)
- 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, refresh_token)
+ if err:
+ return err
return json_response({"AuthenticationResult": result})
if auth_flow == "CUSTOM_AUTH":
@@ -3873,13 +3860,20 @@ def _refresh_auth_result(pool, pid, cid, refresh_token):
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.
+ try:
+ claims = _decode_id_token_unverified(refresh_token)
+ except (ValueError, AttributeError):
+ claims = None
+ if (not isinstance(claims, dict) or claims.get("token_use") != "refresh"
+ or str(claims.get("iss", "")).rsplit("/", 1)[-1] != pid):
+ return None, error_response_json("NotAuthorizedException", "Invalid Refresh Token", 400)
+ if claims.get("client_id") != cid:
+ return None, error_response_json("NotAuthorizedException",
+ "Refresh Token has different Client", 400)
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]
+ return None, error_response_json("NotAuthorizedException",
+ "The user has been deleted for the associated refresh token", 400)
if _refresh_token_revoked(refresh_token, user):
return None, error_response_json("NotAuthorizedException",
"Refresh Token has been revoked", 400)
@@ -6413,7 +6407,7 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Non
trigger_source="TokenGeneration_HostedAuth")
id_token = _fake_token(sub, pool_id, effective_client_id, "id", username, user_attrs=user_attrs,
trigger_source="TokenGeneration_HostedAuth")
- refresh_token = secrets.token_urlsafe(48)
+ refresh_token = _fake_token(sub, pool_id, effective_client_id, "refresh")
return json_response({
"id_token": id_token,
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index 06337451..ab3b9282 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -1213,6 +1213,53 @@ def test_cognito_refresh_token_alias(cognito_idp):
assert "AccessToken" in refresh["AuthenticationResult"]
assert "RefreshToken" not in refresh["AuthenticationResult"]
[email protected]("case", ["garbage", "access_token", "other_pool", "other_client", "deleted_user"])
[email protected]("api", ["initiate_auth", "admin_initiate_auth", "get_tokens_from_refresh_token"])
+def test_cognito_refresh_token_not_issued_to_client_refused(cognito_idp, api, case):
+ """A refresh token this pool and client did not issue mints no tokens for another user."""
+ flows = ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"]
+ pid, other_pid = (cognito_idp.create_user_pool(PoolName=f"RefreshRefused{n}")["UserPool"]["Id"] for n in "AB")
+ cid, cid2, other_cid = (
+ cognito_idp.create_user_pool_client(UserPoolId=p, ClientName="app", ExplicitAuthFlows=flows)
+ ["UserPoolClient"]["ClientId"] for p in (pid, pid, other_pid)
+ )
+ for p, name in [(pid, "first"), (pid, "second"), (other_pid, "other")]:
+ cognito_idp.admin_create_user(UserPoolId=p, Username=name)
+ cognito_idp.admin_set_user_password(UserPoolId=p, Username=name, Password="RefreshPass1!", Permanent=True)
+
+ def login(client_id, username):
+ return cognito_idp.initiate_auth(
+ ClientId=client_id, AuthFlow="USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": username, "PASSWORD": "RefreshPass1!"},
+ )["AuthenticationResult"]
+
+ tokens = login(cid, "second")
+ client_id, token = {
+ "garbage": (cid, "not-a-refresh-token"),
+ "access_token": (cid, tokens["AccessToken"]),
+ "other_pool": (cid, login(other_cid, "other")["RefreshToken"]),
+ "other_client": (cid2, tokens["RefreshToken"]),
+ "deleted_user": (cid, tokens["RefreshToken"]),
+ }[case]
+ if case == "deleted_user":
+ cognito_idp.admin_delete_user(UserPoolId=pid, Username="second")
+ calls = {
+ "initiate_auth": lambda: cognito_idp.initiate_auth(
+ ClientId=client_id, AuthFlow="REFRESH_TOKEN_AUTH", AuthParameters={"REFRESH_TOKEN": token}),
+ "admin_initiate_auth": lambda: cognito_idp.admin_initiate_auth(
+ UserPoolId=pid, ClientId=client_id, AuthFlow="REFRESH_TOKEN_AUTH",
+ AuthParameters={"REFRESH_TOKEN": token}),
+ "get_tokens_from_refresh_token": lambda: cognito_idp.get_tokens_from_refresh_token(
+ ClientId=client_id, RefreshToken=token),
+ }
+ with pytest.raises(ClientError) as exc:
+ calls[api]()
+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"
+ assert exc.value.response["Error"]["Message"] == {
+ "other_client": "Refresh Token has different Client",
+ "deleted_user": "The user has been deleted for the associated refresh token",
+ }.get(case, "Invalid Refresh Token")
+
def test_cognito_respond_to_auth_challenge_new_password(cognito_idp):
"""RespondToAuthChallenge with NEW_PASSWORD_REQUIRED confirms the user."""
pid = cognito_idp.create_user_pool(PoolName="ChallengePool")["UserPool"]["Id"]
@@ -2187,6 +2234,7 @@ def test_cognito_oauth2_authorize_invalid_client(cognito_idp):
def test_cognito_saml_full_flow(cognito_idp):
"""Full SAML flow: authorize → SAML response → token exchange → user created."""
pid, cid = _setup_saml_pool(cognito_idp)
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="local-first", MessageAction="SUPPRESS")
# Step 1: GET /oauth2/authorize → extract RelayState from redirect Location
url = (
@@ -2265,6 +2313,12 @@ def test_cognito_saml_full_flow(cognito_idp):
assert attrs.get("email") == "[email protected]"
assert attrs.get("name") == "John Doe"
+ # Step 5: the federated refresh token refreshes the federated user's session
+ refreshed = cognito_idp.initiate_auth(
+ ClientId=cid, AuthFlow="REFRESH_TOKEN_AUTH", AuthParameters={"REFRESH_TOKEN": tokens["refresh_token"]},
+ )["AuthenticationResult"]
+ assert cognito_idp.get_user(AccessToken=refreshed["AccessToken"])["Username"] == "[email protected]"
+
def test_cognito_saml_presignup_lambda_rejects_unauthorized_user(cognito_idp, lam):
"""PreSignUp_ExternalProvider trigger fails closed: an uninvited federated