Skip to content

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

fix(cognito): check GetOpenIdToken logins under AUTH=true (#2269)

iot-rockete4826cbd7895
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 066fb38e..6a41362d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **Cognito Identity — `GetOpenIdToken` checks `Logins` under `AUTH=true`** — the call issued a token for an identity with a login when the request carried no `Logins`, and for any token in `Logins`; with `AUTH=true` it now answers `NotAuthorizedException` as AWS does, with `Access to Identity '<identity id>' is forbidden.` without `Logins` and, for a user pool login, when the token is no ID token of a trusted app client, has a bad signature, expired more than five minutes ago or belongs to another user than the identity's login. Contributed by @iot-rocket.
- **IoT Data — denials answer `ForbiddenException` under `AUTH=true`** — the data plane (Publish, retained messages, shadows) answered an IAM denial or a failed authentication with `AccessDeniedException`, `InvalidSignatureException` or `UnrecognizedClientException` and the principal and action in the message; it now answers 403 `ForbiddenException` as AWS does, with no message for a policy denial and `Forbidden` for a failed authentication. Contributed by @iot-rocket.
- **IoT — `aws:ResourceTag` conditions and the denied resource under `AUTH=true`** — a policy condition on `aws:ResourceTag/<key>` never matched for IoT, so a tag-scoped Allow denied every call and a tag-scoped Deny never applied; it now reads the tags of the thing group, policy, job or other IoT resource the call names, and an IoT denial names that resource (`on resource: <arn>`, `*` for a call that names none) as AWS does. Contributed by @iot-rocket.
- **IoT — tagging calls are authorized on the tagged resource under `AUTH=true`** — `TagResource`, `UntagResource` and `ListTagsForResource` were checked against resource `*`, so a policy scoped to a thing group, job or other IoT ARN denied them even on that resource, and only `Resource: "*"` let them through; they are now checked against the `resourceArn` the request names. Contributed by @iot-rocket.
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 08beb4e1..df36375c 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -7590,7 +7590,50 @@ def _get_credentials_for_identity(data):
})
+_LOGIN_TOKEN_CLOCK_SKEW = 300
+
+
+def _open_id_token_logins_error(pool: dict, identity_id: str, logins: dict):
+ """The NotAuthorizedException for GetOpenIdToken Logins AWS would not accept, or None."""
+ stored = pool["_identities"][identity_id].get("Logins") or {}
+ if not logins:
+ if not stored:
+ return None
+ return error_response_json("NotAuthorizedException", f"Access to Identity '{identity_id}' is forbidden.", 400)
+ unsupported = "Token is not from a supported provider of this identity pool."
+ skewed_now = int(time.time()) - _LOGIN_TOKEN_CLOCK_SKEW
+ for provider, token in logins.items():
+ # Only user pool logins are verified; other providers' tokens are opaque here.
+ if not provider.startswith("cognito-idp."):
+ continue
+ clients = [p.get("ClientId") for p in pool.get("CognitoIdentityProviders") or []
+ if p.get("ProviderName") == provider]
+ claims = _token_claims(token)
+ if not clients:
+ message = unsupported
+ elif not isinstance(token, str) or token.count(".") != 2 or not claims:
+ message = "Invalid login token. Not a valid OpenId Connect identity token."
+ elif claims.get("iss") != f"https://{provider}":
+ message = "Invalid login token. Issuer doesn't match providerName"
+ elif _RSA_PRIVATE_KEY is not None and not _signature_valid(token):
+ message = "Invalid login token. Token signature invalid."
+ elif "aud" not in claims:
+ message = "Invalid login token. Missing a required claim: aud"
+ elif claims["aud"] not in clients:
+ message = unsupported
+ elif not isinstance(claims.get("exp"), (int, float)) or skewed_now >= claims["exp"]:
+ message = f"Invalid login token. Token expired: {skewed_now} >= {claims.get('exp')}"
+ elif provider in stored and _token_claims(stored[provider]).get("sub") != claims.get("sub"):
+ message = ("Logins don't match. Please include at least one valid login "
+ "for this identity or identity pool.")
+ else:
+ continue
+ return error_response_json("NotAuthorizedException", message, 400)
+ return None
+
+
def _get_open_id_token(data):
+ from ministack.app import AUTH
identity_id = data.get("IdentityId", new_uuid())
# Find pool containing this identity
pool_id = ""
@@ -7598,6 +7641,9 @@ def _get_open_id_token(data):
for iid, pool in _identity_pools.items():
if identity_id in pool["_identities"]:
pool_id = iid
+ error = _open_id_token_logins_error(pool, identity_id, logins) if AUTH else None
+ if error:
+ return error
logins = logins or pool["_identities"][identity_id].get("Logins") or {}
break
if not pool_id:
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index 5ac86de0..94e01766 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -1313,6 +1313,117 @@ def test_cognito_get_open_id_token_unknown_identity(cognito_identity):
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
assert exc.value.response["Error"]["Message"] == f"Identity '{unknown}' not found."
+
+def _identity_logins(cognito_idp, cognito_identity):
+ """User pools A and B, an identity pool trusting A's first client, its identities and the users' tokens."""
+ from types import SimpleNamespace
+
+ def pool_with_users(*usernames):
+ pid = cognito_idp.create_user_pool(PoolName="IdentityLogins")["UserPool"]["Id"]
+ cid = cognito_idp.create_user_pool_client(
+ UserPoolId=pid, ClientName="app", ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH"],
+ IdTokenValidity=5, TokenValidityUnits={"IdToken": "minutes"})["UserPoolClient"]["ClientId"]
+ for name in usernames:
+ cognito_idp.admin_create_user(UserPoolId=pid, Username=name, MessageAction="SUPPRESS")
+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username=name, Password="Passw0rd!", Permanent=True)
+ return pid, cid
+
+ def sign_in(cid, name):
+ return cognito_idp.initiate_auth(ClientId=cid, AuthFlow="USER_PASSWORD_AUTH", AuthParameters={
+ "USERNAME": name, "PASSWORD": "Passw0rd!"})["AuthenticationResult"]
+
+ pid, cid = pool_with_users("u1", "u2", "u3")
+ other_cid = cognito_idp.create_user_pool_client(UserPoolId=pid, ClientName="other", ExplicitAuthFlows=[
+ "ALLOW_USER_PASSWORD_AUTH"])["UserPoolClient"]["ClientId"]
+ pid_b, cid_b = pool_with_users("u4")
+ u1 = sign_in(cid, "u1")
+ tokens = {
+ "u1": u1["IdToken"], "u1 access": u1["AccessToken"], "u2": sign_in(cid, "u2")["IdToken"],
+ "u3": sign_in(cid, "u3")["IdToken"], "b": sign_in(cid_b, "u4")["IdToken"],
+ "u1 other client": sign_in(other_cid, "u1")["IdToken"],
+ }
+ provider = f"cognito-idp.us-east-1.amazonaws.com/{pid}"
+ iid = cognito_identity.create_identity_pool(
+ IdentityPoolName="IdentityLogins", AllowUnauthenticatedIdentities=True,
+ CognitoIdentityProviders=[{"ProviderName": provider, "ClientId": cid}])["IdentityPoolId"]
+
+ def call(action, **data):
+ """The result of a cognito-identity call, or its (code, message)."""
+ try:
+ return getattr(cognito_identity, action)(**data)
+ except ClientError as e:
+ return e.response["Error"]["Code"], e.response["Error"]["Message"]
+
+ return SimpleNamespace(
+ call=call, tokens=tokens, provider=provider, provider_b=f"cognito-idp.us-east-1.amazonaws.com/{pid_b}",
+ unauth=cognito_identity.get_id(IdentityPoolId=iid)["IdentityId"],
+ u1=cognito_identity.get_id(IdentityPoolId=iid, Logins={provider: tokens["u1"]})["IdentityId"],
+ )
+
+
+def test_cognito_get_open_id_token_checks_logins(auth_enabled, cognito_idp, cognito_identity):
+ ctx = _identity_logins(cognito_idp, cognito_identity)
+ provider, tokens = ctx.provider, ctx.tokens
+ head, payload, sig = tokens["u1"].split(".")
+ unsupported = "Token is not from a supported provider of this identity pool."
+ mismatch = "Logins don't match. Please include at least one valid login for this identity or identity pool."
+ for logins, message in [
+ (None, f"Access to Identity '{ctx.u1}' is forbidden."),
+ ({provider: tokens["u3"]}, mismatch),
+ ({provider: tokens["u2"]}, mismatch),
+ ({provider: tokens["u1 other client"]}, unsupported),
+ ({provider: tokens["b"]}, "Invalid login token. Issuer doesn't match providerName"),
+ ({ctx.provider_b: tokens["b"]}, unsupported),
+ ({provider: tokens["u1 access"]}, "Invalid login token. Missing a required claim: aud"),
+ ({provider: f"{head}.{payload}.{sig[::-1]}"}, "Invalid login token. Token signature invalid."),
+ ({provider: "not-a-token"}, "Invalid login token. Not a valid OpenId Connect identity token."),
+ ]:
+ result = ctx.call("get_open_id_token", IdentityId=ctx.u1, **({"Logins": logins} if logins else {}))
+ if auth_enabled:
+ assert result == ("NotAuthorizedException", message)
+ else:
+ assert result["IdentityId"] == ctx.u1
+
+ def amr(**data):
+ return _decode_jwt_claims(ctx.call("get_open_id_token", **data)["Token"])["amr"]
+
+ assert amr(IdentityId=ctx.unauth) == ["unauthenticated"]
+ assert amr(IdentityId=ctx.u1, Logins={provider: tokens["u1"]})[:2] == ["authenticated", provider]
+ # An identity without a login takes one.
+ assert amr(IdentityId=ctx.unauth, Logins={provider: tokens["u2"]})[:2] == ["authenticated", provider]
+
+
+def test_cognito_get_open_id_token_expired_login_under_auth(monkeypatch):
+ from ministack.core.responses import AccountRegionScopedDict
+
+ mod, call = _idp_in_process(monkeypatch, auth=True)
+ monkeypatch.setattr(mod, "_identity_pools", AccountRegionScopedDict())
+
+ def identity(action, **data):
+ status, _, body = asyncio.run(mod._dispatch_identity(action, data))
+ result = json.loads(body) if body else {}
+ return (result["__type"].split("#")[-1], result["message"]) if status != 200 else result
+
+ pid, cid, sign_in = _password_client_with_users(
+ call, "u1", IdTokenValidity=5, TokenValidityUnits={"IdToken": "minutes"})
+ provider = f"cognito-idp.us-east-1.amazonaws.com/{pid}"
+ iid = identity("CreateIdentityPool", IdentityPoolName="ExpiredLogins", AllowUnauthenticatedIdentities=True,
+ CognitoIdentityProviders=[{"ProviderName": provider, "ClientId": cid}])["IdentityPoolId"]
+ u1 = identity("GetId", IdentityPoolId=iid, Logins={provider: sign_in("u1")["IdToken"]})["IdentityId"]
+ now = int(time.time())
+ with monkeypatch.context() as m:
+ # ID tokens of this client live 300 s; AWS accepts them for 300 s more.
+ m.setattr(mod.time, "time", lambda: now - 599)
+ late = sign_in("u1")["IdToken"]
+ m.setattr(mod.time, "time", lambda: now - 600)
+ expired = sign_in("u1")["IdToken"]
+ m.setattr(mod.time, "time", lambda: now)
+ assert "Token" in identity("GetOpenIdToken", IdentityId=u1, Logins={provider: late})
+ assert identity("GetOpenIdToken", IdentityId=u1, Logins={provider: expired}) == (
+ "NotAuthorizedException", f"Invalid login token. Token expired: {now - 300} >= {now - 300}")
+
+
def test_cognito_signup_always_unconfirmed(cognito_idp):
"""SignUp always returns UNCONFIRMED regardless of AutoVerifiedAttributes."""
# Pool with AutoVerifiedAttributes — user still starts UNCONFIRMED