Skip to content

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

feat(cognito): add support for AdminLinkProviderForUser (#1503)

Nahuel Nucera09f4fec9d910
diff --git a/README.md b/README.md
index c9055205..31c842d9 100644
--- a/README.md
+++ b/README.md
@@ -575,7 +575,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i
| **EBS** | CreateVolume, DeleteVolume, DescribeVolumes, DescribeVolumeStatus, AttachVolume, DetachVolume, ModifyVolume, DescribeVolumesModifications, EnableVolumeIO, ModifyVolumeAttribute, DescribeVolumeAttribute, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, CopySnapshot, ModifySnapshotAttribute, DescribeSnapshotAttribute | Part of EC2 Query/XML service; attach/detach updates volume state; snapshots stored as completed immediately; Pro-only on LocalStack — free here |
| **EFS** | CreateFileSystem, DescribeFileSystems, DeleteFileSystem, UpdateFileSystem, CreateMountTarget, DescribeMountTargets, DeleteMountTarget, DescribeMountTargetSecurityGroups, ModifyMountTargetSecurityGroups, CreateAccessPoint, DescribeAccessPoints, DeleteAccessPoint, TagResource, UntagResource, ListTagsForResource, PutLifecycleConfiguration, DescribeLifecycleConfiguration, PutBackupPolicy, DescribeBackupPolicy, DescribeAccountPreferences, PutAccountPreferences | REST/JSON `/2015-02-01/*`; CreationToken idempotency; FileSystem deletion blocked when mount targets exist; Pro-only on LocalStack — free here |
| **EMR** | RunJobFlow, DescribeCluster, ListClusters, TerminateJobFlows, ModifyCluster, SetTerminationProtection, SetVisibleToAllUsers, AddJobFlowSteps, DescribeStep, ListSteps, CancelSteps, AddInstanceFleet, ListInstanceFleets, ModifyInstanceFleet, AddInstanceGroups, ListInstanceGroups, ModifyInstanceGroups, ListBootstrapActions, AddTags, RemoveTags, GetBlockPublicAccessConfiguration, PutBlockPublicAccessConfiguration | Control plane only — no real Spark/Hadoop; clusters start in WAITING (KeepAlive=true) or TERMINATED (KeepAlive=false); steps stored as COMPLETED immediately; all three instance modes (simple, InstanceGroups, InstanceFleets); TerminationProtected enforced; Pro-only on LocalStack — free here |
-| **Cognito** | **User Pools**: CreateUserPool, DeleteUserPool, DescribeUserPool, ListUserPools, UpdateUserPool, CreateUserPoolClient, DeleteUserPoolClient, DescribeUserPoolClient, ListUserPoolClients, UpdateUserPoolClient, CreateResourceServer, UpdateResourceServer, DescribeResourceServer, DeleteResourceServer, ListResourceServers, AdminCreateUser, AdminDeleteUser, AdminGetUser, ListUsers, AdminSetUserPassword, AdminUpdateUserAttributes, AdminConfirmSignUp, AdminDisableUser, AdminEnableUser, AdminResetUserPassword, AdminUserGlobalSignOut, AdminAddUserToGroup, AdminRemoveUserFromGroup, AdminListGroupsForUser, AdminListUserAuthEvents, AdminInitiateAuth, AdminRespondToAuthChallenge, InitiateAuth, RespondToAuthChallenge, GlobalSignOut, RevokeToken, SignUp, ConfirmSignUp, ForgotPassword, ConfirmForgotPassword, ChangePassword, GetUser, UpdateUserAttributes, DeleteUser, CreateGroup, DeleteGroup, GetGroup, ListGroups, ListUsersInGroup, CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain, GetUserPoolMfaConfig, SetUserPoolMfaConfig, AssociateSoftwareToken, VerifySoftwareToken, AdminSetUserMFAPreference, SetUserMFAPreference, TagResource, UntagResource, ListTagsForResource; **Identity Pools**: CreateIdentityPool, DeleteIdentityPool, DescribeIdentityPool, ListIdentityPools, UpdateIdentityPool, GetId, GetCredentialsForIdentity, GetOpenIdToken, SetIdentityPoolRoles, GetIdentityPoolRoles, ListIdentities, DescribeIdentity, MergeDeveloperIdentities, UnlinkDeveloperIdentity, UnlinkIdentity, TagResource, UntagResource, ListTagsForResource; **OAuth2**: /oauth2/token (client_credentials) | Stub JWT tokens (structurally valid base64url JWTs); SRP auth returns PASSWORD_VERIFIER challenge; **CUSTOM_AUTH flow** wired through the configured `DefineAuthChallenge` / `CreateAuthChallenge` / `VerifyAuthChallengeResponse` Lambda triggers (passwordless / magic-link / SMS-OTP); session TTL honors `AuthSessionValidity`, capped at 3 answered rounds per AWS; confirmation codes hardcoded (signup: 123456, forgot-password: 654321); TOTP SOFTWARE_TOKEN_MFA challenge flow; MFA config and per-user enrollment stored in-memory; **user pool domains**: `CreateUserPoolDomain` with `CustomDomainConfig` registers a custom domain served on its own FQDN (without it, `Domain` is a prefix expanded to `{prefix}.auth.{region}.amazoncognito.com`), and the SAML ACS URL and OIDC federation callback are built from it — set one when MiniStack is reached through an external TLS terminator, so external IdPs get a reachable `https://{domain}/oauth2/idpresponse` instead of the internal gateway address |
+| **Cognito** | **User Pools**: CreateUserPool, DeleteUserPool, DescribeUserPool, ListUserPools, UpdateUserPool, CreateUserPoolClient, DeleteUserPoolClient, DescribeUserPoolClient, ListUserPoolClients, UpdateUserPoolClient, CreateResourceServer, UpdateResourceServer, DescribeResourceServer, DeleteResourceServer, ListResourceServers, AdminCreateUser, AdminDeleteUser, AdminGetUser, ListUsers, AdminSetUserPassword, AdminUpdateUserAttributes, AdminConfirmSignUp, AdminDisableUser, AdminEnableUser, AdminResetUserPassword, AdminUserGlobalSignOut, AdminAddUserToGroup, AdminRemoveUserFromGroup, AdminListGroupsForUser, AdminListUserAuthEvents, AdminInitiateAuth, AdminRespondToAuthChallenge, InitiateAuth, RespondToAuthChallenge, GlobalSignOut, RevokeToken, SignUp, ConfirmSignUp, ForgotPassword, ConfirmForgotPassword, ChangePassword, GetUser, UpdateUserAttributes, DeleteUser, CreateGroup, DeleteGroup, GetGroup, ListGroups, ListUsersInGroup, CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain, GetUserPoolMfaConfig, SetUserPoolMfaConfig, AssociateSoftwareToken, VerifySoftwareToken, AdminSetUserMFAPreference, SetUserMFAPreference, CreateIdentityProvider, DescribeIdentityProvider, UpdateIdentityProvider, DeleteIdentityProvider, ListIdentityProviders, GetIdentityProviderByIdentifier, AdminLinkProviderForUser, AdminDisableProviderForUser, TagResource, UntagResource, ListTagsForResource; **Identity Pools**: CreateIdentityPool, DeleteIdentityPool, DescribeIdentityPool, ListIdentityPools, UpdateIdentityPool, GetId, GetCredentialsForIdentity, GetOpenIdToken, SetIdentityPoolRoles, GetIdentityPoolRoles, ListIdentities, DescribeIdentity, MergeDeveloperIdentities, UnlinkDeveloperIdentity, UnlinkIdentity, TagResource, UntagResource, ListTagsForResource; **OAuth2**: /oauth2/token (client_credentials) | Stub JWT tokens (structurally valid base64url JWTs); SRP auth returns PASSWORD_VERIFIER challenge; **CUSTOM_AUTH flow** wired through the configured `DefineAuthChallenge` / `CreateAuthChallenge` / `VerifyAuthChallengeResponse` Lambda triggers (passwordless / magic-link / SMS-OTP); session TTL honors `AuthSessionValidity`, capped at 3 answered rounds per AWS; confirmation codes hardcoded (signup: 123456, forgot-password: 654321); TOTP SOFTWARE_TOKEN_MFA challenge flow; MFA config and per-user enrollment stored in-memory; **user pool domains**: `CreateUserPoolDomain` with `CustomDomainConfig` registers a custom domain served on its own FQDN (without it, `Domain` is a prefix expanded to `{prefix}.auth.{region}.amazoncognito.com`), and the SAML ACS URL and OIDC federation callback are built from it — set one when MiniStack is reached through an external TLS terminator, so external IdPs get a reachable `https://{domain}/oauth2/idpresponse` instead of the internal gateway address; **federated user linking**: `AdminLinkProviderForUser` links an external identity to an existing profile before its first sign-in, so that sign-in resolves to the linked profile instead of minting a second `{Provider}_id` one, and the profile carries the `identities` attribute (also an ID-token claim) |
| **ECR** | CreateRepository, DescribeRepositories, DeleteRepository, ListImages, DescribeImages, PutImage, BatchGetImage, BatchDeleteImage, GetAuthorizationToken, GetRepositoryPolicy, SetRepositoryPolicy, DeleteRepositoryPolicy, PutLifecyclePolicy, GetLifecyclePolicy, DeleteLifecyclePolicy, ListTagsForResource, TagResource, UntagResource, PutImageTagMutability, PutImageScanningConfiguration, DescribeRegistry, GetDownloadUrlForLayer, BatchCheckLayerAvailability, InitiateLayerUpload, UploadLayerPart, CompleteLayerUpload | In-memory image registry; Docker V2 manifest support; authorization token generation; lifecycle policies; tag mutability; Pro-only on LocalStack — free here |
| **AppSync** | **GraphQL APIs**: CreateGraphQLApi, GetGraphQLApi, ListGraphQLApis, UpdateGraphQLApi, DeleteGraphQLApi, CreateApiKey, DeleteApiKey, ListApiKeys, CreateDataSource, GetDataSource, ListDataSources, DeleteDataSource, CreateResolver, GetResolver, ListResolvers, DeleteResolver, CreateType, ListTypes, GetType, TagResource, UntagResource, ListTagsForResource; **Event APIs**: CreateApi, GetApi, ListApis, UpdateApi, DeleteApi, CreateChannelNamespace, GetChannelNamespace, ListChannelNamespaces, UpdateChannelNamespace, DeleteChannelNamespace, CreateApiKey, ListApiKeys, DeleteApiKey, HTTP Publish, WebSocket subscribe/publish | GraphQL queries/mutations execute against DynamoDB resolvers; Lambda resolvers supported. Event APIs support AWS-shaped `/v2/apis` management, `/v1/apis/{apiId}/apikeys` API-key operations, `POST /event` on `*.appsync-api.*`, and realtime `*.appsync-realtime-api.*` WebSocket flows with API-key and Lambda-authorizer checks |
| **Cloud Map** | CreateHttpNamespace, CreatePrivateDnsNamespace, CreatePublicDnsNamespace, GetNamespace, ListNamespaces, DeleteNamespace, UpdateHttpNamespace, UpdatePrivateDnsNamespace, UpdatePublicDnsNamespace, CreateService, GetService, ListServices, DeleteService, UpdateService, RegisterInstance, DeregisterInstance, DiscoverInstances, DiscoverInstancesRevision, ListInstances, GetInstancesHealthStatus, UpdateInstanceCustomHealthStatus, GetServiceAttributes, UpdateServiceAttributes, DeleteServiceAttributes, GetOperation, ListOperations, TagResource, UntagResource, ListTagsForResource | DNS namespaces create Route53 hosted zones; operation tracking; Terraform `aws_service_discovery_*` compatible |
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index fa3c64ca..41f2daa2 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -24,6 +24,7 @@ User Pools operations:
CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain,
CreateIdentityProvider, DescribeIdentityProvider, UpdateIdentityProvider,
DeleteIdentityProvider, ListIdentityProviders, GetIdentityProviderByIdentifier,
+ AdminLinkProviderForUser, AdminDisableProviderForUser,
GetUserPoolMfaConfig, SetUserPoolMfaConfig,
AssociateSoftwareToken, VerifySoftwareToken,
TagResource, UntagResource, ListTagsForResource.
@@ -620,6 +621,15 @@ def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "acces
for k, v in user_attrs.items():
if k == "sub":
continue
+ if k == "identities":
+ # "Your user's ID token contains all of their associated
+ # providers in the identities claim" — as an array, while
+ # the user attribute itself carries JSON text.
+ try:
+ claims[k] = json.loads(v)
+ except (TypeError, ValueError):
+ claims[k] = v
+ continue
claims[k] = v
if "email" in user_attrs:
claims.setdefault("email_verified", True)
@@ -1900,6 +1910,8 @@ async def _dispatch_idp(action: str, data: dict):
"DeleteIdentityProvider": _delete_identity_provider,
"ListIdentityProviders": _list_identity_providers,
"GetIdentityProviderByIdentifier": _get_identity_provider_by_identifier,
+ "AdminLinkProviderForUser": _admin_link_provider_for_user,
+ "AdminDisableProviderForUser": _admin_disable_provider_for_user,
# MFA
"GetUserPoolMfaConfig": _get_user_pool_mfa_config,
"SetUserPoolMfaConfig": _set_user_pool_mfa_config,
@@ -4131,6 +4143,257 @@ def _get_identity_provider_by_identifier(data):
# MFA CONFIG
# ===========================================================================
+# ---------------------------------------------------------------------------
+# Linking federated users to an existing profile (#1499)
+#
+# "When a federated user signs in to your user pool for the first time, Amazon
+# Cognito looks for a local profile that you have linked to their identity. If
+# no linked profile exists, your user pool creates a new profile." Links are
+# created ahead of that first sign-in, typically from a PreSignUp trigger.
+# ---------------------------------------------------------------------------
+
+# "You can link up to five federated users to each user profile."
+_PROVIDER_LINK_MAX_PER_USER = 5
+# "You can link users to each IdP from up to five IdP attribute claims."
+_PROVIDER_LINK_MAX_ATTRIBUTES_PER_IDP = 5
+# ProviderName values Cognito recognises without a SAML/OIDC configuration.
+_SOCIAL_PROVIDER_TYPES = {
+ "Facebook": "Facebook",
+ "Google": "Google",
+ "LoginWithAmazon": "LoginWithAmazon",
+ "SignInWithApple": "SignInWithApple",
+}
+
+
+def _provider_links(pool: dict) -> dict:
+ """{(provider, attribute_name, attribute_value): destination username}."""
+ return pool.setdefault("_provider_links", {})
+
+
+def _provider_link_key(provider_name, attribute_name, attribute_value):
+ return "\x00".join((provider_name, attribute_name or "", attribute_value))
+
+
+def _provider_type_for(pool: dict, provider_name: str) -> str:
+ """Resolve the IdP's ProviderType, preferring the pool's own configuration."""
+ for provider in pool.get("_identity_providers", {}).values():
+ if provider.get("ProviderName") == provider_name:
+ return provider.get("ProviderType") or "OIDC"
+ return _SOCIAL_PROVIDER_TYPES.get(provider_name, "OIDC")
+
+
+def _user_identities(user: dict) -> list:
+ """The user's `identities` attribute, decoded. AWS stores it as JSON text."""
+ raw = _attr_list_to_dict(user.get("Attributes", [])).get("identities")
+ if not raw:
+ return []
+ try:
+ parsed = json.loads(raw)
+ except (TypeError, ValueError):
+ return []
+ return parsed if isinstance(parsed, list) else []
+
+
+def _set_user_identities(user: dict, identities: list) -> None:
+ attrs = _attr_list_to_dict(user.get("Attributes", []))
+ if identities:
+ attrs["identities"] = json.dumps(identities)
+ else:
+ attrs.pop("identities", None)
+ user["Attributes"] = _dict_to_attr_list(attrs)
+
+
+def _provider_user_identifier(data, field):
+ """Validate a ProviderUserIdentifierType member. Returns (value, error)."""
+ raw = data.get(field)
+ if not isinstance(raw, dict):
+ return None, error_response_json(
+ "InvalidParameterException", f"{field} is required.", 400)
+ provider_name = (raw.get("ProviderName") or "").strip()
+ attribute_value = (raw.get("ProviderAttributeValue") or "").strip()
+ if not provider_name:
+ return None, error_response_json(
+ "InvalidParameterException",
+ f"{field}.ProviderName is required.", 400)
+ if not attribute_value:
+ return None, error_response_json(
+ "InvalidParameterException",
+ f"{field}.ProviderAttributeValue is required.", 400)
+ return {
+ "ProviderName": provider_name,
+ "ProviderAttributeName": (raw.get("ProviderAttributeName") or "").strip(),
+ "ProviderAttributeValue": attribute_value,
+ }, None
+
+
+def _federated_profile_username(provider_name, attribute_value):
+ """Auto-created federated profiles are named `{Provider name}_identifier`."""
+ return f"{provider_name}_{attribute_value}"
+
+
+def _admin_link_provider_for_user(data):
+ pid = data.get("UserPoolId")
+ pool, err = _resolve_pool(pid)
+ if err:
+ return err
+
+ destination, err = _provider_user_identifier(data, "DestinationUser")
+ if err:
+ return err
+ source, err = _provider_user_identifier(data, "SourceUser")
+ if err:
+ return err
+
+ # "This user must be a federated user (for example, a SAML or Facebook
+ # user), not another native user."
+ if source["ProviderName"] == "Cognito":
+ return error_response_json(
+ "InvalidParameterException",
+ "SourceUser must be a federated user, not a Cognito user.", 400)
+
+ # "For a native username + password user, the ProviderAttributeValue for
+ # the DestinationUser should be the username in the user pool. For a
+ # federated user, it should be the provider-specific user_id." The
+ # DestinationUser's ProviderAttributeName is ignored.
+ if destination["ProviderName"] == "Cognito":
+ destination_username = destination["ProviderAttributeValue"]
+ else:
+ destination_username = _federated_profile_username(
+ destination["ProviderName"], destination["ProviderAttributeValue"])
+ destination_user = pool["_users"].get(destination_username)
+ if not destination_user:
+ return error_response_json(
+ "UserNotFoundException", "User does not exist.", 400)
+
+ # "To link a federated user who has previously signed in, you must first
+ # delete their existing profile."
+ source_profile = _federated_profile_username(
+ source["ProviderName"], source["ProviderAttributeValue"])
+ if source_profile in pool["_users"]:
+ return error_response_json(
+ "AliasExistsException",
+ "This user already exists in the user pool. To link this "
+ "federated identity, delete the existing profile first.", 400)
+
+ links = _provider_links(pool)
+ key = _provider_link_key(
+ source["ProviderName"], source["ProviderAttributeName"],
+ source["ProviderAttributeValue"])
+ linked_to = links.get(key)
+ if linked_to == destination_username:
+ return json_response({})
+ if linked_to:
+ return error_response_json(
+ "AliasExistsException",
+ "This federated identity is already linked to another user "
+ "profile.", 400)
+
+ identities = _user_identities(destination_user)
+ if len(identities) >= _PROVIDER_LINK_MAX_PER_USER:
+ return error_response_json(
+ "LimitExceededException",
+ "You can link up to "
+ f"{_PROVIDER_LINK_MAX_PER_USER} federated users to each user "
+ "profile.", 400)
+ attribute_names = {
+ stored_key.split("\x00")[1]
+ for stored_key in links
+ if stored_key.split("\x00")[0] == source["ProviderName"]
+ }
+ if (source["ProviderAttributeName"] not in attribute_names
+ and len(attribute_names) >= _PROVIDER_LINK_MAX_ATTRIBUTES_PER_IDP):
+ return error_response_json(
+ "LimitExceededException",
+ "You can link users to each IdP from up to "
+ f"{_PROVIDER_LINK_MAX_ATTRIBUTES_PER_IDP} IdP attribute claims.",
+ 400)
+
+ links[key] = destination_username
+ identities.append({
+ "userId": source["ProviderAttributeValue"],
+ "providerName": source["ProviderName"],
+ "providerType": _provider_type_for(pool, source["ProviderName"]),
+ # AWS carries the SAML entity issuer here and null for social IdPs. We
+ # never learn an entity id, so it stays null.
+ "issuer": None,
+ # A linked identity is never the profile's primary one.
+ "primary": False,
+ "dateCreated": int(time.time() * 1000),
+ })
+ _set_user_identities(destination_user, identities)
+ destination_user["UserLastModifiedDate"] = _now_epoch()
+ logger.info("Cognito: linked %s user %s to %s in pool %s",
+ source["ProviderName"], source["ProviderAttributeValue"],
+ destination_username, pid)
+ return json_response({})
+
+
+def _admin_disable_provider_for_user(data):
+ pid = data.get("UserPoolId")
+ pool, err = _resolve_pool(pid)
+ if err:
+ return err
+
+ user_identifier, err = _provider_user_identifier(data, "User")
+ if err:
+ return err
+
+ links = _provider_links(pool)
+ key = _provider_link_key(
+ user_identifier["ProviderName"],
+ user_identifier["ProviderAttributeName"],
+ user_identifier["ProviderAttributeValue"])
+ destination_username = links.get(key)
+ if not destination_username:
+ return error_response_json(
+ "ResourceNotFoundException",
+ "The specified federated identity is not linked to a user "
+ "profile.", 400)
+
+ del links[key]
+ destination_user = pool["_users"].get(destination_username)
+ if destination_user:
+ identities = [
+ identity for identity in _user_identities(destination_user)
+ if not (identity.get("providerName") == user_identifier["ProviderName"]
+ and identity.get("userId")
+ == user_identifier["ProviderAttributeValue"])
+ ]
+ _set_user_identities(destination_user, identities)
+ destination_user["UserLastModifiedDate"] = _now_epoch()
+ return json_response({})
+
+
+def _linked_username_for_federation(pool, provider_name, name_id, user_attrs):
+ """Resolve a federated sign-in to a linked local profile, if one exists.
+
+ Cognito looks for the link before it would create a `{Provider}_id`
+ profile, so a linked user signs in to the profile they were linked to
+ rather than getting a second one.
+ """
+ links = _provider_links(pool)
+ if not links:
+ return None
+ # "When you set ProviderAttributeName to Cognito_Subject, Amazon Cognito
+ # will automatically parse the default unique identifier found in the
+ # subject from the IdP token."
+ candidates = [("Cognito_Subject", name_id), ("", name_id)]
+ # "For OIDC, the ProviderAttributeName can be any mapped value from a claim
+ # in the ID token" — match against the mapped attributes of this sign-in.
+ candidates.extend(
+ (attribute_name, value)
+ for attribute_name, value in (user_attrs or {}).items()
+ if isinstance(value, str)
+ )
+ for attribute_name, value in candidates:
+ username = links.get(
+ _provider_link_key(provider_name, attribute_name, value))
+ if username and username in pool["_users"]:
+ return username
+ return None
+
+
+
def _get_user_pool_mfa_config(data):
pid = data.get("UserPoolId")
pool, err = _resolve_pool(pid)
@@ -4688,8 +4951,10 @@ def _saml2_idp_response(body: bytes, query_params):
cognito_attr = reverse_mapping.get(idp_claim, idp_claim)
user_attrs[cognito_attr] = value
- # Create or update federated user
- username = f"{provider_name}_{name_id}"
+ # Create or update federated user. A profile linked ahead of this first
+ # sign-in wins over minting a new `{Provider}_id` one (#1499).
+ username = (_linked_username_for_federation(pool, provider_name, name_id, user_attrs)
+ or f"{provider_name}_{name_id}")
existing_user = pool["_users"].get(username)
now = _now_epoch()
@@ -4919,7 +5184,8 @@ def _oauth2_idp_response(method, body, query_params):
return error_response_json("InvalidParameterException",
"OIDC id_token has no `sub` or `email` claim.", 400)
- username = f"{provider_name}_{name_id}"
+ username = (_linked_username_for_federation(pool, provider_name, name_id, user_attrs)
+ or f"{provider_name}_{name_id}")
existing_user = pool["_users"].get(username)
now = _now_epoch()
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index abf1d4fe..127395d9 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -7353,3 +7353,255 @@ def test_cognito_saml_authn_request_acs_uses_custom_domain(cognito_idp):
xml = zlib.decompress(base64.b64decode(saml_request), -15).decode()
assert f'AssertionConsumerServiceURL="https://{domain}/saml2/idpresponse"' in xml
assert f'urn:amazon:cognito:sp:{pid}' in xml
+
+
+# ---------------------------------------------------------------------------
+# Linking federated users to an existing profile (#1499)
+# ---------------------------------------------------------------------------
+
+def _saml_sign_in(cid, name_id, attributes):
+ """Drive /oauth2/authorize -> /saml2/idpresponse -> /oauth2/token."""
+ url = (
+ f"{ENDPOINT}/oauth2/authorize?"
+ f"response_type=code&client_id={cid}"
+ f"&redirect_uri=http://localhost:3000/callback"
+ f"&identity_provider=TestSAML&state=mystate&scope=openid"
+ )
+ try:
+ _no_redirect_opener.open(url)
+ raise AssertionError("Expected redirect")
+ except urllib.error.HTTPError as e:
+ location = e.headers.get("Location", "")
+ relay_state = _parse_qs(urlparse(location).query).get("RelayState", [""])[0]
+
+ form = _urlencode({
+ "SAMLResponse": _build_mock_saml_response(name_id, attributes),
+ "RelayState": relay_state,
+ }).encode()
+ req = urllib.request.Request(
+ f"{ENDPOINT}/saml2/idpresponse", data=form,
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ try:
+ _no_redirect_opener.open(req)
+ raise AssertionError("Expected redirect")
+ except urllib.error.HTTPError as e:
+ callback = e.headers.get("Location", "")
+ code = _parse_qs(urlparse(callback).query).get("code", [""])[0]
+
+ token_req = urllib.request.Request(
+ f"{ENDPOINT}/oauth2/token",
+ data=(f"grant_type=authorization_code&code={code}&client_id={cid}"
+ f"&redirect_uri=http://localhost:3000/callback").encode(),
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ with urllib.request.urlopen(token_req) as resp:
+ tokens = json.loads(resp.read())
+ payload = tokens["id_token"].split(".")[1]
+ payload += "=" * (4 - len(payload) % 4)
+ return json.loads(base64.urlsafe_b64decode(payload))
+
+
+def test_cognito_admin_link_provider_writes_identities_attribute(cognito_idp):
+ pid, _cid = _setup_saml_pool(cognito_idp)
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="carlos", MessageAction="SUPPRESS",
+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],
+ )
+
+ assert cognito_idp.admin_link_provider_for_user(
+ UserPoolId=pid,
+ DestinationUser={"ProviderName": "Cognito", "ProviderAttributeValue": "carlos"},
+ SourceUser={"ProviderName": "TestSAML", "ProviderAttributeName": "email",
+ "ProviderAttributeValue": "[email protected]"},
+ )["ResponseMetadata"]["HTTPStatusCode"] == 200
+
+ attrs = {a["Name"]: a["Value"] for a in cognito_idp.admin_get_user(
+ UserPoolId=pid, Username="carlos")["UserAttributes"]}
+ identities = json.loads(attrs["identities"])
+ assert len(identities) == 1
+ identity = identities[0]
+ assert identity["userId"] == "[email protected]"
+ assert identity["providerName"] == "TestSAML"
+ assert identity["providerType"] == "SAML"
+ # A linked identity is never the profile's primary one.
+ assert identity["primary"] is False
+ assert isinstance(identity["dateCreated"], int)
+ assert set(identity) == {
+ "userId", "providerName", "providerType", "issuer", "primary",
+ "dateCreated",
+ }
+
+
+def test_cognito_linked_federated_sign_in_resolves_to_the_local_profile(
+ cognito_idp,
+):
+ """A linked user signs in to the profile they were linked to, not a new one."""
+ pid, cid = _setup_saml_pool(cognito_idp)
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="carlos", MessageAction="SUPPRESS",
+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],
+ )
+ native_sub = {a["Name"]: a["Value"] for a in cognito_idp.admin_get_user(
+ UserPoolId=pid, Username="carlos")["UserAttributes"]}["sub"]
+
+ cognito_idp.admin_link_provider_for_user(
+ UserPoolId=pid,
+ DestinationUser={"ProviderName": "Cognito", "ProviderAttributeValue": "carlos"},
+ SourceUser={"ProviderName": "TestSAML",
+ "ProviderAttributeName": "Cognito_Subject",
+ "ProviderAttributeValue": "[email protected]"},
+ )
+
+ claims = _saml_sign_in(cid, "[email protected]", {
+ "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress":
+ "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "Carlos",
+ })
+
+ # "After Amazon Cognito matches your federated user to a linked profile,
+ # they always sign in to that profile."
+ assert claims["sub"] == native_sub
+ assert claims["cognito:username"] == "carlos"
+ # "Your user's ID token contains all of their associated providers in the
+ # identities claim."
+ assert isinstance(claims["identities"], list)
+ assert claims["identities"][0]["providerName"] == "TestSAML"
+
+ # No second `{Provider}_id` profile was minted.
+ with pytest.raises(ClientError) as exc_info:
+ cognito_idp.admin_get_user(
+ UserPoolId=pid, Username="[email protected]")
+ assert exc_info.value.response["Error"]["Code"] == "UserNotFoundException"
+
+ # "Your user pool then updates the linked local profile with the claims
+ # mapped from their sign-in."
+ attrs = {a["Name"]: a["Value"] for a in cognito_idp.admin_get_user(
+ UserPoolId=pid, Username="carlos")["UserAttributes"]}
+ assert attrs["name"] == "Carlos"
+
+
+def test_cognito_unlinked_federated_sign_in_still_creates_its_own_profile(
+ cognito_idp,
+):
+ pid, cid = _setup_saml_pool(cognito_idp)
+ claims = _saml_sign_in(cid, "[email protected]", {
+ "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress":
+ })
+ user = cognito_idp.admin_get_user(
+ UserPoolId=pid, Username="[email protected]")
+ assert user["UserStatus"] == "EXTERNAL_PROVIDER"
+ assert claims["cognito:username"] == "[email protected]"
+
+
+def test_cognito_admin_disable_provider_unlinks_and_restores_new_profiles(
+ cognito_idp,
+):
+ pid, cid = _setup_saml_pool(cognito_idp)
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="carlos", MessageAction="SUPPRESS",
+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],
+ )
+ source = {"ProviderName": "TestSAML",
+ "ProviderAttributeName": "Cognito_Subject",
+ "ProviderAttributeValue": "[email protected]"}
+ cognito_idp.admin_link_provider_for_user(
+ UserPoolId=pid,
+ DestinationUser={"ProviderName": "Cognito", "ProviderAttributeValue": "carlos"},
+ SourceUser=source,
+ )
+ cognito_idp.admin_disable_provider_for_user(UserPoolId=pid, User=source)
+
+ attrs = {a["Name"]: a["Value"] for a in cognito_idp.admin_get_user(
+ UserPoolId=pid, Username="carlos")["UserAttributes"]}
+ assert "identities" not in attrs
+
+ # Unlinked again, the same sign-in mints its own federated profile.
+ _saml_sign_in(cid, "[email protected]", {
+ "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress":
+ })
+ assert cognito_idp.admin_get_user(
+ UserPoolId=pid, Username="[email protected]",
+ )["UserStatus"] == "EXTERNAL_PROVIDER"
+
+ with pytest.raises(ClientError) as exc_info:
+ cognito_idp.admin_disable_provider_for_user(UserPoolId=pid, User=source)
+ assert exc_info.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_cognito_admin_link_provider_errors(cognito_idp):
+ pid, _cid = _setup_saml_pool(cognito_idp)
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="carlos", MessageAction="SUPPRESS",
+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],
+ )
+ dest = {"ProviderName": "Cognito", "ProviderAttributeValue": "carlos"}
+
+ def source(value, provider="TestSAML", attribute="Cognito_Subject"):
+ return {"ProviderName": provider, "ProviderAttributeName": attribute,
+ "ProviderAttributeValue": value}
+
+ with pytest.raises(ClientError) as exc_info:
+ cognito_idp.admin_link_provider_for_user(
+ UserPoolId=pid,
+ DestinationUser={"ProviderName": "Cognito",
+ "ProviderAttributeValue": "nobody"},
+ SourceUser=source("a"))
+ assert exc_info.value.response["Error"]["Code"] == "UserNotFoundException"
+
+ # "This user must be a federated user ... not another native user."
+ with pytest.raises(ClientError) as exc_info:
+ cognito_idp.admin_link_provider_for_user(
+ UserPoolId=pid, DestinationUser=dest,
+ SourceUser=source("carlos", provider="Cognito"))
+ assert exc_info.value.response["Error"]["Code"] == "InvalidParameterException"
+
+ # Relinking the same pair is a no-op; relinking to another profile is not.
+ cognito_idp.admin_link_provider_for_user(
+ UserPoolId=pid, DestinationUser=dest, SourceUser=source("dup"))
+ cognito_idp.admin_link_provider_for_user(
+ UserPoolId=pid, DestinationUser=dest, SourceUser=source("dup"))
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="other", MessageAction="SUPPRESS")
+ with pytest.raises(ClientError) as exc_info:
+ cognito_idp.admin_link_provider_for_user(
+ UserPoolId=pid,
+ DestinationUser={"ProviderName": "Cognito",
+ "ProviderAttributeValue": "other"},
+ SourceUser=source("dup"))
+ assert exc_info.value.response["Error"]["Code"] == "AliasExistsException"
+
+ # "You can link up to five federated users to each user profile."
+ for i in range(4):
+ cognito_idp.admin_link_provider_for_user(
+ UserPoolId=pid, DestinationUser=dest, SourceUser=source(f"extra-{i}"))
+ with pytest.raises(ClientError) as exc_info:
+ cognito_idp.admin_link_provider_for_user(
+ UserPoolId=pid, DestinationUser=dest, SourceUser=source("one-too-many"))
+ assert exc_info.value.response["Error"]["Code"] == "LimitExceededException"
+
+
+def test_cognito_admin_link_provider_rejects_an_already_signed_in_user(
+ cognito_idp,
+):
+ """"To link a federated user who has previously signed in, you must first
+ delete their existing profile."""
+ pid, cid = _setup_saml_pool(cognito_idp)
+ _saml_sign_in(cid, "[email protected]", {
+ "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress":
+ })
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="carlos", MessageAction="SUPPRESS")
+
+ with pytest.raises(ClientError) as exc_info:
+ cognito_idp.admin_link_provider_for_user(
+ UserPoolId=pid,
+ DestinationUser={"ProviderName": "Cognito",
+ "ProviderAttributeValue": "carlos"},
+ SourceUser={"ProviderName": "TestSAML",
+ "ProviderAttributeName": "Cognito_Subject",
+ "ProviderAttributeValue": "[email protected]"})
+ assert exc_info.value.response["Error"]["Code"] == "AliasExistsException"