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(cognito): verify access tokens and their lifetime under AUTH=true (#2149)
iot-rocket63fcce887142
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7561f4b2..6428f250 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **Cognito — token lifetimes follow the app client** — access and ID tokens, `ExpiresIn` and the `/oauth2/token` `expires_in` were always one hour; they now follow the client's `AccessTokenValidity`, `IdTokenValidity` and `TokenValidityUnits` (one hour when unset, as on AWS), a client created without the two validities no longer reports `60` for them, and an expired token is refused by API Gateway's Cognito and JWT authorizers and, with `AUTH=true`, an expired access token by Cognito with `Access Token has expired`. Contributed by @iot-rocket.+- **Cognito — access tokens are verified under `AUTH=true`** — `GetUser` and the other calls that take an `AccessToken` accepted any JWT carrying a user's `sub`, including an ID token, a token with an altered payload and a token revoked by `GlobalSignOut`, `AdminUserGlobalSignOut` or `RevokeToken`; with `AUTH=true` they now answer `NotAuthorizedException` with `Invalid Access Token`, `Could not verify signature for Access Token` or `Access Token has been revoked`, as AWS does. Contributed by @iot-rocket.+- **IAM / CloudFormation — user and role tag keys** — IAM user and role tag keys now compare without case while preserving their spelling. Create and tag operations reject duplicate keys, untag operations match keys regardless of case, and CloudFormation validates duplicate keys and merges stack tags accordingly. User tag updates also compare keys without case. Other resource types retain case-sensitive tag handling.- **Signer — signing material checks in `PutSigningProfile` under `AUTH=true`** — `PutSigningProfile` accepted any certificate ARN, or no `signingMaterial` at all, on every platform; with `AUTH=true` the IoT and FreeRTOS platforms now refuse a profile without `signingMaterial` and a certificate ARN that is malformed, in another region or account, unknown to ACM or not issued, and the Lambda and Notation platforms refuse any `signingMaterial`, with AWS's errors. Contributed by @iot-rocket.diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 408a63fe..031812c8 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -6792,14 +6792,14 @@ def _cognito_user_pool_delete(physical_id, props):# UpdateUserPoolClient's parameters, with the value a dropped property# reverts to: what the service's CreateUserPoolClient fills in when the# request omits it, since the resource reference says a parameter without a-# value is set to its default. None clears AnalyticsConfiguration, which the-# client record omits on read. RefreshTokenRotation has no field on the-# record and is not modelled.+# value is set to its default. None clears AnalyticsConfiguration and the+# access and ID token validities, which the client record omits on read.+# RefreshTokenRotation has no field on the record and is not modelled._COGNITO_USER_POOL_CLIENT_UPDATABLE = {"ClientName": "","RefreshTokenValidity": 30,- "AccessTokenValidity": 60,- "IdTokenValidity": 60,+ "AccessTokenValidity": None,+ "IdTokenValidity": None,"TokenValidityUnits": {},"ReadAttributes": [],"WriteAttributes": [],diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 6d2ef71f..82251d88 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -466,7 +466,7 @@ _pool_domain_map = AccountRegionScopedDict() # domain -> pool_id_authorization_codes: dict[str, dict] = {} # code -> {client_id, pool_id, redirect_uri, scope, username, nonce, expires_at, code_challenge, code_challenge_method}_refresh_tokens: dict[str, dict] = {} # refresh_token_value -> {pool_id, client_id, username, scope}-_revoked_tokens: set = set() # refresh-token values invalidated by RevokeToken+_revoked_tokens: set = set() # refresh tokens and origin_jti values revoked# ---------------------------------------------------------------------------# In-memory state — Identity Pools (cognito-identity)@@ -745,12 +745,25 @@ def _identity_pool_id_from_arn(resource_arn: str) -> str | None:return pool_id+_VALIDITY_UNIT_SECONDS = {"seconds": 1, "minutes": 60, "hours": 3600, "days": 86400}+++def _token_validity(pool_id: str, client_id: str, token_type: str) -> int:+ """Seconds a token of this app client is valid, by its settings or the AWS default."""+ client = ((_user_pools.get(pool_id) or {}).get("_clients") or {}).get(client_id) or {}+ kind, value, unit = {"id": ("IdToken", 1, "hours"), "refresh": ("RefreshToken", 30, "days")}.get(+ token_type, ("AccessToken", 1, "hours"))+ value = client.get(f"{kind}Validity") or value+ unit = (client.get("TokenValidityUnits") or {}).get(kind) or unit+ return int(value) * _VALIDITY_UNIT_SECONDS.get(unit, 3600)++def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "access",username: str = "", user_attrs: dict | None = None,groups: list[str] | None = None,nonce: str = "",trigger_source: str = "TokenGeneration_Authentication",- client_metadata: dict | None = None) -> str:+ client_metadata: dict | None = None, origin_jti: str = "") -> str:"""Return a JWT signed with the RSA key when cryptography is available.For ``access`` and ``id`` tokens, runs the user pool's PreTokenGeneration@@ -758,13 +771,13 @@ def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "accesRefresh tokens are opaque in AWS and skip the trigger."""now = int(time.time())- origin_jti = new_uuid()+ origin_jti = origin_jti or new_uuid()claims = {"sub": sub,"iss": f"https://cognito-idp.{_pool_region(pool_id)}.amazonaws.com/{pool_id}","token_use": token_type,"iat": now,- "exp": now + 3600,+ "exp": now + _token_validity(pool_id, client_id, token_type),"jti": new_uuid(),}if token_type == "id":@@ -811,6 +824,7 @@ def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "acceselse:# RefreshToken — opaque in real AWS, but we use a JWT stub for simplicityclaims["client_id"] = client_id+ claims["origin_jti"] = origin_jtiif token_type in ("access", "id"):claims = _apply_pretoken_trigger(@@ -1116,6 +1130,51 @@ def _build_presignup_event(pool_id: str, client_id: str, username: str,}+def _token_claims(token) -> dict:+ """The unverified claims of a JWT, or {} when it is not one."""+ try:+ claims = _decode_id_token_unverified(token)+ except (ValueError, AttributeError):+ return {}+ return claims if isinstance(claims, dict) else {}+++def _signature_valid(token: str) -> bool:+ """Whether a JWT is signed with this emulator's signing key."""+ from cryptography.exceptions import InvalidSignature+ from cryptography.hazmat.primitives import hashes+ from cryptography.hazmat.primitives.asymmetric import padding+ signing_input, _, sig = token.rpartition(".")+ try:+ _RSA_PRIVATE_KEY.public_key().verify(+ base64.urlsafe_b64decode(sig + "=" * (-len(sig) % 4)), signing_input.encode(),+ padding.PKCS1v15(), hashes.SHA256())+ except (InvalidSignature, ValueError):+ return False+ return True+++def _access_token_error(data: dict):+ """The NotAuthorizedException for an AccessToken AWS would not accept, or None."""+ token = data.get("AccessToken")+ if not token or not isinstance(token, str):+ return None+ claims = _token_claims(token)+ if token.count(".") != 2 or not claims:+ message = "Invalid Access Token"+ elif claims.get("token_use") != "access":+ message = "Invalid Access Token"+ elif _RSA_PRIVATE_KEY is not None and not _signature_valid(token):+ 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 claims.get("origin_jti") in _revoked_tokens:+ message = "Access Token has been revoked"+ else:+ return None+ return error_response_json("NotAuthorizedException", message, 400)++def _user_from_token(token: str, pool: dict):"""Decode a stub JWT and return the matching user from pool, or None."""try:@@ -2345,7 +2404,7 @@ def _run_idp_handler(handler, action: str, data: dict):if action in _UNSIGNED_IDP_ACTIONS:_pin_unsigned_idp_scope(data)from ministack.app import AUTH- error = _validate_client_secret_hash(action, data) if AUTH else None+ error = (_validate_client_secret_hash(action, data) or _access_token_error(data)) if AUTH else Noneif error:return errorreturn handler(data)@@ -2738,8 +2797,8 @@ def _create_user_pool_client(data):"CreationDate": now,"LastModifiedDate": now,"RefreshTokenValidity": data.get("RefreshTokenValidity", 30),- "AccessTokenValidity": data.get("AccessTokenValidity", 60),- "IdTokenValidity": data.get("IdTokenValidity", 60),+ "AccessTokenValidity": data.get("AccessTokenValidity"),+ "IdTokenValidity": data.get("IdTokenValidity"),"TokenValidityUnits": data.get("TokenValidityUnits", {}),"ReadAttributes": data.get("ReadAttributes", []),"WriteAttributes": data.get("WriteAttributes", []),@@ -3648,6 +3707,7 @@ def _admin_user_global_sign_out(data):# Invalidate every token issued before now (checked by REFRESH_TOKEN_AUTH)# and drop the user's OAuth-flow refresh tokens.user["_signout_at"] = _now_epoch()+ _revoked_tokens.update(user.pop("_origin_jtis", []))uname = user.get("Username", username)for tok in [t for t, e in _refresh_tokens.items()if e.get("username") == uname and e.get("pool_id") == pid]:@@ -3769,7 +3829,10 @@ def _mfa_challenge_for_user(pool: dict, user: dict, pid: str, username: str) ->def _build_auth_result(pool_id: str, client_id: str, user: dict, nonce: str = "",trigger_source: str = "TokenGeneration_Authentication",- client_metadata: dict | None = None) -> dict:+ client_metadata: dict | None = None, origin_jti: str = "") -> dict:+ if not origin_jti:+ origin_jti = new_uuid()+ user.setdefault("_origin_jtis", []).append(origin_jti)attrs = _attr_list_to_dict(user.get("Attributes", []))sub = attrs.get("sub", user["Username"])username = user.get("Username", "")@@ -3778,14 +3841,14 @@ def _build_auth_result(pool_id: str, client_id: str, user: dict, nonce: str = """AccessToken": _fake_token(sub, pool_id, client_id, "access", username=username,user_attrs=attrs, groups=groups,trigger_source=trigger_source,- client_metadata=client_metadata),+ client_metadata=client_metadata, origin_jti=origin_jti),"IdToken": _fake_token(sub, pool_id, client_id, "id", username=username,user_attrs=attrs, groups=groups, nonce=nonce,trigger_source=trigger_source,- client_metadata=client_metadata),- "RefreshToken": _fake_token(sub, pool_id, client_id, "refresh"),+ client_metadata=client_metadata, origin_jti=origin_jti),+ "RefreshToken": _fake_token(sub, pool_id, client_id, "refresh", origin_jti=origin_jti),"TokenType": "Bearer",- "ExpiresIn": 3600,+ "ExpiresIn": _token_validity(pool_id, client_id, "access"),}@@ -4174,7 +4237,8 @@ def _refresh_auth_result(pool, pid, cid, refresh_token):user, err = _refresh_auth_user(pool, pid, cid, refresh_token)if err:return None, err- result = _build_auth_result(pid, cid, user, trigger_source="TokenGeneration_RefreshTokens")+ result = _build_auth_result(pid, cid, user, trigger_source="TokenGeneration_RefreshTokens",+ origin_jti=_token_claims(refresh_token).get("origin_jti", ""))result.pop("RefreshToken", None) # AWS doesn't return a new refresh token herereturn result, None@@ -4461,6 +4525,7 @@ def _global_sign_out(data):user = pool["_users"].get(username)if user:user["_signout_at"] = _now_epoch()+ _revoked_tokens.update(user.pop("_origin_jtis", []))if username and pool_id:for tok in [t for t, e in _refresh_tokens.items()if e.get("username") == username and e.get("pool_id") == pool_id]:@@ -4475,6 +4540,9 @@ def _revoke_token(data):if token:_revoked_tokens.add(token)_refresh_tokens.pop(token, None)+ claims = _token_claims(token)+ if claims.get("token_use") == "refresh" and claims.get("origin_jti"):+ _revoked_tokens.add(claims["origin_jti"])return json_response({})@@ -6744,7 +6812,7 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Non"id_token": result["IdToken"],"refresh_token": refresh_val,"token_type": "Bearer",- "expires_in": 3600,+ "expires_in": result["ExpiresIn"],}return 200, {"Content-Type": "application/json"}, json.dumps(resp).encode()@@ -6764,27 +6832,29 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Nonuser_attrs = {}groups = []+ origin_jti = new_uuid()pool = _get_pool_unscoped(pool_id)if pool:user = pool["_users"].get(username)if user:user_attrs = _attr_list_to_dict(user.get("Attributes", []))groups = user.get("_groups", [])+ user.setdefault("_origin_jtis", []).append(origin_jti)access_token = _fake_token(sub, pool_id, effective_client_id, "access", username,user_attrs=user_attrs, groups=groups,- trigger_source="TokenGeneration_HostedAuth")+ trigger_source="TokenGeneration_HostedAuth", origin_jti=origin_jti)id_token = _fake_token(sub, pool_id, effective_client_id, "id", username, user_attrs=user_attrs,groups=groups, trigger_source="TokenGeneration_HostedAuth",- nonce=code_data.get("nonce", ""))- refresh_token = _fake_token(sub, pool_id, effective_client_id, "refresh")+ nonce=code_data.get("nonce", ""), origin_jti=origin_jti)+ refresh_token = _fake_token(sub, pool_id, effective_client_id, "refresh", origin_jti=origin_jti)return json_response({"id_token": id_token,"access_token": access_token,"refresh_token": refresh_token,"token_type": "Bearer",- "expires_in": 3600,+ "expires_in": _token_validity(pool_id, effective_client_id, "access"),})return _oauth2_error("invalid_grant", "Invalid or expired authorization code.")@@ -6813,13 +6883,14 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Nonattrs = _attr_list_to_dict(user.get("Attributes", []))sub = attrs.get("sub", user["Username"])username = user.get("Username", "")+ origin_jti = _token_claims(refresh_val).get("origin_jti", "")resp = {"access_token": _fake_token(sub, pool_id, client_id, "access", username=username,- trigger_source="TokenGeneration_RefreshTokens"),+ trigger_source="TokenGeneration_RefreshTokens", origin_jti=origin_jti),"id_token": _fake_token(sub, pool_id, client_id, "id", username=username, user_attrs=attrs,- trigger_source="TokenGeneration_RefreshTokens"),+ trigger_source="TokenGeneration_RefreshTokens", origin_jti=origin_jti),"token_type": "Bearer",- "expires_in": 3600,+ "expires_in": _token_validity(pool_id, client_id, "access"),}return 200, {"Content-Type": "application/json"}, json.dumps(resp).encode()@@ -6854,7 +6925,7 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Nonresp = {"access_token": access_token,"token_type": "Bearer",- "expires_in": 3600,+ "expires_in": _token_validity(pool_id, cid, "access"),}return 200, {"Content-Type": "application/json"}, json.dumps(resp).encode()@@ -7443,6 +7514,7 @@ def reset():_auth_codes.clear()_authorization_codes.clear()_refresh_tokens.clear()+ _revoked_tokens.clear()_challenge_sessions.clear()_pending_new_password.clear()_pending_user_auth.clear()diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 14565cf0..324b55ef 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -22273,7 +22273,7 @@ def test_cfn_cognito_user_pool_client_dropped_properties_revert_to_defaults(cfn,if declared:props.update({"CallbackURLs": ["https://example.com/cb"],"PreventUserExistenceErrors": "ENABLED",- "RefreshTokenValidity": 10})+ "RefreshTokenValidity": 10, "AccessTokenValidity": 2})return json.dumps({"Resources": {"Pool": {"Type": "AWS::Cognito::UserPool",@@ -22295,6 +22295,7 @@ def test_cfn_cognito_user_pool_client_dropped_properties_revert_to_defaults(cfn,assert client["CallbackURLs"] == ["https://example.com/cb"]assert client["PreventUserExistenceErrors"] == "ENABLED"assert client["RefreshTokenValidity"] == 10+ assert client["AccessTokenValidity"] == 2cfn.update_stack(StackName=stack_name, TemplateBody=template(False))stack = _wait_stack(cfn, stack_name)@@ -22306,6 +22307,7 @@ def test_cfn_cognito_user_pool_client_dropped_properties_revert_to_defaults(cfn,assert client.get("CallbackURLs", []) == []assert client["PreventUserExistenceErrors"] == "LEGACY"assert client["RefreshTokenValidity"] == 30+ assert "AccessTokenValidity" not in clientfinally:_delete_cfn_test_stack(cfn, stack_name)diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex afd214b8..00a22583 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -1521,6 +1521,161 @@ def test_cognito_revoke_token(cognito_idp):AuthParameters={"REFRESH_TOKEN": refresh_token},)++def _idp_in_process(monkeypatch, auth):+ """Run IDP actions through the dispatcher on empty stores, with the AUTH switch set."""+ import ministack.app as app_mod+ from ministack.core.responses import AccountRegionScopedDict++ mod = _cognito_module()+ monkeypatch.setattr(app_mod, "AUTH", auth)+ monkeypatch.setattr(mod, "_user_pools", AccountRegionScopedDict())+ monkeypatch.setattr(mod, "_refresh_tokens", {})+ monkeypatch.setattr(mod, "_revoked_tokens", set())++ def call(action, **data):+ status, _, body = asyncio.run(mod._dispatch_idp(action, data))+ result = json.loads(body) if body else {}+ if status != 200:+ return result["__type"].split("#")[-1], result["message"]+ return result++ return mod, call+++def _password_client_with_users(call, *usernames, **client_options):+ """A pool, a USER_PASSWORD_AUTH client and confirmed users; returns (pool id, client id, sign-in)."""+ pid = call("CreateUserPool", PoolName="AccessTokenPool")["UserPool"]["Id"]+ cid = call("CreateUserPoolClient", UserPoolId=pid, ClientName="app",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ **client_options)["UserPoolClient"]["ClientId"]+ for name in usernames:+ call("AdminCreateUser", UserPoolId=pid, Username=name, MessageAction="SUPPRESS")+ call("AdminSetUserPassword", UserPoolId=pid, Username=name, Password="Passw0rd!", Permanent=True)++ def sign_in(name):+ return call("InitiateAuth", ClientId=cid, AuthFlow="USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": name, "PASSWORD": "Passw0rd!"})["AuthenticationResult"]++ return pid, cid, sign_in+++def test_cognito_access_token_must_be_a_signed_access_token_under_auth(monkeypatch):+ _, call = _idp_in_process(monkeypatch, auth=True)+ _, _, sign_in = _password_client_with_users(call, "alice", "bob")+ alice, bob = sign_in("alice"), sign_in("bob")+ header, _, signature = alice["AccessToken"].split(".")+ for token, message in [+ ("not-a-token", "Invalid Access Token"),+ (alice["IdToken"], "Invalid Access Token"),+ (alice["RefreshToken"], "Invalid Access Token"),+ (f"{header}.{bob['AccessToken'].split('.')[1]}.{signature}", "Could not verify signature for Access Token"),+ (f"{header}.{alice['IdToken'].split('.')[1]}.{signature}", "Invalid Access Token"),+ ]:+ assert call("GetUser", AccessToken=token) == ("NotAuthorizedException", message)+ assert call("GetUser", AccessToken=alice["AccessToken"])["Username"] == "alice"+++def test_cognito_sign_out_and_revoke_token_revoke_access_tokens_under_auth(monkeypatch):+ _, call = _idp_in_process(monkeypatch, auth=True)+ pid, cid, sign_in = _password_client_with_users(call, "alice", "bob")+ revoked = ("NotAuthorizedException", "Access Token has been revoked")+ a, b, other = sign_in("alice"), sign_in("alice"), sign_in("bob")+ refreshed = call("InitiateAuth", ClientId=cid, AuthFlow="REFRESH_TOKEN_AUTH",+ AuthParameters={"REFRESH_TOKEN": b["RefreshToken"]})["AuthenticationResult"]["AccessToken"]+ assert _decode_jwt_claims(refreshed)["origin_jti"] == _decode_jwt_claims(b["AccessToken"])["origin_jti"]+ assert _decode_jwt_claims(a["IdToken"])["origin_jti"] == _decode_jwt_claims(a["AccessToken"])["origin_jti"]++ # RevokeToken revokes the access tokens of that refresh token's session only.+ call("RevokeToken", ClientId=cid, Token=a["RefreshToken"])+ assert call("GetUser", AccessToken=a["AccessToken"]) == revoked+ assert call("GetUser", AccessToken=b["AccessToken"])["Username"] == "alice"+ assert call("GetUser", AccessToken=refreshed)["Username"] == "alice"+ call("RevokeToken", ClientId=cid, Token=b["RefreshToken"])+ assert call("GetUser", AccessToken=refreshed) == revoked++ # GlobalSignOut revokes every session of the user, for every access-token call.+ c = sign_in("alice")["AccessToken"]+ call("GlobalSignOut", AccessToken=c)+ for action, kwargs in [+ ("GetUser", {}),+ ("UpdateUserAttributes", {"UserAttributes": [{"Name": "name", "Value": "x"}]}),+ ("ChangePassword", {"PreviousPassword": "Passw0rd!", "ProposedPassword": "Passw0rd!2"}),+ ("AssociateSoftwareToken", {}),+ ("GlobalSignOut", {}),+ ("DeleteUser", {}),+ ]:+ assert call(action, AccessToken=c, **kwargs) == revoked++ d = sign_in("alice")["AccessToken"]+ assert call("GetUser", AccessToken=d)["Username"] == "alice"+ call("AdminUserGlobalSignOut", UserPoolId=pid, Username="alice")+ assert call("GetUser", AccessToken=d) == revoked+ assert call("GetUser", AccessToken=other["AccessToken"])["Username"] == "bob"+++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(+ call, "alice", AccessTokenValidity=5, TokenValidityUnits={"AccessToken": "minutes"})+ issued = time.time() - 301+ with monkeypatch.context() as m:+ m.setattr(mod.time, "time", lambda: issued)+ expired, revoked = sign_in("alice"), sign_in("alice")+ call("RevokeToken", ClientId=cid, Token=revoked["RefreshToken"])+ message = ("NotAuthorizedException", "Access Token has expired")+ assert call("GetUser", AccessToken=expired["AccessToken"]) == message+ assert call("GlobalSignOut", AccessToken=expired["AccessToken"]) == message+ assert call("GetUser", AccessToken=revoked["AccessToken"]) == message+ refreshed = call("InitiateAuth", ClientId=cid, AuthFlow="REFRESH_TOKEN_AUTH",+ AuthParameters={"REFRESH_TOKEN": expired["RefreshToken"]})["AuthenticationResult"]+ assert call("GetUser", AccessToken=refreshed["AccessToken"])["Username"] == "alice"+++def test_cognito_access_tokens_not_checked_without_auth(monkeypatch):+ _, call = _idp_in_process(monkeypatch, auth=False)+ _, cid, sign_in = _password_client_with_users(call, "alice", "bob")+ alice, bob = sign_in("alice"), sign_in("bob")+ header, _, signature = alice["AccessToken"].split(".")+ call("RevokeToken", ClientId=cid, Token=alice["RefreshToken"])+ for token in (alice["AccessToken"], alice["IdToken"], f"{header}.{bob['AccessToken'].split('.')[1]}.{signature}"):+ assert "Username" in call("GetUser", AccessToken=token)+++def test_cognito_token_lifetimes_follow_client_validity(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="TokenValidityPool")["UserPool"]["Id"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="alice", MessageAction="SUPPRESS")+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="alice", Password="Passw0rd!", Permanent=True)+ flows = ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"]+ for settings, access, id_token in [+ ({}, 3600, 3600),+ ({"AccessTokenValidity": 2, "IdTokenValidity": 3}, 7200, 10800),+ ({"AccessTokenValidity": 5, "IdTokenValidity": 90,+ "TokenValidityUnits": {"AccessToken": "minutes", "IdToken": "minutes"}}, 300, 5400),+ ({"AccessTokenValidity": 1, "IdTokenValidity": 3600,+ "TokenValidityUnits": {"AccessToken": "days", "IdToken": "seconds"}}, 86400, 3600),+ ]:+ client = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="app", ExplicitAuthFlows=flows, **settings)["UserPoolClient"]+ described = cognito_idp.describe_user_pool_client(+ UserPoolId=pid, ClientId=client["ClientId"])["UserPoolClient"]+ assert described.get("AccessTokenValidity") == settings.get("AccessTokenValidity")+ assert described.get("IdTokenValidity") == settings.get("IdTokenValidity")+ result = cognito_idp.initiate_auth(+ ClientId=client["ClientId"], AuthFlow="USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "alice", "PASSWORD": "Passw0rd!"})["AuthenticationResult"]+ refreshed = cognito_idp.initiate_auth(+ ClientId=client["ClientId"], AuthFlow="REFRESH_TOKEN_AUTH",+ AuthParameters={"REFRESH_TOKEN": result["RefreshToken"]})["AuthenticationResult"]+ for tokens in (result, refreshed):+ access_claims = _decode_jwt_claims(tokens["AccessToken"])+ id_claims = _decode_jwt_claims(tokens["IdToken"])+ assert tokens["ExpiresIn"] == access_claims["exp"] - access_claims["iat"] == access+ assert id_claims["exp"] - id_claims["iat"] == id_token+ refresh_claims = _decode_jwt_claims(result["RefreshToken"])+ assert refresh_claims["exp"] - refresh_claims["iat"] == 30 * 86400++def test_cognito_describe_identity(cognito_identity):resp = cognito_identity.create_identity_pool(IdentityPoolName="DescribeIdPool",@@ -4252,6 +4407,27 @@ def test_oauth2_token_client_credentials():assert 'refresh_token' not in resp+def test_oauth2_token_client_credentials_expires_with_the_client():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp, generate_secret=True)+ cognito_idp.update_user_pool_client(+ UserPoolId=pool_id, ClientId=client['ClientId'],+ AccessTokenValidity=5, TokenValidityUnits={'AccessToken': 'minutes'},+ )++ status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {+ 'grant_type': 'client_credentials',+ 'client_id': client['ClientId'],+ 'client_secret': client['ClientSecret'],+ 'scope': 'openid',+ })++ assert status == 200+ resp = json.loads(body)+ claims = _decode_jwt_claims(resp['access_token'])+ assert resp['expires_in'] == claims['exp'] - claims['iat'] == 300++def test_oauth2_token_client_auth_basic():cognito_idp = make_client('cognito-idp')pool_id, client = _setup_pool_with_user(cognito_idp, generate_secret=True)@@ -6238,8 +6414,8 @@ def test_cognito_unsigned_user_pool_operations_pin_the_owning_region():RefreshToken=refresh_token,)assert refreshed["AuthenticationResult"]["AccessToken"]- west.revoke_token(Token=refresh_token, ClientId=client_id)west.global_sign_out(AccessToken=access_token)+ west.revoke_token(Token=refresh_token, ClientId=client_id)west.admin_create_user(UserPoolId=pool_id, Username="delete-user")west.admin_set_user_password(@@ -6326,7 +6502,7 @@ def test_cognito_client_and_hosted_scans_preserve_account_boundaries():),)def test_cognito_unsigned_idp_operations_pin_each_payload_path(- action, payload_kind+ action, payload_kind, monkeypatch):from ministack.core.responses import (get_account_id,@@ -6336,6 +6512,7 @@ def test_cognito_unsigned_idp_operations_pin_each_payload_path()mod = _cognito_module()+ monkeypatch.setattr(mod, "_access_token_error", lambda _data: None)original_account = get_account_id()original_region = get_region()owner_account = "111111111111"