Skip to content

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

fix(cognito): AdminDisableUser revokes the user's tokens under AUTH=true (#2273)

iot-rocket74cdb195af59
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 01ca8263..6c3241ee 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **Cognito — `AdminDisableUser` revokes the user's tokens under `AUTH=true`** — a disabled user's access and refresh tokens kept working, also after `AdminEnableUser`; with `AUTH=true` they are now refused with `User is disabled.` while the user is disabled, and the sessions from before stay revoked once the user is enabled again (`Access Token has been revoked`, `Refresh Token has been revoked`, `invalid_grant` at `/oauth2/token`), as AWS does, and the access token of a deleted user gets `UserNotFoundException: User does not exist.` Contributed by @iot-rocket.
- **Cognito — `/oauth2/userInfo` requires the `openid` scope under `AUTH=true`** — an access token without the `openid` scope, such as the token of a user pool API sign-in or of a Hosted UI grant of `email` alone, returned the user's attributes; with `AUTH=true` it now answers 401 `invalid_token` `Access token does not contain the 'openid' scope` once the token, its `username` and the user have passed the other checks. Contributed by @iot-rocket.
- **Cognito — `/oauth2/userInfo` verifies the access token under `AUTH=true`** — the endpoint returned the user's attributes for any JWT carrying a user's `sub`, including an ID token, a token with an altered payload, a revoked or expired token and the token of a disabled or deleted user; with `AUTH=true` it now answers 401 `invalid_token` with AWS's `error_description` and `WWW-Authenticate` for each case. Contributed by @iot-rocket.
- **Cognito — `/oauth2/userInfo` verifies the access token under `AUTH=true`** — the endpoint returned the user's attributes for any JWT carrying a user's `sub`, including an ID token, a token with an altered payload, a revoked or expired token and the token of a disabled or deleted user; with `AUTH=true` it now answers 401 `invalid_token` with AWS's `error_description` and `WWW-Authenticate` for each case. Contributed by @iot-rocket.
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 03d1e7f6..0781f538 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -1301,8 +1301,16 @@ def _signature_valid(token: str) -> bool:
return True
+def _token_owner(claims: dict):
+ """The user named by a token's iss and username, False if the pool lacks it, None without either."""
+ pool = _user_pools.get(str(claims.get("iss", "")).rsplit("/", 1)[-1])
+ if not pool or not claims.get("username"):
+ return None
+ return pool["_users"].get(claims["username"]) or False
+
+
def _access_token_error(data: dict):
- """The NotAuthorizedException for an AccessToken AWS would not accept, or None."""
+ """The error for an AccessToken AWS would not accept, or None."""
token = data.get("AccessToken")
if not token or not isinstance(token, str):
return None
@@ -1315,6 +1323,10 @@ def _access_token_error(data: dict):
message = "Could not verify signature for Access Token"
elif not isinstance(claims.get("exp"), (int, float)) or time.time() >= claims["exp"]:
message = "Access Token has expired"
+ elif (user := _token_owner(claims)) is False:
+ return error_response_json("UserNotFoundException", "User does not exist.", 400)
+ elif user and not user.get("Enabled", True):
+ message = "User is disabled."
elif claims.get("origin_jti") in _revoked_tokens:
message = "Access Token has been revoked"
elif _API_TOKEN_SCOPE not in str(claims.get("scope", _API_TOKEN_SCOPE)).split():
@@ -3828,6 +3840,13 @@ def _admin_disable_user(data):
return err
user["Enabled"] = False
user["UserLastModifiedDate"] = _now_epoch()
+ from ministack.app import AUTH
+ if AUTH:
+ # Every session ends: its tokens stay revoked after AdminEnableUser.
+ _revoked_tokens.update(user.pop("_origin_jtis", []))
+ for tok in [t for t, e in _refresh_tokens.items()
+ if e.get("username") == user["Username"] and e.get("pool_id") == pid]:
+ del _refresh_tokens[tok]
return json_response({})
@@ -4419,7 +4438,10 @@ def _refresh_auth_user(pool, pid, cid, refresh_token):
if not user:
return None, error_response_json("NotAuthorizedException",
"The user has been deleted for the associated refresh token", 400)
- if _refresh_token_revoked(refresh_token, user):
+ from ministack.app import AUTH
+ if AUTH and not user.get("Enabled", True):
+ return None, error_response_json("NotAuthorizedException", "User is disabled.", 400)
+ if _refresh_token_revoked(refresh_token, user) or (AUTH and claims.get("origin_jti") in _revoked_tokens):
return None, error_response_json("NotAuthorizedException",
"Refresh Token has been revoked", 400)
return user, None
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index ccc8e3d5..685984c6 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -1937,6 +1937,93 @@ def test_cognito_sign_out_and_revoke_token_revoke_access_tokens_under_auth(monke
assert call("GetUser", AccessToken=other["AccessToken"])["Username"] == "bob"
+def _disable_user_pool(cognito_idp):
+ """testuser and erin in a pool with a public client; returns (pool id, client id, sign-in, GetUser, refresh)."""
+ client = _scoped_code_client(cognito_idp, ["openid", "aws.cognito.signin.user.admin"])
+ pid, cid = client["UserPoolId"], client["ClientId"]
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="erin", MessageAction="SUPPRESS")
+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="erin", Password="TestPass1!", Permanent=True)
+
+ def outcome(call, **kwargs):
+ try:
+ return call(**kwargs)
+ except ClientError as e:
+ return e.response["Error"]["Code"], e.response["Error"]["Message"]
+
+ def sign_in(username):
+ return cognito_idp.admin_initiate_auth(
+ UserPoolId=pid, ClientId=cid, AuthFlow="ADMIN_USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": username, "PASSWORD": "TestPass1!"})["AuthenticationResult"]
+
+ def get_user(token):
+ result = outcome(cognito_idp.get_user, AccessToken=token)
+ return result["Username"] if isinstance(result, dict) else result
+
+ def refresh(token):
+ """REFRESH_TOKEN_AUTH, GetTokensFromRefreshToken and the token endpoint's refresh grant: "OK" or the error."""
+ outcomes = [outcome(cognito_idp.initiate_auth, ClientId=cid, AuthFlow="REFRESH_TOKEN_AUTH",
+ AuthParameters={"REFRESH_TOKEN": token}),
+ outcome(cognito_idp.get_tokens_from_refresh_token, ClientId=cid, RefreshToken=token)]
+ status, _, body = _post_form(f"{ENDPOINT}/oauth2/token", {
+ "grant_type": "refresh_token", "client_id": cid, "refresh_token": token})
+ return ["OK" if isinstance(o, dict) else o for o in outcomes] + [
+ "OK" if status == 200 else json.loads(body)["error"]]
+
+ return pid, cid, sign_in, get_user, refresh
+
+
+def test_cognito_disable_user_revokes_tokens(auth_enabled, cognito_idp):
+ pid, cid, sign_in, get_user, refresh = _disable_user_pool(cognito_idp)
+ bob, erin = sign_in("testuser"), sign_in("erin")
+ hosted = _code_grant_tokens(cognito_idp, cid, "openid aws.cognito.signin.user.admin")
+ refreshed = cognito_idp.initiate_auth(ClientId=cid, AuthFlow="REFRESH_TOKEN_AUTH", AuthParameters={
+ "REFRESH_TOKEN": bob["RefreshToken"]})["AuthenticationResult"]["AccessToken"]
+ access_tokens = (bob["AccessToken"], refreshed, hosted["access_token"])
+ refresh_tokens = (bob["RefreshToken"], hosted["refresh_token"])
+ assert refresh(hosted["refresh_token"]) == ["OK"] * 3
+
+ # While disabled every token of the user is refused as disabled, refresh tokens too.
+ cognito_idp.admin_disable_user(UserPoolId=pid, Username="testuser")
+ disabled = ("NotAuthorizedException", "User is disabled.")
+ for token in access_tokens:
+ assert get_user(token) == (disabled if auth_enabled else "testuser")
+ update = {"AccessToken": bob["AccessToken"], "UserAttributes": [{"Name": "name", "Value": "Bob"}]}
+ if auth_enabled:
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.update_user_attributes(**update)
+ assert (exc.value.response["Error"]["Code"], exc.value.response["Error"]["Message"]) == disabled
+ else:
+ cognito_idp.update_user_attributes(**update)
+ for token in refresh_tokens:
+ assert refresh(token) == ([disabled, disabled, "invalid_grant"] if auth_enabled else ["OK"] * 3)
+ assert get_user(erin["AccessToken"]) == "erin"
+
+ # AdminEnableUser lets the user sign in again; the sessions from before stay revoked.
+ cognito_idp.admin_enable_user(UserPoolId=pid, Username="testuser")
+ revoked = ("NotAuthorizedException", "Access Token has been revoked")
+ for token in access_tokens:
+ assert get_user(token) == (revoked if auth_enabled else "testuser")
+ refresh_revoked = ("NotAuthorizedException", "Refresh Token has been revoked")
+ for token in refresh_tokens:
+ assert refresh(token) == ([refresh_revoked, refresh_revoked, "invalid_grant"] if auth_enabled else ["OK"] * 3)
+ later = sign_in("testuser")
+ assert get_user(later["AccessToken"]) == "testuser"
+ assert refresh(later["RefreshToken"]) == ["OK"] * 3
+
+
+def test_cognito_deleted_user_access_token(auth_enabled, cognito_idp):
+ pid, _, sign_in, get_user, _ = _disable_user_pool(cognito_idp)
+ old = sign_in("erin")["AccessToken"]
+ cognito_idp.admin_delete_user(UserPoolId=pid, Username="erin")
+ invalid = ("NotAuthorizedException", "Invalid access token.")
+ assert get_user(old) == (("UserNotFoundException", "User does not exist.") if auth_enabled else invalid)
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="erin", MessageAction="SUPPRESS")
+ # The same username belongs to another user now.
+ assert get_user(old) == invalid
+
+
def test_cognito_expired_access_token_refused_under_auth(monkeypatch):
mod, call = _idp_in_process(monkeypatch, auth=True)
_, cid, sign_in = _password_client_with_users(