Skip to content

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

fix(cognito): verify the USER_SRP_AUTH password proof and refuse an unconfirmed user (#1758)

iot-rocket9354887774eb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 869be815..549824d1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **Cognito — `USER_SRP_AUTH` checks the password** — `PASSWORD_VERIFIER` answered random `SALT` and `SRP_B` values and accepted any response, so a wrong password, a missing `TIMESTAMP` or a disabled or unconfirmed user all got tokens. The challenge now carries SRP-6a parameters with a stable salt per user, and the response is refused with `NotAuthorizedException` unless its signature proves the stored password. `TIMESTAMP` must read `EEE MMM d HH:mm:ss z yyyy` with `UTC` or `GMT` as the zone, the signature is computed over its canonical form, `PASSWORD_CLAIM_SIGNATURE` must be base64, and a temporary password leads to `NEW_PASSWORD_REQUIRED`. A client without `ALLOW_USER_SRP_AUTH`, an unknown user under `LEGACY`, a disabled and an unconfirmed user are refused at `InitiateAuth`. The built-in `PASSWORD_VERIFIER` step of `CUSTOM_WITH_SRP` gets the same check. Contributed by @iot-rocket.
- **EventBridge — `PutEvents` refuses `aws.*` sources** — an entry whose `Source` starts with `aws.` now fails with `NotAuthorizedForSourceException` in its result entry and counts in `FailedEntryCount`, while the other entries of the batch are still delivered; previously it was dispatched to rules and archives like a custom event.
- **Bedrock AgentCore — `InvokeAgentRuntime` enforces IAM policies** — with `AUTH=true`, runtime invocations now resolve to `bedrock-agentcore:InvokeAgentRuntime` and authorize against the ARN in the request path, so a policy can allow one runtime and deny another. Previously, the action was not extracted and the request bypassed identity-policy evaluation.
diff --git a/README.md b/README.md
index 7ef8143c..b56f5145 100644
--- a/README.md
+++ b/README.md
@@ -597,7 +597,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, CreateIdentityProvider, DescribeIdentityProvider, UpdateIdentityProvider, DeleteIdentityProvider, ListIdentityProviders, GetIdentityProviderByIdentifier, AdminLinkProviderForUser, AdminDisableProviderForUser, TagResource, UntagResource, ListTagsForResource; **Identity Pools**: CreateIdentityPool, DeleteIdentityPool, DescribeIdentityPool, ListIdentityPools, UpdateIdentityPool, GetId, GetCredentialsForIdentity, GetOpenIdToken, SetIdentityPoolRoles, GetIdentityPoolRoles, SetPrincipalTagAttributeMap, GetPrincipalTagAttributeMap, 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 verifies for real: the `AssociateSoftwareToken` secret is stored and checked with RFC 6238 (wrong code = `EnableSoftwareTokenMFAException` on verify, `CodeMismatchException` on the SOFTWARE_TOKEN_MFA challenge); 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); **`PreventUserExistenceErrors=ENABLED`** hides an unknown user across the auth flows (generic `NotAuthorizedException` incl. at `RespondToAuthChallenge`, simulated `CodeDeliveryDetails` with the masked `Destination` on `ForgotPassword`/`ResendConfirmationCode`, `CodeMismatchException` on `ConfirmForgotPassword`; the API default is `LEGACY`, as on AWS); `AdminListUserAuthEvents` requires `UserPoolAddOns.AdvancedSecurityMode` != `OFF`, else `UserPoolAddOnNotEnabledException` as on AWS — events themselves are never recorded, so the answer is always an empty list; **principal tag attribute maps** are stored and reported verbatim per identity provider, and a provider that was never configured answers `ResourceNotFoundException` (`No Principal Tags configured for Provider {name}`) as on AWS — `UseDefaults` round-trips but is never expanded into a tag map, since AWS applies the default claim mapping when it vends credentials, and `GetCredentialsForIdentity` registers its credentials as an STS session (GetCallerIdentity reports the pool role assumed as `CognitoIdentityCredentials`, and `AUTH=true` evaluates the session like any AssumeRole), though principal tags still never reach a session's `aws:PrincipalTag` policy context |
+| **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, SetPrincipalTagAttributeMap, GetPrincipalTagAttributeMap, ListIdentities, DescribeIdentity, MergeDeveloperIdentities, UnlinkDeveloperIdentity, UnlinkIdentity, TagResource, UntagResource, ListTagsForResource; **OAuth2**: /oauth2/token (client_credentials) | Stub JWT tokens (structurally valid base64url JWTs); `USER_SRP_AUTH` runs real SRP: `PASSWORD_VERIFIER` checks the client's proof against the stored password; **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 verifies for real: the `AssociateSoftwareToken` secret is stored and checked with RFC 6238 (wrong code = `EnableSoftwareTokenMFAException` on verify, `CodeMismatchException` on the SOFTWARE_TOKEN_MFA challenge); 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); **`PreventUserExistenceErrors=ENABLED`** hides an unknown user across the auth flows (generic `NotAuthorizedException` incl. at `RespondToAuthChallenge`, simulated `CodeDeliveryDetails` with the masked `Destination` on `ForgotPassword`/`ResendConfirmationCode`, `CodeMismatchException` on `ConfirmForgotPassword`; the API default is `LEGACY`, as on AWS); `AdminListUserAuthEvents` requires `UserPoolAddOns.AdvancedSecurityMode` != `OFF`, else `UserPoolAddOnNotEnabledException` as on AWS — events themselves are never recorded, so the answer is always an empty list; **principal tag attribute maps** are stored and reported verbatim per identity provider, and a provider that was never configured answers `ResourceNotFoundException` (`No Principal Tags configured for Provider {name}`) as on AWS — `UseDefaults` round-trips but is never expanded into a tag map, since AWS applies the default claim mapping when it vends credentials, and `GetCredentialsForIdentity` registers its credentials as an STS session (GetCallerIdentity reports the pool role assumed as `CognitoIdentityCredentials`, and `AUTH=true` evaluates the session like any AssumeRole), though principal tags still never reach a session's `aws:PrincipalTag` policy context |
| **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, UpdateApiKey, DeleteApiKey, ListApiKeys, CreateDataSource, GetDataSource, ListDataSources, UpdateDataSource, DeleteDataSource, CreateResolver, GetResolver, ListResolvers, UpdateResolver, DeleteResolver, CreateFunction, GetFunction, ListFunctions, UpdateFunction, DeleteFunction, CreateType, GetType, ListTypes, UpdateType, StartSchemaCreation, GetSchemaCreationStatus, GetIntrospectionSchema, PutGraphqlApiEnvironmentVariables, GetGraphqlApiEnvironmentVariables, CreateApiCache, GetApiCache, UpdateApiCache, DeleteApiCache, FlushApiCache, EvaluateCode, TagResource, UntagResource, ListTagsForResource; **Event APIs**: CreateApi, GetApi, ListApis, UpdateApi, DeleteApi, CreateChannelNamespace, GetChannelNamespace, ListChannelNamespaces, UpdateChannelNamespace, DeleteChannelNamespace, CreateApiKey, ListApiKeys, DeleteApiKey, HTTP Publish, WebSocket subscribe/publish | GraphQL execution goes through `graphql-core` when the API has a schema (parse, validate, execute; an AppSync prelude supplies the `AWS*` scalars and `@aws_*` directives; a schemaless API keeps a lenient path); **`APPSYNC_JS` resolvers execute** — unit and pipeline, `util`/`runtime`/`extensions` globals, the `@aws-appsync/utils/dynamodb` helpers, `NONE`/`HTTP`/`AMAZON_DYNAMODB`/`AWS_LAMBDA` data sources — on a pool of warm Node workers (one evaluation in flight per worker, 30s bound with kill-and-respawn, heap cap; reuses the image's Node, no new dependency); `GetIntrospectionSchema` serves SDL or a real `format=JSON` introspection document; the API cache is honored by the data plane under `FULL_REQUEST_CACHING` and `PER_RESOLVER_CACHING`; a data-plane request satisfying none of the API's auth modes answers `401 UnauthorizedException`, as on AWS (credentials are not verified — only their absence is refused). 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 6a60fd8a..2acc86d3 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -1513,21 +1513,182 @@ def _build_verify_auth_challenge_event(pool_id: str, client_id: str, username: s
-def _srp_password_verifier_challenge_parameters(username: str) -> dict:
- """ChallengeParameters shape Amplify expects for PASSWORD_VERIFIER."""
- return {
- "USER_ID_FOR_SRP": username,
- "SRP_B": base64.b64encode(secrets.token_bytes(128)).hex(),
- "SALT": base64.b64encode(secrets.token_bytes(16)).hex(),
- "SECRET_BLOCK": base64.b64encode(secrets.token_bytes(32)).decode(),
+# ---------------------------------------------------------------------------
+# SRP password verifier (USER_SRP_AUTH and CUSTOM_WITH_SRP)
+# ---------------------------------------------------------------------------
+
+# The 3072-bit prime of RFC 5054 (Appendix A) with generator 2, the group Cognito and its client SDKs
+# use; the RFC itself lists generator 5 for this prime.
+_SRP_N = int(
+ "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DD"
+ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
+ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
+ "83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
+ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
+ "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
+ "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
+ "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",
+ 16,
+)
+_SRP_G = 2
+_SRP_A_RE = re.compile(r"^[0-9a-fA-F]+$")
+_SRP_WEEKDAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
+_SRP_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
+# EEE MMM d HH:mm:ss z yyyy in English, parsed the way AWS does (measured): the weekday and
+# month names in any case, one or two digits for the day, and UTC or GMT as the zone. The zone
+# is the one part AWS reads case-sensitively, so `utc` is a format error where `wed` is not.
+_SRP_TIMESTAMP_RE = re.compile(
+ r"^((?i:Mon|Tue|Wed|Thu|Fri|Sat|Sun)) ((?i:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)) "
+ r"(\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (UTC|GMT) (\d{4})$"
+)
+
+
+def _srp_pad(n: int) -> bytes:
+ """Big-endian bytes with a leading zero byte when the high bit is set, as the SDKs pad."""
+ return n.to_bytes(n.bit_length() // 8 + 1, "big")
+
+
+def _srp_hash(*parts: bytes) -> int:
+ return int.from_bytes(hashlib.sha256(b"".join(parts)).digest(), "big")
+
+
+_SRP_K = _srp_hash(_srp_pad(_SRP_N), _srp_pad(_SRP_G))
+
+
+def _srp_verifier(pool_id: str, user_id: str, password: str, salt_hex: str) -> int:
+ """v = g^x with x = H(salt | H(poolName + userId + ":" + password))."""
+ pool_name = pool_id.split("_", 1)[-1]
+ inner = hashlib.sha256(f"{pool_name}{user_id}:{password}".encode()).digest()
+ return pow(_SRP_G, _srp_hash(_srp_pad(int(salt_hex, 16)), inner), _SRP_N)
+
+
+def _srp_salt(seed: str) -> str:
+ """A per-user salt derived from a stable seed, so it survives restarts like the user does.
+
+ The first byte is never zero: the JavaScript SDK pads the salt as an
+ integer and pycognito as the hex string, and the two only agree when no
+ leading zero byte can be dropped.
+ """
+ digest = hashlib.sha256(f"cognito-srp-salt:{seed}".encode()).digest()
+ while digest[0] == 0:
+ digest = hashlib.sha256(digest).digest()
+ return digest[:16].hex()
+
+
+def _srp_challenge(pool_id: str, user: dict | None, user_id: str, srp_a: str,
+ secret_block: str) -> tuple:
+ """PASSWORD_VERIFIER ChallengeParameters plus the state the response is checked against.
+
+ An unknown user (PreventUserExistenceErrors=ENABLED) gets a salt derived from
+ the name it was asked for and a verifier nobody can answer.
+ """
+ if user is not None:
+ seed = _attr_list_to_dict(user.get("Attributes", [])).get("sub") or user["Username"]
+ salt = _srp_salt(seed)
+ v = _srp_verifier(pool_id, user_id, user.get("_password") or "", salt)
+ else:
+ salt = _srp_salt(f"{pool_id}:{user_id}")
+ v = pow(_SRP_G, secrets.randbelow(_SRP_N - 2) + 1, _SRP_N)
+ b = secrets.randbelow(_SRP_N - 2) + 1
+ big_b = (_SRP_K * v + pow(_SRP_G, b, _SRP_N)) % _SRP_N
+ params = {
+ "SALT": salt,
+ "SECRET_BLOCK": secret_block,
+ "SRP_B": format(big_b, "x"),
+ "USERNAME": user_id,
+ "USER_ID_FOR_SRP": user_id,
}
+ state = {"srp_a": srp_a, "srp_b": format(big_b, "x"), "b": format(b, "x"),
+ "salt": salt, "secret_block": secret_block}
+ return params, state
+
+
+def _srp_canonical_timestamp(timestamp: str) -> str | None:
+ """The timestamp the proof is signed over, or None when it does not parse.
+
+ The format check is lenient, the signature is not: it is computed over the
+ canonical form (weekday derived from the date, unpadded day, UTC), so a
+ padded day or a wrong weekday parses and then fails the proof.
+ """
+ match = _SRP_TIMESTAMP_RE.match(timestamp)
+ if not match:
+ return None
+ _, month, day, hour, minute, second, _zone, year = match.groups()
+ month = month.capitalize()
+ try:
+ moment = datetime(int(year), _SRP_MONTHS.index(month) + 1, int(day),
+ int(hour), int(minute), int(second))
+ except ValueError:
+ return None
+ return (f"{_SRP_WEEKDAYS[moment.weekday()]} {month} {moment.day} "
+ f"{moment:%H:%M:%S} UTC {moment.year}")
-def _return_custom_auth_password_verifier(token: str, session: dict, username: str):
+def _srp_response_format_error(responses: dict):
+ """The request validation PASSWORD_VERIFIER applies before it looks at the proof.
+
+ The keys are checked in the order AWS names them (measured): an empty
+ response set is its own message, then USERNAME, TIMESTAMP, the signature
+ and the secret block.
+ """
+ if not responses:
+ return error_response_json("InvalidParameterException",
+ "Missing required parameter challenge responses.", 400)
+ for key in ("USERNAME", "TIMESTAMP", "PASSWORD_CLAIM_SIGNATURE", "PASSWORD_CLAIM_SECRET_BLOCK"):
+ if not responses.get(key):
+ return error_response_json("InvalidParameterException",
+ f"Missing required parameter {key}", 400)
+ if _srp_canonical_timestamp(responses["TIMESTAMP"]) is None:
+ return error_response_json("InvalidParameterException",
+ "TIMESTAMP format should be EEE MMM d HH:mm:ss z yyyy in english.", 400)
+ try:
+ base64.b64decode(responses["PASSWORD_CLAIM_SIGNATURE"], validate=True)
+ except (ValueError, base64.binascii.Error):
+ return error_response_json("InvalidParameterException",
+ "Invalid PASSWORD_CLAIM_SIGNATURE format. Must be a Base64 string.", 400)
+ return None
+
+
+def _srp_proof_valid(pool_id: str, user: dict, state: dict, responses: dict) -> bool:
+ """Recompute the client's PASSWORD_CLAIM_SIGNATURE from the stored password."""
+ secret_block = responses["PASSWORD_CLAIM_SECRET_BLOCK"]
+ if not hmac.compare_digest(secret_block.encode(), state["secret_block"].encode()):
+ return False
+ try:
+ big_a = int(state["srp_a"], 16)
+ except (TypeError, ValueError):
+ # CUSTOM_AUTH stores SRP_A as the client sent it; a value that is not
+ # hex cannot pass the proof.
+ return False
+ if big_a % _SRP_N == 0:
+ return False
+ big_b = int(state["srp_b"], 16)
+ u = _srp_hash(_srp_pad(big_a), _srp_pad(big_b))
+ if u == 0:
+ return False
+ user_id = user["Username"]
+ v = _srp_verifier(pool_id, user_id, user.get("_password") or "", state["salt"])
+ s = pow(big_a * pow(v, u, _SRP_N), int(state["b"], 16), _SRP_N)
+ prk = hmac.new(_srp_pad(u), _srp_pad(s), hashlib.sha256).digest()
+ key = hmac.new(prk, b"Caldera Derived Key\x01", hashlib.sha256).digest()[:16]
+ message = (pool_id.split("_", 1)[-1] + user_id).encode() + base64.b64decode(secret_block) \
+ + _srp_canonical_timestamp(responses["TIMESTAMP"]).encode()
+ expected = hmac.new(key, message, hashlib.sha256).digest()
+ return hmac.compare_digest(expected, base64.b64decode(responses["PASSWORD_CLAIM_SIGNATURE"]))
+
+
+def _awaits_password_proof(session: dict) -> bool:
+ """A USER_SRP_AUTH challenge, or a CUSTOM_WITH_SRP round still owing PASSWORD_VERIFIER."""
+ return session.get("auth_flow") == "USER_SRP_AUTH" or bool(session.get("pending_builtin_challenge"))
+
+
+def _return_custom_auth_password_verifier(token: str, session: dict, user: dict):
"""Return Cognito-owned PASSWORD_VERIFIER for CUSTOM_AUTH (CUSTOM_WITH_SRP)."""
- params = _srp_password_verifier_challenge_parameters(username)
+ params, session["srp"] = _srp_challenge(
+ session["pool_id"], user, user["Username"], session.get("srp_a", ""),
+ base64.b64encode(secrets.token_bytes(32)).decode(),
+ )
session["pending_builtin_challenge"] = "PASSWORD_VERIFIER"
- session["srp_challenge_parameters"] = params
return json_response({
"ChallengeName": "PASSWORD_VERIFIER",
"Session": token,
@@ -1570,9 +1731,7 @@ def _continue_custom_auth_after_define(
# Cognito-owned SRP challenges — do not invoke CreateAuthChallenge.
if next_challenge in ("PASSWORD_VERIFIER", "SRP_A"):
- return _return_custom_auth_password_verifier(
- token, session, session["username"]
- )
+ return _return_custom_auth_password_verifier(token, session, user)
if next_challenge != "CUSTOM_CHALLENGE":
del _challenge_sessions[token]
@@ -3348,6 +3507,118 @@ def _build_auth_result(pool_id: str, client_id: str, user: dict, nonce: str = ""
}
+def _password_auth_result(pool: dict, pid: str, cid: str, user: dict, username: str,
+ client_metadata: dict | None = None):
+ """What a verified password answers: NEW_PASSWORD_REQUIRED, an MFA challenge or tokens."""
+ if user.get("UserStatus") == "FORCE_CHANGE_PASSWORD":
+ session = base64.b64encode(secrets.token_bytes(32)).decode()
+ return json_response({
+ "ChallengeName": "NEW_PASSWORD_REQUIRED",
+ "Session": session,
+ "ChallengeParameters": {
+ "USER_ID_FOR_SRP": username,
+ "requiredAttributes": "[]",
+ "userAttributes": json.dumps(_attr_list_to_dict(user.get("Attributes", []))),
+ },
+ })
+ mfa_challenge = _mfa_challenge_for_user(pool, user, pid, username)
+ if mfa_challenge:
+ return json_response(mfa_challenge)
+ return json_response({"AuthenticationResult": _build_auth_result(
+ pid, cid, user, client_metadata=client_metadata)})
+
+
+def _initiate_user_srp_auth(pool: dict, pid: str, cid: str, auth_params: dict):
+ """USER_SRP_AUTH for InitiateAuth and AdminInitiateAuth: a real PASSWORD_VERIFIER.
+
+ AWS returns no Session here; the SECRET_BLOCK the client echoes back is the
+ handle to the pending challenge, valid for AuthSessionValidity.
+ """
+ flows = pool["_clients"].get(cid, {}).get("ExplicitAuthFlows") or []
+ # An empty or legacy-only ExplicitAuthFlows keeps SRP enabled.
+ if any(f.startswith("ALLOW_") for f in flows) and "ALLOW_USER_SRP_AUTH" not in flows:
+ return error_response_json("InvalidParameterException",
+ "USER_SRP_AUTH is not enabled for the client.", 400)
+ srp_a = auth_params.get("SRP_A")
+ if not srp_a:
+ return error_response_json("InvalidParameterException", "Missing required parameter SRP_A", 400)
+ if not _SRP_A_RE.match(srp_a):
+ return error_response_json(
+ "InvalidParameterException",
+ f"1 validation error detected: Value '{srp_a}' at 'sRPA' failed to satisfy constraint: "
+ "Member must satisfy regular expression pattern: ^[0-9a-fA-F]+$", 400)
+ username = auth_params.get("USERNAME")
+ user, _err = _resolve_user(pool, username)
+ # Username and aliases sign in; unlike the directory operations, the sub does not.
+ if user is not None and user["Username"] != username \
+ and _attr_list_to_dict(user.get("Attributes", [])).get("sub") == username:
+ user = None
+ if user is None:
+ if not username or not _hides_user_existence(pool, cid):
+ return error_response_json("UserNotFoundException", "User does not exist.", 400)
+ user_id = username
+ else:
+ if not user.get("Enabled", True):
+ return error_response_json("NotAuthorizedException", "User is disabled.", 400)
+ if user.get("UserStatus") == "UNCONFIRMED":
+ return error_response_json("UserNotConfirmedException", "User is not confirmed.", 400)
+ user_id = user["Username"]
+ token, session = _create_challenge_session(pid, cid, user_id)
+ session["auth_flow"] = "USER_SRP_AUTH"
+ params, session["srp"] = _srp_challenge(pid, user, user_id, srp_a, token)
+ return json_response({"ChallengeName": "PASSWORD_VERIFIER", "ChallengeParameters": params})
+
+
+def _respond_to_password_verifier(data: dict, cid: str):
+ """PASSWORD_VERIFIER for RespondToAuthChallenge and its admin variant.
+
+ A CUSTOM_WITH_SRP round arrives with the CUSTOM_AUTH Session and continues
+ with DefineAuthChallenge; USER_SRP_AUTH is found by its SECRET_BLOCK.
+ """
+ responses = data.get("ChallengeResponses") or {}
+ err = _srp_response_format_error(responses)
+ if err:
+ return err
+ denied = error_response_json("NotAuthorizedException", "Incorrect username or password.", 400)
+ token = data.get("Session")
+ session = _get_challenge_session(token)[0] if token else None
+ custom = session is not None and session.get("pending_builtin_challenge") == "PASSWORD_VERIFIER"
+ if not custom:
+ token = responses.get("PASSWORD_CLAIM_SECRET_BLOCK") or ""
+ session = _get_challenge_session(token)[0]
+ if session is None or "srp" not in session or session.get("pending_builtin_challenge"):
+ return denied
+ if session["client_id"] != cid:
+ return denied
+ pool = _user_pools.get(session["pool_id"])
+ if not pool:
+ return error_response_json("ResourceNotFoundException",
+ f"Pool {session['pool_id']} not found.", 400)
+ user = _resolve_user(pool, session["username"])[0]
+ # A challenge answers any number of proofs until the session expires, as on AWS.
+ if user is None or not _srp_proof_valid(session["pool_id"], user, session["srp"], responses):
+ return denied
+ refused = _password_signin_refused(user)
+ if refused:
+ return refused
+ client_metadata = data.get("ClientMetadata", {})
+ if not custom:
+ return _password_auth_result(pool, session["pool_id"], cid, user, user["Username"],
+ client_metadata)
+ _append_challenge_to_session(session, "PASSWORD_VERIFIER", True, None, {}, {})
+ session["pending_builtin_challenge"] = None
+ user_attrs = _attr_list_to_dict(user.get("Attributes", []))
+ define_result, err = _invoke_define_auth_challenge_trigger(
+ session["pool_id"], session["client_id"], session["username"],
+ user_attrs, session, client_metadata
+ )
+ if err:
+ return err
+ return _continue_custom_auth_after_define(
+ token, session, user, user_attrs, client_metadata, define_result
+ )
+
+
def _admin_initiate_auth(data):
pid = data.get("UserPoolId")
cid = data.get("ClientId")
@@ -3368,26 +3639,19 @@ def _admin_initiate_auth(data):
return _hidden_user_error(pool, cid, _err)
if not user.get("Enabled", True):
return error_response_json("NotAuthorizedException", "User is disabled.", 400)
+ # Answered before the password is looked at, right or wrong; a disabled
+ # user is refused as disabled first (measured).
+ if user.get("UserStatus") == "UNCONFIRMED":
+ return error_response_json("UserNotConfirmedException", "User is not confirmed.", 400)
refused = _password_signin_refused(user)
if refused:
return refused
if user.get("_password") and user["_password"] != password:
return error_response_json("NotAuthorizedException", "Incorrect username or password.", 400)
- if user.get("UserStatus") == "FORCE_CHANGE_PASSWORD":
- session = base64.b64encode(secrets.token_bytes(32)).decode()
- return json_response({
- "ChallengeName": "NEW_PASSWORD_REQUIRED",
- "Session": session,
- "ChallengeParameters": {
- "USER_ID_FOR_SRP": username,
- "requiredAttributes": "[]",
- "userAttributes": json.dumps(_attr_list_to_dict(user.get("Attributes", []))),
- },
- })
- mfa_challenge = _mfa_challenge_for_user(pool, user, pid, username)
- if mfa_challenge:
- return json_response(mfa_challenge)
- return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})
+ return _password_auth_result(pool, pid, cid, user, username)
+
+ if auth_flow == "USER_SRP_AUTH":
+ return _initiate_user_srp_auth(pool, pid, cid, auth_params)
if auth_flow in ("REFRESH_TOKEN_AUTH", "REFRESH_TOKEN"):
refresh_token = auth_params.get("REFRESH_TOKEN", "")
@@ -3444,6 +3708,7 @@ def _admin_initiate_auth(data):
# PASSWORD_VERIFIER (built-in), then later CUSTOM_CHALLENGE for MFA.
if auth_params.get("SRP_A") or auth_params.get("CHALLENGE_NAME") == "SRP_A":
_append_challenge_to_session(session, "SRP_A", True, None, {}, {})
+ session["srp_a"] = auth_params.get("SRP_A") or ""
# Invoke DefineAuthChallenge first
define_result, err = _invoke_define_auth_challenge_trigger(
@@ -3476,8 +3741,10 @@ def _admin_respond_to_auth_challenge(data):
challenge_answer = responses.get("ANSWER", "")
client_metadata = data.get("ClientMetadata", {})
- # Validate session
+ # Validate session; one awaiting a password proof is not a custom challenge.
session, err = _get_challenge_session(token)
+ if not err and _awaits_password_proof(session):
+ err = "InvalidParameterException: Session does not exist"
if err:
# Parse the error from the helper
if "Session does not exist" in err:
@@ -3533,36 +3800,7 @@ def _admin_respond_to_auth_challenge(data):
)
if challenge_name == "PASSWORD_VERIFIER":
- token = data.get("Session")
- session, sess_err = _get_challenge_session(token) if token else (None, None)
- if session is not None and session.get("pending_builtin_challenge") == "PASSWORD_VERIFIER":
- client_metadata = data.get("ClientMetadata", {})
- username = responses.get("USERNAME") or session["username"]
- pool = _user_pools.get(session["pool_id"])
- if not pool:
- return error_response_json("ResourceNotFoundException",
- f"Pool {session['pool_id']} not found.", 400)
- user, err = _resolve_user(pool, username)
- if err:
- del _challenge_sessions[token]
- return _hidden_user_error(pool, cid, err)
- refused = _password_signin_refused(user)
- if refused:
- return refused
- _append_challenge_to_session(session, "PASSWORD_VERIFIER", True, None, {}, {})
- session["pending_builtin_challenge"] = None
- user_attrs = _attr_list_to_dict(user.get("Attributes", []))
- define_result, err = _invoke_define_auth_challenge_trigger(
- session["pool_id"], session["client_id"], session["username"],
- user_attrs, session, client_metadata
- )
- if err:
- return err
- return _continue_custom_auth_after_define(
- token, session, user, user_attrs, client_metadata, define_result
- )
- return error_response_json("InvalidParameterException",
- "PASSWORD_VERIFIER session not found for CUSTOM_AUTH", 400)
+ return _respond_to_password_verifier(data, cid)
if challenge_name == "NEW_PASSWORD_REQUIRED":
username = responses.get("USERNAME")
@@ -3702,26 +3940,16 @@ def _initiate_auth(data):
return _hidden_user_error(pool, cid, _err)
if not user.get("Enabled", True):
return error_response_json("NotAuthorizedException", "User is disabled.", 400)
+ # Answered before the password is looked at, right or wrong; a disabled
+ # user is refused as disabled first (measured).
+ if user.get("UserStatus") == "UNCONFIRMED":
+ return error_response_json("UserNotConfirmedException", "User is not confirmed.", 400)
refused = _password_signin_refused(user)
if refused:
return refused
if user.get("_password") and user["_password"] != password:
return error_response_json("NotAuthorizedException", "Incorrect username or password.", 400)
- if user.get("UserStatus") == "FORCE_CHANGE_PASSWORD":
- session = base64.b64encode(secrets.token_bytes(32)).decode()
- return json_response({
- "ChallengeName": "NEW_PASSWORD_REQUIRED",
- "Session": session,
- "ChallengeParameters": {
- "USER_ID_FOR_SRP": username,
- "requiredAttributes": "[]",
- "userAttributes": json.dumps(_attr_list_to_dict(user.get("Attributes", []))),
- },
- })
- mfa_challenge = _mfa_challenge_for_user(pool, user, pid, username)
- if mfa_challenge:
- return json_response(mfa_challenge)
- return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})
+ return _password_auth_result(pool, pid, cid, user, username)
if auth_flow in ("REFRESH_TOKEN_AUTH", "REFRESH_TOKEN"):
result, err = _refresh_auth_result(pool, pid, cid, auth_params.get("REFRESH_TOKEN", ""))
@@ -3729,19 +3957,8 @@ def _initiate_auth(data):
return err
return json_response({"AuthenticationResult": result})
- # USER_SRP_AUTH — return SRP challenge stub
if auth_flow == "USER_SRP_AUTH":
- username = auth_params.get("USERNAME", "")
- return json_response({
- "ChallengeName": "PASSWORD_VERIFIER",
- "Session": base64.b64encode(secrets.token_bytes(32)).decode(),
- "ChallengeParameters": {
- "USER_ID_FOR_SRP": username,
- "SRP_B": base64.b64encode(secrets.token_bytes(128)).hex(),
- "SALT": base64.b64encode(secrets.token_bytes(16)).hex(),
- "SECRET_BLOCK": base64.b64encode(secrets.token_bytes(32)).decode(),
- },
- })
+ return _initiate_user_srp_auth(pool, pid, cid, auth_params)
if auth_flow == "CUSTOM_AUTH":
# Validate ExplicitAuthFlows
@@ -3778,6 +3995,7 @@ def _initiate_auth(data):
# PASSWORD_VERIFIER (built-in), then later CUSTOM_CHALLENGE for MFA.
if auth_params.get("SRP_A") or auth_params.get("CHALLENGE_NAME") == "SRP_A":
_append_challenge_to_session(session, "SRP_A", True, None, {}, {})
+ session["srp_a"] = auth_params.get("SRP_A") or ""
# Invoke DefineAuthChallenge first
define_result, err = _invoke_define_auth_challenge_trigger(
@@ -3815,8 +4033,10 @@ def _respond_to_auth_challenge(data):
challenge_answer = responses.get("ANSWER", "")
client_metadata = data.get("ClientMetadata", {})
- # Validate session
+ # Validate session; one awaiting a password proof is not a custom challenge.
session, err = _get_challenge_session(token)
+ if not err and _awaits_password_proof(session):
+ err = "InvalidParameterException: Session does not exist"
if err:
# Parse the error from the helper
if "Session does not exist" in err:
@@ -3872,53 +4092,7 @@ def _respond_to_auth_challenge(data):
)
if challenge_name == "PASSWORD_VERIFIER":
- token = data.get("Session")
- session, sess_err = _get_challenge_session(token) if token else (None, None)
- # CUSTOM_AUTH / CUSTOM_WITH_SRP session: stub-accept SRP claim, then DefineAuth.
- if session is not None and session.get("pending_builtin_challenge") == "PASSWORD_VERIFIER":
- client_metadata = data.get("ClientMetadata", {})
- username = responses.get("USERNAME") or session["username"]
- pool = _user_pools.get(session["pool_id"])
- if not pool:
- return error_response_json("ResourceNotFoundException",
- f"Pool {session['pool_id']} not found.", 400)
- user, err = _resolve_user(pool, username)
- if err:
- del _challenge_sessions[token]
- return _hidden_user_error(pool, cid, err)
- refused = _password_signin_refused(user)
- if refused:
- return refused
- # Emulator parity with USER_SRP_AUTH: accept Amplify's PASSWORD_CLAIM_* without
- # full SRP math.
- _append_challenge_to_session(session, "PASSWORD_VERIFIER", True, None, {}, {})
- session["pending_builtin_challenge"] = None
- user_attrs = _attr_list_to_dict(user.get("Attributes", []))
- define_result, err = _invoke_define_auth_challenge_trigger(
- session["pool_id"], session["client_id"], session["username"],
- user_attrs, session, client_metadata
- )
- if err:
- return err
- return _continue_custom_auth_after_define(
- token, session, user, user_attrs, client_metadata, define_result
- )
-
- username = responses.get("USERNAME")
- new_password = responses.get("NEW_PASSWORD") or responses.get("PASSWORD")
- client_metadata = data.get("ClientMetadata", {})
- user, _err = _resolve_user(pool, username)
- if _err:
- return _hidden_user_error(pool, cid, _err)
- refused = _password_signin_refused(user)
- if refused:
- return refused
- if new_password:
- user["_password"] = new_password
- user["UserStatus"] = "CONFIRMED"
- user["UserLastModifiedDate"] = _now_epoch()
- return json_response({"AuthenticationResult": _build_auth_result(
- pid, cid, user, client_metadata=client_metadata)})
+ return _respond_to_password_verifier(data, cid)
if challenge_name == "NEW_PASSWORD_REQUIRED":
username = responses.get("USERNAME")
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index 0f556f31..06337451 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -1,10 +1,14 @@
"""Cognito tests — user pools, identity pools, OAuth2/OIDC flows, auth-code persistence."""
import base64
+import datetime
+import hashlib
+import hmac
import importlib
import io
import json
import os
+import secrets
import time
import urllib.error
import urllib.request
@@ -333,6 +337,26 @@ def test_cognito_initiate_auth_user_password(cognito_idp):
assert "IdToken" in result
assert "RefreshToken" in result
[email protected]("admin", [False, True], ids=["user-password-auth", "admin-user-password-auth"])
[email protected]("password", ["GinaPass1!", "Wrong1!"], ids=["right-password", "wrong-password"])
+def test_cognito_password_auth_unconfirmed_user_is_refused(cognito_idp, admin, password):
+ """An unconfirmed user is refused before the password is checked."""
+ pid = cognito_idp.create_user_pool(PoolName="UnconfirmedPool")["UserPool"]["Id"]
+ cid = cognito_idp.create_user_pool_client(
+ UserPoolId=pid, ClientName="UnconfirmedApp",
+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_ADMIN_USER_PASSWORD_AUTH"],
+ )["UserPoolClient"]["ClientId"]
+ cognito_idp.sign_up(ClientId=cid, Username="gina", Password="GinaPass1!")
+ params = {"USERNAME": "gina", "PASSWORD": password}
+ with pytest.raises(ClientError) as exc:
+ if admin:
+ cognito_idp.admin_initiate_auth(UserPoolId=pid, ClientId=cid, AuthFlow="ADMIN_USER_PASSWORD_AUTH",
+ AuthParameters=params)
+ else:
+ cognito_idp.initiate_auth(ClientId=cid, AuthFlow="USER_PASSWORD_AUTH", AuthParameters=params)
+ assert exc.value.response["Error"]["Code"] == "UserNotConfirmedException"
+ assert exc.value.response["Error"]["Message"] == "User is not confirmed."
+
def test_cognito_signup_and_confirm(cognito_idp):
pid = cognito_idp.create_user_pool(PoolName="SignupPool")["UserPool"]["Id"]
cid = cognito_idp.create_user_pool_client(UserPoolId=pid, ClientName="SignupApp")["UserPoolClient"]["ClientId"]
@@ -6902,32 +6926,90 @@ def test_custom_auth_with_srp_full_flow_issues_tokens(cognito_idp, lam):
"DefineAuthChallenge": define_arn,
})
- step1 = cognito_idp.initiate_auth(
- ClientId=cid,
- AuthFlow="CUSTOM_AUTH",
- AuthParameters={
- "USERNAME": "[email protected]",
- "CHALLENGE_NAME": "SRP_A",
- "SRP_A": "ab" * 128,
- },
- )
- assert step1["ChallengeName"] == "PASSWORD_VERIFIER"
- secret = step1["ChallengeParameters"]["SECRET_BLOCK"]
+ def respond(password):
+ a, big_a = _srp_a()
+ step1 = cognito_idp.initiate_auth(
+ ClientId=cid,
+ AuthFlow="CUSTOM_AUTH",
+ AuthParameters={
+ "USERNAME": "[email protected]",
+ "CHALLENGE_NAME": "SRP_A",
+ "SRP_A": format(big_a, "x"),
+ },
+ )
+ assert step1["ChallengeName"] == "PASSWORD_VERIFIER"
+ return cognito_idp.respond_to_auth_challenge(
+ ClientId=cid,
+ ChallengeName="PASSWORD_VERIFIER",
+ Session=step1["Session"],
+ ChallengeResponses=_srp_responses(pid, step1["ChallengeParameters"], password, a, big_a),
+ )
- step2 = cognito_idp.respond_to_auth_challenge(
- ClientId=cid,
- ChallengeName="PASSWORD_VERIFIER",
- Session=step1["Session"],
- ChallengeResponses={
- "USERNAME": "[email protected]",
- "PASSWORD_CLAIM_SECRET_BLOCK": secret,
- "PASSWORD_CLAIM_SIGNATURE": "deadbeef",
- "TIMESTAMP": "Tue Jul 28 17:40:00 UTC 2026",
- },
- )
- assert "AuthenticationResult" in step2
+ step2 = respond("Pass1234!")
assert "AccessToken" in step2["AuthenticationResult"]
+ # The built-in step verifies the proof like USER_SRP_AUTH does.
+ with pytest.raises(ClientError) as exc:
+ respond("Wrong1234!")
+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"
+
+
[email protected]("admin", [False, True], ids=["respond", "admin-respond"])
[email protected]("handle", ["user-srp-secret-block", "custom-with-srp-pending-verifier"])
+def test_custom_challenge_refuses_a_session_awaiting_a_password_proof(cognito_idp, lam, handle, admin):
+ """CUSTOM_CHALLENGE only answers a custom challenge: a pending PASSWORD_VERIFIER,
+ whether the USER_SRP_AUTH SECRET_BLOCK or a CUSTOM_WITH_SRP Session, is refused
+ before any trigger runs, so the answer cannot stand in for the password proof."""
+ verify_handler = (
+ "def handler(event, ctx):\n"
+ " event['response']['answerCorrect'] = True\n"
+ " return event\n"
+ )
+ define_handler = (
+ "def handler(event, ctx):\n"
+ " session = event['request']['session']\n"
+ " if session and session[-1].get('challengeName') == 'SRP_A':\n"
+ " event['response']['challengeName'] = 'PASSWORD_VERIFIER'\n"
+ " elif session and session[-1].get('challengeResult'):\n"
+ " event['response']['issueTokens'] = True\n"
+ " elif not session:\n"
+ " event['response']['challengeName'] = 'CUSTOM_CHALLENGE'\n"
+ " else:\n"
+ " event['response']['failAuthentication'] = True\n"
+ " return event\n"
+ )
+ pid, _ = _setup_pool(cognito_idp, "CustomSrpBypassPool", {
+ "VerifyAuthChallengeResponse": _create_lambda(lam, "verify-srp-bypass", verify_handler),
+ "DefineAuthChallenge": _create_lambda(lam, "define-srp-bypass", define_handler),
+ })
+ cid = cognito_idp.create_user_pool_client(
+ UserPoolId=pid, ClientName="srp-and-custom",
+ ExplicitAuthFlows=["ALLOW_USER_SRP_AUTH", "ALLOW_CUSTOM_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
+ )["UserPoolClient"]["ClientId"]
+ srp_a = format(_srp_a()[1], "x")
+ if handle == "user-srp-secret-block":
+ started = cognito_idp.initiate_auth(
+ ClientId=cid, AuthFlow="USER_SRP_AUTH",
+ AuthParameters={"USERNAME": "[email protected]", "SRP_A": srp_a})
+ session = started["ChallengeParameters"]["SECRET_BLOCK"]
+ else:
+ started = cognito_idp.initiate_auth(
+ ClientId=cid, AuthFlow="CUSTOM_AUTH",
+ AuthParameters={"USERNAME": "[email protected]", "CHALLENGE_NAME": "SRP_A", "SRP_A": srp_a})
+ session = started["Session"]
+ assert started["ChallengeName"] == "PASSWORD_VERIFIER"
+
+ respond = {"ClientId": cid, "ChallengeName": "CUSTOM_CHALLENGE", "Session": session,
+ "ChallengeResponses": {"USERNAME": "[email protected]", "ANSWER": "anything"}}
+ with pytest.raises(ClientError) as exc:
+ if admin:
+ cognito_idp.admin_respond_to_auth_challenge(UserPoolId=pid, **respond)
+ else:
+ cognito_idp.respond_to_auth_challenge(**respond)
+ # No AWS measurement of this mismatch; the emulator's error for an unusable session.
+ assert exc.value.response["Error"]["Code"] == "InvalidParameterException"
+ assert exc.value.response["Error"]["Message"] == "Session does not exist"
+
def test_custom_auth_define_receives_client_metadata(cognito_idp, lam):
"""ClientMetadata on RespondToAuthChallenge is passed into DefineAuthChallenge."""
@@ -8053,7 +8135,8 @@ def test_cognito_admin_disable_provider_deactivates_native_user(cognito_idp):
pid = cognito_idp.create_user_pool(PoolName="NativeDisablePool")["UserPool"]["Id"]
cid = cognito_idp.create_user_pool_client(
UserPoolId=pid, ClientName="c",
- ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_USER_SRP_AUTH",
+ "ALLOW_REFRESH_TOKEN_AUTH"],
)["UserPoolClient"]["ClientId"]
cognito_idp.admin_create_user(UserPoolId=pid, Username="gina", MessageAction="SUPPRESS")
cognito_idp.admin_set_user_password(
@@ -8074,18 +8157,9 @@ def test_cognito_admin_disable_provider_deactivates_native_user(cognito_idp):
AuthParameters={"USERNAME": "gina", "PASSWORD": "Passw0rd!"})
assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"
- # SRP is password sign-in too: answering PASSWORD_VERIFIER must refuse.
- chal = cognito_idp.initiate_auth(
- ClientId=cid, AuthFlow="USER_SRP_AUTH",
- AuthParameters={"USERNAME": "gina", "SRP_A": "1" * 16})
+ # SRP is password sign-in too: even a correct PASSWORD_VERIFIER must refuse.
with pytest.raises(ClientError) as exc:
- cognito_idp.respond_to_auth_challenge(
- ClientId=cid, ChallengeName="PASSWORD_VERIFIER",
- Session=chal["Session"],
- ChallengeResponses={"USERNAME": "gina",
- "PASSWORD_CLAIM_SIGNATURE": "sig",
- "PASSWORD_CLAIM_SECRET_BLOCK": "blk",
- "TIMESTAMP": "now"})
+ _srp_sign_in(cognito_idp, pid, cid, "gina", "Passw0rd!")
assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"
@@ -8306,37 +8380,371 @@ def test_cognito_prevent_user_existence_errors_admin_directory_still_reports(cog
def test_cognito_prevent_user_existence_errors_masks_srp_challenge(cognito_idp):
"""USER_SRP_AUTH must not leak at RespondToAuthChallenge.
- This is the flow a browser SDK uses. InitiateAuth answers a
- PASSWORD_VERIFIER challenge without resolving the user at all, so masking
- InitiateAuth alone would leave the whole browser sign-in leaking one step
- later, where the password proof is checked.
+ This is the flow a browser SDK uses. With ENABLED, InitiateAuth answers an
+ unknown user with a PASSWORD_VERIFIER challenge like a known one, so the
+ refusal comes one step later, where the password proof is checked.
"""
- _pid, cid = _pool_with_client(cognito_idp, "ENABLED")
+ pid, cid = _pool_with_client(cognito_idp, "ENABLED")
def srp_failure(username):
- started = cognito_idp.initiate_auth(
- ClientId=cid, AuthFlow="USER_SRP_AUTH",
- AuthParameters={"USERNAME": username, "SRP_A": "ab" * 32},
- )
- assert started["ChallengeName"] == "PASSWORD_VERIFIER"
with pytest.raises(ClientError) as exc:
- cognito_idp.respond_to_auth_challenge(
- ClientId=cid, ChallengeName="PASSWORD_VERIFIER",
- Session=started["Session"],
- ChallengeResponses={
- "USERNAME": username,
- "PASSWORD_CLAIM_SIGNATURE": "sig",
- "PASSWORD_CLAIM_SECRET_BLOCK": "blk",
- "TIMESTAMP": "Mon Aug 31 00:00:00 UTC 2026",
- },
- )
+ _srp_sign_in(cognito_idp, pid, cid, username, "Wrong1!")
err = exc.value.response["Error"]
return err["Code"], err["Message"]
- assert srp_failure("[email protected]") == (
+ assert srp_failure("[email protected]") == srp_failure("[email protected]") == (
"NotAuthorizedException", "Incorrect username or password.")
+# ── USER_SRP_AUTH: PASSWORD_VERIFIER checks the proof ─────────────────────────
+
+_SRP_N = int(
+ "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DD"
+ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
+ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
+ "83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
+ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
+ "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
+ "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
+ "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",
+ 16,
+)
+
+
+def _srp_pad(n):
+ return n.to_bytes(n.bit_length() // 8 + 1, "big")
+
+
+def _srp_hash(*parts):
+ return int.from_bytes(hashlib.sha256(b"".join(parts)).digest(), "big")
+
+
+def _srp_a():
+ a = secrets.randbelow(_SRP_N - 2) + 1
+ return a, pow(2, a, _SRP_N)
+
+
+def _srp_timestamp():
+ now = datetime.datetime.now(datetime.timezone.utc)
+ return f"{now:%a %b} {now.day} {now:%H:%M:%S} UTC {now:%Y}"
+
+
+def _srp_responses(pool_id, params, password, a, big_a, timestamp=None):
+ """Client side of PASSWORD_VERIFIER, as the AWS SDKs compute it."""
+ timestamp = timestamp or _srp_timestamp()
+ pool_name, user_id = pool_id.split("_", 1)[1], params["USER_ID_FOR_SRP"]
+ big_b, salt = int(params["SRP_B"], 16), int(params["SALT"], 16)
+ k = _srp_hash(_srp_pad(_SRP_N), _srp_pad(2))
+ u = _srp_hash(_srp_pad(big_a), _srp_pad(big_b))
+ x = _srp_hash(_srp_pad(salt), hashlib.sha256(f"{pool_name}{user_id}:{password}".encode()).digest())
+ s = pow(big_b - k * pow(2, x, _SRP_N), a + u * x, _SRP_N)
+ prk = hmac.new(_srp_pad(u), _srp_pad(s), hashlib.sha256).digest()
+ key = hmac.new(prk, b"Caldera Derived Key\x01", hashlib.sha256).digest()[:16]
+ msg = (pool_name + user_id).encode() + base64.b64decode(params["SECRET_BLOCK"]) + timestamp.encode()
+ return {
+ "USERNAME": user_id,
+ "TIMESTAMP": timestamp,
+ "PASSWORD_CLAIM_SECRET_BLOCK": params["SECRET_BLOCK"],
+ "PASSWORD_CLAIM_SIGNATURE": base64.b64encode(hmac.new(key, msg, hashlib.sha256).digest()).decode(),
+ }
+
+
+def _srp_sign_in(cognito_idp, pid, cid, username, password, admin=False, overrides=None):
+ """USER_SRP_AUTH end to end; an override of None drops that response key, a TIMESTAMP one is signed."""
+ a, big_a = _srp_a()
+ auth = {"AuthFlow": "USER_SRP_AUTH", "ClientId": cid,
+ "AuthParameters": {"USERNAME": username, "SRP_A": format(big_a, "x")}}
+ started = (cognito_idp.admin_initiate_auth(UserPoolId=pid, **auth) if admin
+ else cognito_idp.initiate_auth(**auth))
+ assert started["ChallengeName"] == "PASSWORD_VERIFIER"
+ assert "Session" not in started
+ responses = _srp_responses(pid, started["ChallengeParameters"], password, a, big_a,
+ (overrides or {}).get("TIMESTAMP"))
+ for key, value in (overrides or {}).items():
+ if value is None:
+ responses.pop(key)
+ else:
+ responses[key] = value
+ respond = {"ClientId": cid, "ChallengeName": "PASSWORD_VERIFIER", "ChallengeResponses": responses}
+ if admin:
+ return started, cognito_idp.admin_respond_to_auth_challenge(UserPoolId=pid, **respond)
+ return started, cognito_idp.respond_to_auth_challenge(**respond)
+
+
+def _srp_pool(cognito_idp, flows=("ALLOW_USER_SRP_AUTH", "ALLOW_REFRESH_TOKEN_AUTH")):
+ pid = cognito_idp.create_user_pool(PoolName="SrpPool", AliasAttributes=["email"])["UserPool"]["Id"]
+ cid = cognito_idp.create_user_pool_client(
+ UserPoolId=pid, ClientName="srp", ExplicitAuthFlows=list(flows),
+ )["UserPoolClient"]["ClientId"]
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="srp-user", MessageAction="SUPPRESS",
+ UserAttributes=[{"Name": "email", "Value": "[email protected]"},
+ {"Name": "email_verified", "Value": "true"}],
+ )
+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="srp-user", Password="Correct1!", Permanent=True)
+ return pid, cid
+
+
[email protected]("login,admin,timestamp", [
+ ("srp-user", False, None),
+ ("srp-user", True, None),
+ ("[email protected]", False, None),
+ # Days old and a single-digit day: no freshness check.
+ ("srp-user", False, "Sat Sep 5 15:34:45 UTC 2026"),
+])
+def test_cognito_srp_correct_password_issues_tokens(cognito_idp, login, admin, timestamp):
+ pid, cid = _srp_pool(cognito_idp)
+ started, result = _srp_sign_in(cognito_idp, pid, cid, login, "Correct1!", admin=admin,
+ overrides={"TIMESTAMP": timestamp} if timestamp else None)
+ params = started["ChallengeParameters"]
+ assert params["USER_ID_FOR_SRP"] == params["USERNAME"] == "srp-user"
+ assert "AccessToken" in result["AuthenticationResult"]
+
+ again = cognito_idp.initiate_auth(
+ ClientId=cid, AuthFlow="USER_SRP_AUTH",
+ AuthParameters={"USERNAME": login, "SRP_A": format(_srp_a()[1], "x")},
+ )["ChallengeParameters"]
+ assert again["SALT"] == params["SALT"]
+ assert again["SRP_B"] != params["SRP_B"]
+
+
[email protected]("password,overrides,code,message", [
+ ("Wrong1!", {}, "NotAuthorizedException", "Incorrect username or password."),
+ ("Correct1!", {"PASSWORD_CLAIM_SIGNATURE": base64.b64encode(bytes(32)).decode()},
+ "NotAuthorizedException", "Incorrect username or password."),
+ ("Correct1!", {"PASSWORD_CLAIM_SECRET_BLOCK": base64.b64encode(bytes(32)).decode()},
+ "NotAuthorizedException", "Incorrect username or password."),
+ ("Correct1!", {"PASSWORD_CLAIM_SIGNATURE": "not!base64!!"},
+ "InvalidParameterException", "Invalid PASSWORD_CLAIM_SIGNATURE format. Must be a Base64 string."),
+ ("Correct1!", {"TIMESTAMP": None}, "InvalidParameterException", "Missing required parameter TIMESTAMP"),
+ ("Correct1!", {"PASSWORD_CLAIM_SIGNATURE": None},
+ "InvalidParameterException", "Missing required parameter PASSWORD_CLAIM_SIGNATURE"),
+ ("Correct1!", {"PASSWORD_CLAIM_SECRET_BLOCK": None},
+ "InvalidParameterException", "Missing required parameter PASSWORD_CLAIM_SECRET_BLOCK"),
+ ("Correct1!", {"USERNAME": None}, "InvalidParameterException", "Missing required parameter USERNAME"),
+ ("Correct1!", {"TIMESTAMP": "not-a-timestamp"},
+ "InvalidParameterException", "TIMESTAMP format should be EEE MMM d HH:mm:ss z yyyy in english."),
+ ("Correct1!", {"TIMESTAMP": "Tue Sep 015 15:34:45 UTC 2026"},
+ "InvalidParameterException", "TIMESTAMP format should be EEE MMM d HH:mm:ss z yyyy in english."),
+ # These parse, but the proof is checked over the canonical timestamp.
+ ("Correct1!", {"TIMESTAMP": "Sat Sep 05 15:34:45 UTC 2026"},
+ "NotAuthorizedException", "Incorrect username or password."),
+ ("Correct1!", {"TIMESTAMP": "Mon Sep 5 15:34:45 UTC 2026"},
+ "NotAuthorizedException", "Incorrect username or password."),
+ # AWS parses the names in any case and GMT as the zone (measured); the proof is over the canonical form.
+ ("Correct1!", {"TIMESTAMP": "wed sep 16 06:04:31 UTC 2026"},
+ "NotAuthorizedException", "Incorrect username or password."),
+ # The zone is the one part AWS reads case-sensitively (measured): lower-casing the whole
+ # stamp is a format error, while lower-casing only the names is not.
+ ("Correct1!", {"TIMESTAMP": "wed sep 16 06:04:31 utc 2026"},
+ "InvalidParameterException", "TIMESTAMP format should be EEE MMM d HH:mm:ss z yyyy in english."),
+ ("Correct1!", {"TIMESTAMP": "Wed Sep 16 08:04:31 CEST 2026"},
+ "InvalidParameterException", "TIMESTAMP format should be EEE MMM d HH:mm:ss z yyyy in english."),
+ ("Correct1!", {"TIMESTAMP": "Wed Sep 16 06:04:31 Z 2026"},
+ "InvalidParameterException", "TIMESTAMP format should be EEE MMM d HH:mm:ss z yyyy in english."),
+ # Several keys missing: AWS names USERNAME, then TIMESTAMP, then the signature, then the block.
+ ("Correct1!", {"TIMESTAMP": None, "PASSWORD_CLAIM_SIGNATURE": None},
+ "InvalidParameterException", "Missing required parameter TIMESTAMP"),
+ ("Correct1!", {"TIMESTAMP": None, "PASSWORD_CLAIM_SIGNATURE": None, "PASSWORD_CLAIM_SECRET_BLOCK": None},
+ "InvalidParameterException", "Missing required parameter TIMESTAMP"),
+ ("Correct1!", {"USERNAME": None, "TIMESTAMP": None},
+ "InvalidParameterException", "Missing required parameter USERNAME"),
+ ("Correct1!", {"PASSWORD_CLAIM_SECRET_BLOCK": None, "PASSWORD_CLAIM_SIGNATURE": None},
+ "InvalidParameterException", "Missing required parameter PASSWORD_CLAIM_SIGNATURE"),
+], ids=["wrong-password", "zeroed-signature", "wrong-secret-block", "signature-not-base64",
+ "timestamp-missing", "signature-missing", "secret-block-missing", "username-missing",
+ "timestamp-malformed", "timestamp-three-digit-day", "timestamp-zero-padded-day", "timestamp-wrong-weekday",
+ "timestamp-lowercase-names", "timestamp-lowercase-zone", "timestamp-cest", "timestamp-z",
+ "timestamp-and-signature-missing",
+ "all-but-username-missing", "username-and-timestamp-missing", "signature-and-block-missing"])
+def test_cognito_srp_bad_proof_is_refused(cognito_idp, password, overrides, code, message):
+ pid, cid = _srp_pool(cognito_idp)
+ with pytest.raises(ClientError) as exc:
+ _srp_sign_in(cognito_idp, pid, cid, "srp-user", password, overrides=overrides)
+ assert exc.value.response["Error"]["Code"] == code
+ assert exc.value.response["Error"]["Message"] == message
+
+
+def test_cognito_srp_salt_never_starts_with_a_zero_byte():
+ """The JavaScript SDK pads the salt as an integer, pycognito as a string; a
+ leading zero byte is the one case where they disagree, so no salt has one."""
+ from ministack.services import cognito as cognito_module
+
+ seeds = [str(n) for n in range(4000)]
+ salts = [cognito_module._srp_salt(seed) for seed in seeds]
+ assert all(len(salt) == 32 and not salt.startswith("00") for salt in salts)
+ # The loop re-hashes at least once for some seed in this range, so it is exercised.
+ plain = [hashlib.sha256(f"cognito-srp-salt:{seed}".encode()).digest()[:16].hex() for seed in seeds]
+ assert any(p.startswith("00") for p in plain)
+ assert len(set(salts)) == len(salts)
+
+
+def test_cognito_srp_proof_refuses_a_non_hex_srp_a():
+ """CUSTOM_AUTH stores SRP_A as sent; the proof check answers False instead of raising."""
+ from ministack.services import cognito as cognito_module
+
+ state = {"srp_a": "zzz-not-hex", "srp_b": "2", "b": "1", "salt": "00", "secret_block": "YQ=="}
+ assert cognito_module._srp_proof_valid("eu-central-1_pool", {"Username": "u"}, state,
+ {"PASSWORD_CLAIM_SECRET_BLOCK": "YQ==", "TIMESTAMP": "x",
+ "PASSWORD_CLAIM_SIGNATURE": "YQ=="}) is False
+
+
[email protected]("flow", ["USER_SRP_AUTH", "USER_PASSWORD_AUTH", "ADMIN_USER_PASSWORD_AUTH"])
+def test_cognito_disabled_unconfirmed_user_is_refused_as_disabled(cognito_idp, flow):
+ """A user that is both UNCONFIRMED and disabled is refused as disabled in every flow (measured)."""
+ pid, cid = _srp_pool(cognito_idp, ["ALLOW_USER_SRP_AUTH", "ALLOW_USER_PASSWORD_AUTH", "ALLOW_ADMIN_USER_PASSWORD_AUTH"])
+ cognito_idp.sign_up(ClientId=cid, Username="srp-both", Password="Correct1!")
+ cognito_idp.admin_disable_user(UserPoolId=pid, Username="srp-both")
+ params = {"USERNAME": "srp-both"}
+ params.update({"SRP_A": format(_srp_a()[1], "x")} if flow == "USER_SRP_AUTH" else {"PASSWORD": "Correct1!"})
+ with pytest.raises(ClientError) as exc:
+ if flow == "ADMIN_USER_PASSWORD_AUTH":
+ cognito_idp.admin_initiate_auth(UserPoolId=pid, ClientId=cid, AuthFlow=flow, AuthParameters=params)
+ else:
+ cognito_idp.initiate_auth(ClientId=cid, AuthFlow=flow, AuthParameters=params)
+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"
+ assert exc.value.response["Error"]["Message"] == "User is disabled."
+
+
+def test_cognito_srp_empty_challenge_responses(cognito_idp):
+ """No response key at all is its own message on AWS (measured)."""
+ pid, cid = _srp_pool(cognito_idp)
+ started = cognito_idp.initiate_auth(ClientId=cid, AuthFlow="USER_SRP_AUTH",
+ AuthParameters={"USERNAME": "srp-user", "SRP_A": format(_srp_a()[1], "x")})
+ assert started["ChallengeName"] == "PASSWORD_VERIFIER"
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.respond_to_auth_challenge(ClientId=cid, ChallengeName="PASSWORD_VERIFIER", ChallengeResponses={})
+ assert exc.value.response["Error"]["Code"] == "InvalidParameterException"
+ assert exc.value.response["Error"]["Message"] == "Missing required parameter challenge responses."
+
+
[email protected]("case,code,message", [
+ ("missing SRP_A", "InvalidParameterException", "Missing required parameter SRP_A"),
+ ("non-hex SRP_A", "InvalidParameterException",
+ "1 validation error detected: Value 'zzz-not-hex' at 'sRPA' failed to satisfy constraint: "
+ "Member must satisfy regular expression pattern: ^[0-9a-fA-F]+$"),
+ ("client without SRP", "InvalidParameterException", "USER_SRP_AUTH is not enabled for the client."),
+ ("unknown user", "UserNotFoundException", "User does not exist."),
+ ("sub as username", "UserNotFoundException", "User does not exist."),
+ ("disabled", "NotAuthorizedException", "User is disabled."),
+ ("unconfirmed", "UserNotConfirmedException", "User is not confirmed."),
+], ids=["missing-srp-a", "non-hex-srp-a", "client-without-srp", "unknown-user", "sub-as-username", "disabled", "unconfirmed"])
+def test_cognito_srp_initiate_refusals(cognito_idp, case, code, message):
+ flows = ["ALLOW_USER_PASSWORD_AUTH"] if case == "client without SRP" else ["ALLOW_USER_SRP_AUTH"]
+ pid, cid = _srp_pool(cognito_idp, flows)
+ username, srp_a = "srp-user", format(_srp_a()[1], "x")
+ if case == "missing SRP_A":
+ srp_a = None
+ elif case == "non-hex SRP_A":
+ srp_a = "zzz-not-hex"
+ elif case == "unknown user":
+ username = "ghost"
+ elif case == "sub as username":
+ attrs = cognito_idp.admin_get_user(UserPoolId=pid, Username=username)["UserAttributes"]
+ username = next(a["Value"] for a in attrs if a["Name"] == "sub")
+ elif case == "disabled":
+ cognito_idp.admin_disable_user(UserPoolId=pid, Username=username)
+ elif case == "unconfirmed":
+ username = "srp-unconfirmed"
+ cognito_idp.sign_up(ClientId=cid, Username=username, Password="Correct1!")
+ auth_params = {"USERNAME": username, **({"SRP_A": srp_a} if srp_a else {})}
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.initiate_auth(ClientId=cid, AuthFlow="USER_SRP_AUTH", AuthParameters=auth_params)
+ assert exc.value.response["Error"]["Code"] == code
+ assert exc.value.response["Error"]["Message"] == message
+
+
+def test_cognito_srp_challenge_answers_repeated_proofs(cognito_idp):
+ """A wrong proof does not use up the challenge, and a correct one can be sent twice."""
+ pid, cid = _srp_pool(cognito_idp)
+ a, big_a = _srp_a()
+ params = cognito_idp.initiate_auth(
+ ClientId=cid, AuthFlow="USER_SRP_AUTH",
+ AuthParameters={"USERNAME": "srp-user", "SRP_A": format(big_a, "x")},
+ )["ChallengeParameters"]
+
+ def respond(password):
+ return cognito_idp.respond_to_auth_challenge(
+ ClientId=cid, ChallengeName="PASSWORD_VERIFIER",
+ ChallengeResponses=_srp_responses(pid, params, password, a, big_a),
+ )
+
+ with pytest.raises(ClientError) as exc:
+ respond("Wrong1!")
+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"
+ assert "AccessToken" in respond("Correct1!")["AuthenticationResult"]
+ assert "AccessToken" in respond("Correct1!")["AuthenticationResult"]
+
+
[email protected]("big_a", [0, _SRP_N], ids=["srp-a-zero", "srp-a-equals-n"])
+def test_cognito_srp_degenerate_srp_a_gets_a_challenge_then_fails_the_proof(cognito_idp, big_a):
+ """AWS answers SRP_A = 0 or N with a challenge and refuses the proof (measured)."""
+ pid, cid = _srp_pool(cognito_idp)
+ started = cognito_idp.initiate_auth(
+ ClientId=cid, AuthFlow="USER_SRP_AUTH",
+ AuthParameters={"USERNAME": "srp-user", "SRP_A": format(big_a, "x")},
+ )
+ assert started["ChallengeName"] == "PASSWORD_VERIFIER"
+ assert "Session" not in started
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.respond_to_auth_challenge(
+ ClientId=cid, ChallengeName="PASSWORD_VERIFIER",
+ ChallengeResponses=_srp_responses(pid, started["ChallengeParameters"], "Correct1!", 1, big_a),
+ )
+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"
+ assert exc.value.response["Error"]["Message"] == "Incorrect username or password."
+
+
[email protected]("sent,signed", [
+ ("Wed Sep 16 06:04:31 GMT 2026", "Wed Sep 16 06:04:31 UTC 2026"),
+ ("wed sep 16 06:04:31 UTC 2026", "Wed Sep 16 06:04:31 UTC 2026"),
+ ("Sat Sep 05 15:34:45 UTC 2026", "Sat Sep 5 15:34:45 UTC 2026"),
+], ids=["zone-gmt", "lowercase-names", "zero-padded-day"])
+def test_cognito_srp_proof_over_the_canonical_timestamp_issues_tokens(cognito_idp, sent, signed):
+ """The accepting half of the canonical-form rule (measured): a stamp that parses but
+ differs from its canonical form is accepted when the proof is signed over that form."""
+ pid, cid = _srp_pool(cognito_idp)
+ a, big_a = _srp_a()
+ started = cognito_idp.initiate_auth(
+ ClientId=cid, AuthFlow="USER_SRP_AUTH",
+ AuthParameters={"USERNAME": "srp-user", "SRP_A": format(big_a, "x")},
+ )
+ responses = _srp_responses(pid, started["ChallengeParameters"], "Correct1!", a, big_a, signed)
+ responses["TIMESTAMP"] = sent
+ result = cognito_idp.respond_to_auth_challenge(
+ ClientId=cid, ChallengeName="PASSWORD_VERIFIER", ChallengeResponses=responses)
+ assert "AccessToken" in result["AuthenticationResult"]
+
+
+def test_cognito_srp_client_without_explicit_auth_flows_gets_the_challenge(cognito_idp):
+ """A client created with no ExplicitAuthFlows allows USER_SRP_AUTH (measured)."""
+ pid, _ = _srp_pool(cognito_idp)
+ cid = cognito_idp.create_user_pool_client(UserPoolId=pid, ClientName="no-flows")["UserPoolClient"]["ClientId"]
+ started = cognito_idp.initiate_auth(
+ ClientId=cid, AuthFlow="USER_SRP_AUTH",
+ AuthParameters={"USERNAME": "srp-user", "SRP_A": format(_srp_a()[1], "x")},
+ )
+ assert started["ChallengeName"] == "PASSWORD_VERIFIER"
+ assert "Session" not in started
+
+
+def test_cognito_srp_temporary_password_requires_new_password(cognito_idp):
+ pid, cid = _srp_pool(cognito_idp)
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="srp-new", TemporaryPassword="Temp1234!",
+ MessageAction="SUPPRESS")
+ _, challenge = _srp_sign_in(cognito_idp, pid, cid, "srp-new", "Temp1234!")
+ assert challenge["ChallengeName"] == "NEW_PASSWORD_REQUIRED"
+ assert {"requiredAttributes", "userAttributes"} <= set(challenge["ChallengeParameters"])
+
+ done = cognito_idp.respond_to_auth_challenge(
+ ClientId=cid, ChallengeName="NEW_PASSWORD_REQUIRED", Session=challenge["Session"],
+ ChallengeResponses={"USERNAME": "srp-new", "NEW_PASSWORD": "Changed1!"},
+ )
+ assert "AccessToken" in done["AuthenticationResult"]
+ _, result = _srp_sign_in(cognito_idp, pid, cid, "srp-new", "Changed1!")
+ assert "AccessToken" in result["AuthenticationResult"]
+
+
def test_cognito_identity_pool_credentials_are_sts_sessions(cognito_identity):
"""Vended identity-pool credentials compose with the rest of the emulator:
GetCallerIdentity resolves them as the pool role assumed with the AWS