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): issue GetOpenIdToken tokens from the identity issuer (#2138)
iot-rocketc1e36a5f7ccd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 99f1a8f2..417dce66 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **Cognito Identity — `GetOpenIdToken` claims** — the token was a user-pool ID token with an empty audience; it is now issued by `https://cognito-identity.amazonaws.com` with the identity pool id as `aud`, the identity id as `sub`, an `amr` list naming the login providers and the user-pool sign-in, the pool ARN in `https://cognito-identity.amazonaws.com/identity-pool-arn` and a 10-minute lifetime. An identity id that no pool knows gets `ResourceNotFoundException` instead of a token. Contributed by @iot-rocket.- **CloudTrail — new trails start with logging off** — `CreateTrail` left a new trail logging, and `GetTrailStatus` reported a `StartLoggingTime` an hour back and a `LatestDeliveryTime` of now. A new trail now reports `IsLogging` false until `StartLogging`, and `GetTrailStatus` returns only the `StartLoggingTime` and `StopLoggingTime` of calls made (a restart keeps the last stop time), without `LatestDeliveryTime` or empty error strings. Contributed by @iot-rocket.## [1.5.26] — 2026-10-11diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 17b31a59..6d2ef71f 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -757,9 +757,6 @@ def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "accesLambda trigger (V2_0 — both tokens; V1_0 — id token only) before signing.Refresh tokens are opaque in AWS and skip the trigger."""- header = base64.urlsafe_b64encode(- json.dumps({"alg": "RS256", "kid": "ministack-key-1"}).encode()- ).rstrip(b"=").decode()now = int(time.time())origin_jti = new_uuid()claims = {@@ -827,7 +824,14 @@ def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "accesgroups=groups or [],client_metadata=client_metadata,)+ return _signed_jwt(claims)++def _signed_jwt(claims: dict) -> str:+ """A JWT over *claims*, signed with the RSA key when cryptography is available."""+ header = base64.urlsafe_b64encode(+ json.dumps({"alg": "RS256", "kid": "ministack-key-1"}).encode()+ ).rstrip(b"=").decode()payload = base64.urlsafe_b64encode(json.dumps(claims).encode()).rstrip(b"=").decode()@@ -7071,6 +7075,32 @@ def _get_id(data):return json_response({"IdentityId": identity_id})+def _identity_login_fields(logins: dict) -> tuple[list[str], list[str]]:+ """The amr list and the API Gateway provider strings of an identity's logins."""+ # The provider string is "<provider>,<provider>:CognitoSignIn:<sub>" per+ # the mapping template reference, sub from the login's id token.+ provider_parts = []+ amr = ["authenticated"] if logins else ["unauthenticated"]+ for provider_name, login_token in logins.items():+ sub = ""+ try:+ payload = json.loads(base64.urlsafe_b64decode(+ login_token.split(".")[1] + "=="))+ sub = payload.get("sub", "")+ except Exception:+ pass+ # amr carries the bare provider name (what trust policies match with+ # ForAnyValue:StringLike per the Cognito RBAC doc) and, for a+ # user-pool sign-in, the CognitoSignIn entry alongside it.+ amr.append(provider_name)+ if sub:+ provider_parts.append(f"{provider_name},{provider_name}:CognitoSignIn:{sub}")+ amr.append(f"{provider_name}:CognitoSignIn:{sub}")+ else:+ provider_parts.append(provider_name)+ return amr, provider_parts++def _get_credentials_for_identity(data):"""Vend identity-pool credentials AND register them as an STS session.@@ -7104,28 +7134,8 @@ def _get_credentials_for_identity(data):role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()# The cognito* identity fields API Gateway reports for IAM-authorized- # calls, precomputed here where the login tokens are at hand: the provider- # string is "<provider>,<provider>:CognitoSignIn:<sub>" per the mapping- # template reference, sub from the login's id token.- provider_parts = []- amr = ["authenticated"] if logins else ["unauthenticated"]- for provider_name, login_token in logins.items():- sub = ""- try:- payload = json.loads(base64.urlsafe_b64decode(- login_token.split(".")[1] + "=="))- sub = payload.get("sub", "")- except Exception:- pass- # amr carries the bare provider name (what trust policies match with- # ForAnyValue:StringLike per the Cognito RBAC doc) and, for a- # user-pool sign-in, the CognitoSignIn entry alongside it.- amr.append(provider_name)- if sub:- provider_parts.append(f"{provider_name},{provider_name}:CognitoSignIn:{sub}")- amr.append(f"{provider_name}:CognitoSignIn:{sub}")- else:- provider_parts.append(provider_name)+ # calls, precomputed here where the login tokens are at hand.+ amr, provider_parts = _identity_login_fields(logins)from ministack.services import sts as sts_svcsts_svc.register_session(access_key, {@@ -7160,12 +7170,26 @@ def _get_open_id_token(data):identity_id = data.get("IdentityId", new_uuid())# Find pool containing this identitypool_id = ""+ logins = data.get("Logins") or {}for iid, pool in _identity_pools.items():if identity_id in pool["_identities"]:pool_id = iid+ logins = logins or pool["_identities"][identity_id].get("Logins") or {}break- token = _fake_token(identity_id, pool_id, "", "id")- return json_response({"IdentityId": identity_id, "Token": token})+ if not pool_id:+ return error_response_json("ResourceNotFoundException", f"Identity '{identity_id}' not found.", 400)+ now = int(time.time())+ claims = {+ "sub": identity_id,+ "aud": pool_id,+ "amr": _identity_login_fields(logins)[0],+ "iss": "https://cognito-identity.amazonaws.com",+ "iat": now,+ "exp": now + 600,+ "https://cognito-identity.amazonaws.com/identity-pool-arn": (+ f"arn:aws:cognito-identity:{get_region()}:{get_account_id()}:identitypool/{pool_id}"),+ }+ return json_response({"IdentityId": identity_id, "Token": _signed_jwt(claims)})def _set_identity_pool_roles(data):diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex f8cac0e7..afd214b8 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -1138,6 +1138,50 @@ def test_cognito_get_open_id_token(cognito_identity):# Verify stub JWT structure: header.payload.sigparts = token.split(".")assert len(parts) == 3+ claims = _decode_jwt_claims(token)+ assert claims["iss"] == "https://cognito-identity.amazonaws.com"+ assert claims["aud"] == iid+ assert claims["sub"] == identity_id+ assert claims["amr"] == ["unauthenticated"]+ assert claims["exp"] - claims["iat"] == 600+ assert claims["https://cognito-identity.amazonaws.com/identity-pool-arn"] == _identity_pool_arn(iid)+++def test_cognito_get_open_id_token_with_user_pool_login(cognito_idp, cognito_identity):+ pool_id = cognito_idp.create_user_pool(PoolName="OidcLoginPool")["UserPool"]["Id"]+ client_id = cognito_idp.create_user_pool_client(+ UserPoolId=pool_id, ClientName="oidc-login", ExplicitAuthFlows=["ALLOW_ADMIN_USER_PASSWORD_AUTH"],+ )["UserPoolClient"]["ClientId"]+ user = cognito_idp.admin_create_user(UserPoolId=pool_id, Username="oidc-user", MessageAction="SUPPRESS")["User"]+ sub = next(a["Value"] for a in user["Attributes"] if a["Name"] == "sub")+ cognito_idp.admin_set_user_password(+ UserPoolId=pool_id, Username="oidc-user", Password="OidcPass1!", Permanent=True,+ )+ id_token = cognito_idp.admin_initiate_auth(+ UserPoolId=pool_id, ClientId=client_id, AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "oidc-user", "PASSWORD": "OidcPass1!"},+ )["AuthenticationResult"]["IdToken"]+ provider = f"cognito-idp.us-east-1.amazonaws.com/{pool_id}"+ iid = cognito_identity.create_identity_pool(+ IdentityPoolName="OidcLoginIdentityPool", AllowUnauthenticatedIdentities=False,+ CognitoIdentityProviders=[{"ProviderName": provider, "ClientId": client_id}],+ )["IdentityPoolId"]+ identity_id = cognito_identity.get_id(IdentityPoolId=iid, Logins={provider: id_token})["IdentityId"]++ token = cognito_identity.get_open_id_token(IdentityId=identity_id, Logins={provider: id_token})["Token"]+ claims = _decode_jwt_claims(token)+ assert claims["iss"] == "https://cognito-identity.amazonaws.com"+ assert claims["aud"] == iid+ assert claims["sub"] == identity_id+ assert claims["amr"] == ["authenticated", provider, f"{provider}:CognitoSignIn:{sub}"]+++def test_cognito_get_open_id_token_unknown_identity(cognito_identity):+ unknown = "us-east-1:00000000-0000-4000-8000-000000000000"+ with pytest.raises(ClientError) as exc:+ cognito_identity.get_open_id_token(IdentityId=unknown)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+ assert exc.value.response["Error"]["Message"] == f"Identity '{unknown}' not found."def test_cognito_signup_always_unconfirmed(cognito_idp):"""SignUp always returns UNCONFIRMED regardless of AutoVerifiedAttributes."""