Skip to content

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

fix(cognito): check GetId and GetCredentialsForIdentity logins (#2270)

iot-rocketf8e5f16b7a85
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6a41362d..138fff09 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **Cognito Identity — `GetId` and `GetCredentialsForIdentity` check `Logins` under `AUTH=true`** — both calls took any token in `Logins`, `GetCredentialsForIdentity` vended authenticated credentials from the stored login when the request carried none, `GetId` created a new identity for a login that already had one, and a login given to an identity without one was not kept; with `AUTH=true` both calls refuse the tokens `GetOpenIdToken` refuses with the same `NotAuthorizedException` messages (and a Google login that is no JWT), `GetCredentialsForIdentity` refuses a request without `Logins` for an identity with a login, `GetId` returns the identity that holds the login, and `GetCredentialsForIdentity` and `GetOpenIdToken` link the login to an identity that had none, as AWS does. Contributed by @iot-rocket.
+- **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.
- **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.
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index df36375c..c8f554d6 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -7485,10 +7485,19 @@ def _update_identity_pool(data):
def _get_id(data):
+ from ministack.app import AUTH
iid = data.get("IdentityPoolId")
pool = _identity_pools.get(iid)
if not pool:
return error_response_json("ResourceNotFoundException", f"Identity pool {iid} not found.", 400)
+ if AUTH:
+ logins = data.get("Logins") or {}
+ error = _identity_logins_error(pool, None, logins)
+ if error:
+ return error
+ owner = _login_owner(pool, logins)
+ if owner:
+ return json_response({"IdentityId": owner})
identity_id = _identity_id(iid)
pool["_identities"][identity_id] = {
"IdentityId": identity_id,
@@ -7535,6 +7544,7 @@ def _get_credentials_for_identity(data):
``CognitoIdentityCredentials`` — GetCallerIdentity reports
``arn:aws:sts::<account>:assumed-role/<RoleName>/CognitoIdentityCredentials``.
"""
+ from ministack.app import AUTH
identity_id = data.get("IdentityId", new_uuid())
now = int(time.time())
logins = data.get("Logins") or {}
@@ -7542,6 +7552,11 @@ def _get_credentials_for_identity(data):
for _iid, candidate in _identity_pools.items():
if identity_id in candidate.get("_identities", {}):
pool = candidate
+ if AUTH:
+ error = _identity_logins_error(candidate, identity_id, logins)
+ if error:
+ return error
+ _link_logins(candidate, identity_id, logins)
if not logins:
logins = candidate["_identities"][identity_id].get("Logins") or {}
break
@@ -7593,26 +7608,30 @@ 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 {}
+def _identity_logins_error(pool: dict, identity_id: str | None, logins: dict):
+ """The NotAuthorizedException for Logins AWS would not accept for an identity (None: a new one), or None."""
+ stored = (pool["_identities"][identity_id].get("Logins") or {}) if identity_id else {}
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."
+ not_oidc = "Invalid login token. Not a valid OpenId Connect identity token."
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:
+ is_jwt = isinstance(token, str) and token.count(".") == 2 and bool(claims)
+ if provider == "accounts.google.com" and not is_jwt and provider in (pool.get("SupportedLoginProviders") or {}):
+ message = not_oidc
+ elif not provider.startswith("cognito-idp."):
+ # Other providers' tokens are opaque here.
+ continue
+ elif 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 not is_jwt:
+ message = not_oidc
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):
@@ -7632,6 +7651,25 @@ def _open_id_token_logins_error(pool: dict, identity_id: str, logins: dict):
return None
+def _login_owner(pool: dict, logins: dict):
+ """The id of the pool's identity that already holds one of these logins, or None."""
+ for provider, token in logins.items():
+ sub = _token_claims(token).get("sub")
+ for identity_id, identity in pool["_identities"].items():
+ held = (identity.get("Logins") or {}).get(provider)
+ if held is not None and (held == token or (sub and _token_claims(held).get("sub") == sub)):
+ return identity_id
+ return None
+
+
+def _link_logins(pool: dict, identity_id: str, logins: dict) -> None:
+ """Give an identity without a login the call's Logins unless another identity holds them."""
+ identity = pool["_identities"][identity_id]
+ if logins and not identity.get("Logins") and not _login_owner(pool, logins):
+ identity["Logins"] = dict(logins)
+ identity["LastModifiedDate"] = _now_epoch()
+
+
def _get_open_id_token(data):
from ministack.app import AUTH
identity_id = data.get("IdentityId", new_uuid())
@@ -7641,9 +7679,11 @@ 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
+ if AUTH:
+ error = _identity_logins_error(pool, identity_id, logins)
+ if error:
+ return error
+ _link_logins(pool, identity_id, logins)
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 94e01766..8c1e74e0 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -1332,20 +1332,22 @@ def _identity_logins(cognito_idp, cognito_identity):
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")
+ pid, cid = pool_with_users("u1", "u2", "u3", "u4", "u5")
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"],
+ "u3": sign_in(cid, "u3")["IdToken"], "u4": sign_in(cid, "u4")["IdToken"], "u5": sign_in(cid, "u5")["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"]
+ CognitoIdentityProviders=[{"ProviderName": provider, "ClientId": cid}],
+ SupportedLoginProviders={"accounts.google.com": "app.apps.googleusercontent.com"})["IdentityPoolId"]
def call(action, **data):
"""The result of a cognito-identity call, or its (code, message)."""
@@ -1356,6 +1358,7 @@ def _identity_logins(cognito_idp, cognito_identity):
return SimpleNamespace(
call=call, tokens=tokens, provider=provider, provider_b=f"cognito-idp.us-east-1.amazonaws.com/{pid_b}",
+ pool=iid,
unauth=cognito_identity.get_id(IdentityPoolId=iid)["IdentityId"],
u1=cognito_identity.get_id(IdentityPoolId=iid, Logins={provider: tokens["u1"]})["IdentityId"],
)
@@ -1394,6 +1397,73 @@ def test_cognito_get_open_id_token_checks_logins(auth_enabled, cognito_idp, cogn
assert amr(IdentityId=ctx.unauth, Logins={provider: tokens["u2"]})[:2] == ["authenticated", provider]
+def test_cognito_get_credentials_for_identity_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."
+ not_oidc = "Invalid login token. Not a valid OpenId Connect identity token."
+ 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"}, not_oidc),
+ ({"accounts.google.com": "not-a-token"}, not_oidc),
+ ]:
+ result = ctx.call("get_credentials_for_identity", IdentityId=ctx.u1, **({"Logins": logins} if logins else {}))
+ if auth_enabled:
+ assert result == ("NotAuthorizedException", message)
+ else:
+ assert result["IdentityId"] == ctx.u1
+ google = ctx.call("get_open_id_token", IdentityId=ctx.u1, Logins={"accounts.google.com": "not-a-token"})
+ assert google == ("NotAuthorizedException", not_oidc) if auth_enabled else "Token" in google
+ matching = ctx.call("get_credentials_for_identity", IdentityId=ctx.u1, Logins={provider: tokens["u1"]})
+ assert matching["IdentityId"] == ctx.u1
+
+
+def test_cognito_get_id_checks_logins(auth_enabled, cognito_idp, cognito_identity):
+ ctx = _identity_logins(cognito_idp, cognito_identity)
+ provider, tokens = ctx.provider, ctx.tokens
+ not_oidc = "Invalid login token. Not a valid OpenId Connect identity token."
+ for logins, message in [
+ ({provider: "not-a-token"}, not_oidc),
+ ({provider: tokens["u1 access"]}, "Invalid login token. Missing a required claim: aud"),
+ ({provider: tokens["u1 other client"]}, "Token is not from a supported provider of this identity pool."),
+ ({"accounts.google.com": "not-a-token"}, not_oidc),
+ ]:
+ result = ctx.call("get_id", IdentityPoolId=ctx.pool, Logins=logins)
+ assert result == ("NotAuthorizedException", message) if auth_enabled else "IdentityId" in result
+ # With AUTH a login that has an identity gets that identity back; without it every GetId makes a new one.
+ found = ctx.call("get_id", IdentityPoolId=ctx.pool, Logins={provider: tokens["u1"]})["IdentityId"]
+ assert (found == ctx.u1) == auth_enabled
+
+
+def test_cognito_identity_without_login_takes_one(auth_enabled, cognito_idp, cognito_identity):
+ ctx = _identity_logins(cognito_idp, cognito_identity)
+ provider, tokens = ctx.provider, ctx.tokens
+ for action, user in (("get_credentials_for_identity", "u4"), ("get_open_id_token", "u5")):
+ identity_id = ctx.call("get_id", IdentityPoolId=ctx.pool)["IdentityId"]
+ assert ctx.call(action, IdentityId=identity_id, Logins={provider: tokens[user]})["IdentityId"] == identity_id
+ logins = ctx.call("describe_identity", IdentityId=identity_id).get("Logins", [])
+ found = ctx.call("get_id", IdentityPoolId=ctx.pool, Logins={provider: tokens[user]})["IdentityId"]
+ without_logins = ctx.call("get_credentials_for_identity", IdentityId=identity_id)
+ if auth_enabled:
+ assert (logins, found) == ([provider], identity_id)
+ assert without_logins == ("NotAuthorizedException", f"Access to Identity '{identity_id}' is forbidden.")
+ else:
+ assert (logins, without_logins["IdentityId"]) == ([], identity_id)
+ assert found != identity_id
+
+
def test_cognito_get_open_id_token_expired_login_under_auth(monkeypatch):
from ministack.core.responses import AccountRegionScopedDict
@@ -1420,8 +1490,9 @@ def test_cognito_get_open_id_token_expired_login_under_auth(monkeypatch):
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}")
+ for action in ("GetOpenIdToken", "GetCredentialsForIdentity"):
+ assert identity(action, IdentityId=u1, Logins={provider: expired}) == (
+ "NotAuthorizedException", f"Invalid login token. Token expired: {now - 300} >= {now - 300}")
def test_cognito_signup_always_unconfirmed(cognito_idp):