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
Echo OAuth2 nonce into Cognito id_token (#605)
Christopher Özbek2c3f58c49a22
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 18bf6d68..c7b6856e 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -337,6 +337,7 @@ def _identity_id(pool_id: str) -> str: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") -> str:"""Return a JWT signed with the RSA key when cryptography is available.@@ -362,6 +363,12 @@ def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "accesclaims["aud"] = client_idclaims["auth_time"] = nowclaims["origin_jti"] = origin_jti+ # OIDC requires the nonce from the authorize request to be echoed back+ # in the id_token so the client can mitigate replay attacks. Strict+ # OIDC clients (e.g. oidc-client-ts) silently discard tokens missing+ # an expected nonce.+ if nonce:+ claims["nonce"] = nonceif username:claims["cognito:username"] = usernameif groups:@@ -1499,7 +1506,7 @@ 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) -> dict:+def _build_auth_result(pool_id: str, client_id: str, user: dict, nonce: str = "") -> dict:attrs = _attr_list_to_dict(user.get("Attributes", []))sub = attrs.get("sub", user["Username"])username = user.get("Username", "")@@ -1508,7 +1515,7 @@ def _build_auth_result(pool_id: str, client_id: str, user: dict) -> dict:"AccessToken": _fake_token(sub, pool_id, client_id, "access", username=username,user_attrs=attrs, groups=groups),"IdToken": _fake_token(sub, pool_id, client_id, "id", username=username,- user_attrs=attrs, groups=groups),+ user_attrs=attrs, groups=groups, nonce=nonce),"RefreshToken": _fake_token(sub, pool_id, client_id, "refresh"),"TokenType": "Bearer","ExpiresIn": 3600,@@ -2836,7 +2843,7 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Nonif client and client.get("ClientSecret") and csec != client["ClientSecret"]:return _oauth2_error("invalid_client", "Invalid client credentials.")- result = _build_auth_result(pool_id, cid, user)+ result = _build_auth_result(pool_id, cid, user, nonce=entry.get("nonce", ""))refresh_val = result["RefreshToken"]_refresh_tokens[refresh_val] = {"pool_id": pool_id,diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 2d3a6bd8..2c62ccf7 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -1912,6 +1912,35 @@ def test_oauth2_token_authorization_code():assert resp['expires_in'] == 3600+def test_oauth2_id_token_echoes_nonce():+ """OIDC requires the id_token to echo the nonce from the authorize request+ so clients can mitigate replay. Strict OIDC clients (oidc-client-ts,+ Auth0/MS libs) silently discard tokens that omit an expected nonce.+ Regression for the bug where the nonce was stored on the auth code but+ never propagated into the id_token."""+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp)+ client_id = client['ClientId']+ client_secret = client.get('ClientSecret', '')++ expected_nonce = 'a-nonce-the-client-sent-' + secrets.token_hex(8)+ code = _do_login_and_get_code(cognito_idp, client_id, {'nonce': expected_nonce})++ status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {+ 'grant_type': 'authorization_code',+ 'code': code,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'client_id': client_id,+ 'client_secret': client_secret,+ })+ assert status == 200+ id_token = json.loads(body)['id_token']+ payload_b64 = id_token.split('.')[1]+ payload_b64 += '=' * (-len(payload_b64) % 4)+ claims = json.loads(base64.urlsafe_b64decode(payload_b64))+ assert claims.get('nonce') == expected_nonce++def test_oauth2_token_authorization_code_with_pkce():cognito_idp = make_client('cognito-idp')pool_id, client = _setup_pool_with_user(cognito_idp, generate_secret=False)