Skip to content

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

fix(cognito): accept API-issued refresh tokens at /oauth2/token (#2007)

Pintouchbaeca00ed4ab
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 31af947a..23459e19 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -34,6 +34,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **API Gateway v2 — JWT claims reach a Lambda as strings** — `requestContext.authorizer.jwt.claims` holds every claim as a string, as on AWS: numbers as digits, booleans as `true`/`false` and arrays as their items in brackets, e.g. `[admin dev]`. Typed event models (for example `aws_lambda_events` in Rust, or Go's `map[string]string`) parse the event.
- **Lambda — throttle `retryAfterSeconds` is a string** — a `TooManyRequestsException` returns `retryAfterSeconds` as a string, as the Lambda API model declares, so SDK clients such as the AWS SDK for Rust parse the response as a throttle.
- **Step Functions — `States.TaskFailed` no longer matches `States.Timeout`** — a `Retry` or `Catch` on `States.TaskFailed` also matched a timeout, so a state machine retried or caught a timeout where AWS does not. `States.TaskFailed` now matches every error except `States.Timeout`, as the Step Functions error handling guide describes.
+- **Cognito — `/oauth2/token` refreshes tokens issued by the API** — the `refresh_token` grant answered `invalid_grant` for a refresh token from `InitiateAuth`, `AdminInitiateAuth`, `RespondToAuthChallenge` or a federated sign-in, because it only knew the ones its own Hosted UI code flow issues. It now validates such a token as `REFRESH_TOKEN_AUTH` does, so a revoked or signed-out token, or one issued to another app client, is still refused with `invalid_grant`, and returns a new ID token and access token. A wrong client secret answers `invalid_client`. Contributed by @Pintouch.
- **AppConfig — predefined deployment strategies** — `AppConfig.AllAtOnce`, `AppConfig.Linear50PercentEvery30Seconds`, `AppConfig.Canary10Percent20Minutes` and `AppConfig.Linear20PercentEvery6Minutes` now exist in every account and region and cannot be updated or deleted, as on AWS. A deployment records its strategy's parameters, and `StartDeployment` and `AWS::AppConfig::Deployment` fail with `ResourceNotFoundException` for a strategy that does not exist, where they used to accept any id. Contributed by @koh-sh.
- **RDS — standalone deletion protection and snapshot-tag settings apply immediately** — `ModifyDBInstance` now applies `DeletionProtection` and `CopyTagsToSnapshot` regardless of `ApplyImmediately`, returning the active values without adding these fields to `PendingModifiedValues`. Omitted settings keep their existing values.
- **OpenSearch — data-plane containers are named per account** — a domain's container was named `ministack-opensearch-<region>-<domain>`, so a second account creating a domain of the same name (including an account on another MiniStack sharing the Docker daemon) failed with a Docker name conflict, and the failed create's cleanup removed containers by that name. The names now carry an account and region hash, as RDS's do. Contributed by @skialpine.
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 761f3653..8a448690 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -6453,6 +6453,37 @@ def _handle_new_password_submit(np_token, form):
# -- /oauth2/token (POST) ---------------------------------------------------
+def _oauth2_refresh_api_issued_token(refresh_val: str, cid: str, csec: str):
+ """Refresh tokens minted by InitiateAuth / RespondToAuthChallenge never enter
+ ``_refresh_tokens`` (that registry only holds Hosted UI grants), yet AWS accepts
+ them at /oauth2/token. Validate them with the REFRESH_TOKEN_AUTH core, and the
+ client secret as the registry branch does."""
+ try:
+ claims = _decode_id_token_unverified(refresh_val)
+ except ValueError:
+ claims = None
+ if not isinstance(claims, dict) or claims.get("token_use") != "refresh":
+ return _oauth2_error("invalid_grant", "Invalid refresh token.")
+ pid = str(claims.get("iss", "")).rsplit("/", 1)[-1]
+ pool = _get_pool_unscoped(pid)
+ if not pool:
+ return _oauth2_error("invalid_grant", "Invalid refresh token.")
+ client_id = cid or str(claims.get("client_id", ""))
+ _, _, client = _find_pool_by_client_id(client_id)
+ if client and client.get("ClientSecret") and csec and csec != client["ClientSecret"]:
+ return _oauth2_error("invalid_client", "Invalid client credentials.")
+ result, err = _refresh_auth_result(pool, pid, client_id, refresh_val)
+ if err:
+ return _oauth2_error("invalid_grant", "Invalid refresh token.")
+ resp = {
+ "access_token": result["AccessToken"],
+ "id_token": result["IdToken"],
+ "token_type": "Bearer",
+ "expires_in": 3600,
+ }
+ return 200, {"Content-Type": "application/json"}, json.dumps(resp).encode()
+
+
def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | None = None):
"""/oauth2/token endpoint — supports authorization_code, refresh_token, client_credentials."""
# Parse form-encoded body
@@ -6586,7 +6617,7 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Non
refresh_val = form.get("refresh_token", "")
entry = _refresh_tokens.get(refresh_val)
if not entry:
- return _oauth2_error("invalid_grant", "Invalid refresh token.")
+ return _oauth2_refresh_api_issued_token(refresh_val, cid, csec)
pool_id = entry["pool_id"]
pool = _get_pool_unscoped(pool_id)
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index c511f1f6..dffff661 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -9220,6 +9220,109 @@ def test_cognito_federation_access_token_pretoken_event_has_user_attributes(cogn
assert access["seen_groups"] == "admins"
+def _api_issued_tokens(cognito_idp, pool_name):
+ """A pool with a confidential client and a user signed in through InitiateAuth.
+
+ Returns (pool_id, client, AuthenticationResult).
+ """
+ pid = cognito_idp.create_user_pool(PoolName=pool_name)["UserPool"]["Id"]
+ client = cognito_idp.create_user_pool_client(
+ UserPoolId=pid, ClientName="bff", GenerateSecret=True,
+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
+ )["UserPoolClient"]
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="apirefresh", MessageAction="SUPPRESS",
+ UserAttributes=[
+ {"Name": "email", "Value": "[email protected]"},
+ {"Name": "email_verified", "Value": "true"},
+ ],
+ )
+ cognito_idp.admin_set_user_password(
+ UserPoolId=pid, Username="apirefresh", Password="Refresh-Pass1", Permanent=True)
+ tokens = cognito_idp.initiate_auth(
+ ClientId=client["ClientId"], AuthFlow="USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "apirefresh", "PASSWORD": "Refresh-Pass1"},
+ )["AuthenticationResult"]
+ return pid, client, tokens
+
+
+def _oauth2_refresh(client, refresh_token, client_secret=None):
+ """POST a refresh_token grant to /oauth2/token, authenticating the client with HTTP Basic."""
+ secret = client["ClientSecret"] if client_secret is None else client_secret
+ basic = base64.b64encode(f"{client['ClientId']}:{secret}".encode()).decode()
+ status, _, body = _post_form(
+ f"{ENDPOINT}/oauth2/token",
+ {"grant_type": "refresh_token", "client_id": client["ClientId"], "refresh_token": refresh_token},
+ headers={"Authorization": f"Basic {basic}"},
+ )
+ return status, json.loads(body)
+
+
+def test_cognito_oauth2_token_refreshes_api_issued_refresh_token(cognito_idp):
+ """/oauth2/token refreshes a token issued by InitiateAuth, not only one from the Hosted UI code flow."""
+ _, client, tokens = _api_issued_tokens(cognito_idp, "OAuthApiRefreshPool")
+
+ status, body = _oauth2_refresh(client, tokens["RefreshToken"])
+
+ assert status == 200, body
+ assert set(body) >= {"access_token", "id_token", "token_type", "expires_in"}
+ assert "refresh_token" not in body
+ id_claims = _decode_jwt_claims(body["id_token"])
+ assert id_claims["token_use"] == "id"
+ assert id_claims["email"] == "[email protected]"
+ assert _decode_jwt_claims(body["access_token"])["client_id"] == client["ClientId"]
+ assert cognito_idp.get_user(AccessToken=body["access_token"])["Username"] == "apirefresh"
+
+
+def test_cognito_oauth2_token_rejects_revoked_api_issued_refresh_token(cognito_idp):
+ _, client, tokens = _api_issued_tokens(cognito_idp, "OAuthApiRefreshRevokedPool")
+ assert _oauth2_refresh(client, tokens["RefreshToken"])[0] == 200
+
+ cognito_idp.revoke_token(
+ Token=tokens["RefreshToken"], ClientId=client["ClientId"], ClientSecret=client["ClientSecret"])
+
+ status, body = _oauth2_refresh(client, tokens["RefreshToken"])
+ assert status == 400
+ assert body["error"] == "invalid_grant"
+
+
+def test_cognito_oauth2_token_rejects_api_issued_refresh_token_of_another_client(cognito_idp):
+ pid, client, tokens = _api_issued_tokens(cognito_idp, "OAuthApiRefreshOtherClientPool")
+ other = cognito_idp.create_user_pool_client(
+ UserPoolId=pid, ClientName="other", GenerateSecret=True)["UserPoolClient"]
+ assert _oauth2_refresh(client, tokens["RefreshToken"])[0] == 200
+
+ status, body = _oauth2_refresh(other, tokens["RefreshToken"])
+ assert status == 400
+ assert body["error"] == "invalid_grant"
+
+
+def test_cognito_oauth2_token_rejects_api_issued_refresh_token_with_wrong_secret(cognito_idp):
+ _, client, tokens = _api_issued_tokens(cognito_idp, "OAuthApiRefreshWrongSecretPool")
+
+ status, body = _oauth2_refresh(client, tokens["RefreshToken"], client_secret="wrong")
+
+ assert status == 400
+ assert body["error"] == "invalid_client"
+
+
[email protected]("case", ["garbage", "access_token", "deleted_pool"])
+def test_cognito_oauth2_token_rejects_invalid_refresh_token(cognito_idp, case):
+ """A string that is not a refresh token of an existing pool mints no tokens."""
+ pid, client, tokens = _api_issued_tokens(cognito_idp, f"OAuthApiRefreshInvalid-{case}")
+ token = {
+ "garbage": "not-a-refresh-token",
+ "access_token": tokens["AccessToken"],
+ "deleted_pool": tokens["RefreshToken"],
+ }[case]
+ if case == "deleted_pool":
+ assert _oauth2_refresh(client, token)[0] == 200
+ cognito_idp.delete_user_pool(UserPoolId=pid)
+
+ status, body = _oauth2_refresh(client, token)
+
+ assert status == 400
+ assert body["error"] == "invalid_grant"
# App-client secrets are independent of the stack's IAM AUTH switch.
def _cognito_secret_hash(client, username):