Skip to content

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

feat(cognito): record auth events and accept event feedback (#2347)

iot-rockete574cc9de4ab
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d3a318c3..6bfdb46b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Added
+- **Cognito — auth events** — `AdminListUserAuthEvents` always answered an empty list; on a pool with threat protection on (`AdvancedSecurityMode` `AUDIT` or `ENFORCED`), password, SRP and admin sign-ins, their MFA answers and password changes are now logged as `SignIn` and `PasswordChange` events with the caller's address, listed newest first with `MaxResults`/`NextToken` paging, and `AdminUpdateAuthEventFeedback` and `UpdateAuthEventFeedback` are implemented. Contributed by @iot-rocket.
- **CloudFront — web ACL association for distributions** — `AssociateDistributionWebACL` and `DisassociateDistributionWebACL` set and clear `WebACLId` in the distribution's config, so `GetDistribution`, `GetDistributionConfig` and `ListDistributions` report it, and answer with the new `ETag`. They need the current `If-Match` (`InvalidIfMatchVersion`, `PreconditionFailed`) and a `WebACLArn`, and a missing distribution answers `NoSuchDistribution`. The web ACL is not looked up and is not evaluated. Contributed by @OS-kiranmalsetty.
- **Route 53 — VPC associations for private hosted zones** — `AssociateVPCWithHostedZone`, `DisassociateVPCFromHostedZone` and `ListHostedZonesByVPC` (paged with `MaxItems` and `NextToken`). They refuse a public zone (`PublicZoneVPCAssociation`), a VPC already associated with a zone of the same name (`ConflictingDomainExists`), a VPC the zone doesn't have (404 `VPCAssociationNotFound`) and the zone's last VPC (`LastVPCAssociation`). Contributed by @kharabasz.
diff --git a/README.md b/README.md
index 79549fa5..aa947dd5 100644
--- a/README.md
+++ b/README.md
@@ -644,7 +644,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, PutFileSystemPolicy, DescribeFileSystemPolicy, DeleteFileSystemPolicy, UpdateFileSystemProtection, CreateReplicationConfiguration, DescribeReplicationConfigurations, DeleteReplicationConfiguration, DescribeAccountPreferences, PutAccountPreferences | REST/JSON `/2015-02-01/*`; CreationToken idempotency; FileSystem deletion blocked when mount targets exist or it is in a replication configuration; `CreateMountTarget` checks the subnet, security groups, zone and address; replication creates records only, nothing is copied; CFN `AWS::EFS::FileSystem`, `MountTarget` and `AccessPoint` supported |
| **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, UpdateUserPoolDomain, SetUICustomization, GetUICustomization, 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 (authorization_code, refresh_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); `AdminCreateUser` invokes the pool's `CustomMessage` trigger for the invitation; 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, AdminUpdateAuthEventFeedback, UpdateAuthEventFeedback, AdminInitiateAuth, AdminRespondToAuthChallenge, InitiateAuth, RespondToAuthChallenge, GlobalSignOut, RevokeToken, SignUp, ConfirmSignUp, ForgotPassword, ConfirmForgotPassword, ChangePassword, GetUser, UpdateUserAttributes, DeleteUser, CreateGroup, DeleteGroup, GetGroup, ListGroups, ListUsersInGroup, CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain, UpdateUserPoolDomain, SetUICustomization, GetUICustomization, 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 (authorization_code, refresh_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); `AdminCreateUser` invokes the pool's `CustomMessage` trigger for the invitation; 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 — with it on, sign-ins, their MFA answers and password changes are recorded as auth events (no risk scoring: every event reports `NoRisk`), and `AdminUpdateAuthEventFeedback` stores feedback on them; **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/app.py b/ministack/app.py
index c39c894f..a5cfd5cd 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -235,6 +235,7 @@ from ministack.core.responses import (
fix_error_content_type,
fix_success_content_type,
set_request_account_id,
+ set_request_client_ip,
set_request_region,
)
from ministack.core.router import detect_service, extract_access_key_id, extract_region
@@ -3162,6 +3163,7 @@ async def app(scope, receive, send):
# USE_SSL terminates TLS here, so no proxy sets the header; fill it in.
if scope.get("scheme") == "https":
headers.setdefault("x-forwarded-proto", "https")
+ set_request_client_ip((scope.get("client") or ("127.0.0.1",))[0])
if AUTH:
pin_request_origin((scope.get("client") or ("127.0.0.1",))[0],
headers.get("x-forwarded-proto", "").split(",")[0].strip().lower() == "https")
diff --git a/ministack/core/responses.py b/ministack/core/responses.py
index 5c6b220e..805abef6 100644
--- a/ministack/core/responses.py
+++ b/ministack/core/responses.py
@@ -103,6 +103,23 @@ def get_region() -> str:
return _request_region.get()
+# Request-scoped caller address, for records that report where a request came from.
+_request_client_ip: contextvars.ContextVar[str] = contextvars.ContextVar(
+ "_request_client_ip",
+ default="127.0.0.1",
+)
+
+
+def set_request_client_ip(address: str) -> None:
+ """Set the caller's address for the current request."""
+ _request_client_ip.set(address)
+
+
+def get_request_client_ip() -> str:
+ """Return the caller's address for the current request."""
+ return _request_client_ip.get()
+
+
@contextlib.contextmanager
def request_scope(account_id: str, region: str):
"""Pin the request-scoped account and region around a block that reaches
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 06bf7fc6..40b6509a 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -20,6 +20,7 @@ User Pools operations:
GetUser, UpdateUserAttributes, DeleteUser,
AdminAddUserToGroup, AdminRemoveUserFromGroup,
AdminListGroupsForUser, AdminListUserAuthEvents,
+ AdminUpdateAuthEventFeedback, UpdateAuthEventFeedback,
CreateGroup, DeleteGroup, GetGroup, ListGroups,
AdminConfirmSignUp, AdminDisableUser, AdminEnableUser,
AdminResetUserPassword, AdminUserGlobalSignOut,
@@ -89,6 +90,7 @@ from ministack.core.responses import (
error_response_json,
get_account_id,
get_region,
+ get_request_client_ip,
json_response,
new_uuid,
set_request_account_id,
@@ -2423,6 +2425,7 @@ _UNSIGNED_IDP_ACTIONS = {
"RevokeToken",
"SetUserMFAPreference",
"SignUp",
+ "UpdateAuthEventFeedback",
"UpdateUserAttributes",
"VerifySoftwareToken",
}
@@ -2662,6 +2665,8 @@ async def _dispatch_idp(action: str, data: dict):
"AdminUserGlobalSignOut": _admin_user_global_sign_out,
"AdminListGroupsForUser": _admin_list_groups_for_user,
"AdminListUserAuthEvents": _admin_list_user_auth_events,
+ "AdminUpdateAuthEventFeedback": _admin_update_auth_event_feedback,
+ "UpdateAuthEventFeedback": _update_auth_event_feedback,
"AdminAddUserToGroup": _admin_add_user_to_group,
"AdminRemoveUserFromGroup": _admin_remove_user_from_group,
# Auth flows
@@ -3997,27 +4002,95 @@ def _admin_list_groups_for_user(data):
return json_response({"Groups": [_group_out(g) for g in groups]})
+_AUTH_EVENTS_MAX_RESULTS = 60
+_AUTH_EVENT_ID_RE = re.compile(r"[\w+-]+")
+
+
+def _auth_events_add_on_error(pool: dict):
+ """UserPoolAddOnNotEnabledException for a pool without threat protection, else None."""
+ if _threat_protection_on(pool.get("UserPoolAddOns")):
+ return None
+ return error_response_json(
+ "UserPoolAddOnNotEnabledException",
+ "This is an add on feature. Please update AdvancedSecurityMode"
+ " for your user pool to access this API.",
+ 400,
+ )
+
+
+def _record_auth_event(pool: dict, user: dict, data: dict, event_type: str, response: str,
+ challenges: tuple = (), session: str | None = None) -> None:
+ """Log an auth event with the verdict AWS gives a low-risk request, when the pool logs events."""
+ if not _threat_protection_on(pool.get("UserPoolAddOns")):
+ return
+ event = {
+ "EventId": new_uuid(),
+ "EventType": event_type,
+ "CreationDate": round(_now_epoch(), 3),
+ "EventResponse": response,
+ "EventRisk": {"RiskDecision": "NoRisk", "CompromisedCredentialsDetected": False},
+ "ChallengeResponses": [{"ChallengeName": name, "ChallengeResponse": result}
+ for name, result in challenges],
+ # The admin flows' ContextData names the user's address; "null" is what AWS
+ # reports for a place it cannot locate, and nothing here locates one.
+ "EventContextData": {
+ "IpAddress": (data.get("ContextData") or {}).get("IpAddress") or get_request_client_ip(),
+ "City": "null",
+ "Country": "null",
+ },
+ }
+ if session:
+ # The challenge session that will answer this InProgress sign-in.
+ event["_session"] = session
+ user.setdefault("_auth_events", []).append(event)
+
+
+def _finish_auth_event(user: dict, session: str | None, challenge: str, passed: bool) -> None:
+ """Close the sign-in event the answered challenge session left InProgress, with its result."""
+ for event in reversed(user.get("_auth_events", [])):
+ if session and event.get("_session") == session:
+ del event["_session"]
+ event["EventResponse"] = "Pass" if passed else "Fail"
+ event["ChallengeResponses"].append(
+ {"ChallengeName": challenge, "ChallengeResponse": "Success" if passed else "Failure"})
+ return
+
+
+_JSON_INTEGER_ERRORS = {
+ str: "STRING_VALUE can not be converted to an Integer",
+ list: "Start of list found where not expected",
+ dict: "Start of structure or map found where not expected.",
+}
+
+
def _admin_list_user_auth_events(data):
- """List a user's auth events, gated on user-pool add-ons as real Cognito is.
-
- Auth events are never recorded here (there is no event store), so a pool
- with add-ons enabled always answers an empty list. A pool without add-ons
- (AdvancedSecurityMode OFF or UserPoolAddOns absent) is refused with
- UserPoolAddOnNotEnabledException. The add-on gate fires before the user is
- resolved — measured against the live service (2026-08-26): an unknown user
- in a pool without add-ons gets the add-on error, not UserNotFound.
- """
+ """List a user's auth events newest first; pools without threat protection are refused first."""
+ raw = data.get("MaxResults")
+ if isinstance(raw, bool):
+ return error_response_json("SerializationException",
+ f"{str(raw).upper()}_VALUE can not be converted to an Integer", 400,
+ message_key="Message")
+ if type(raw) in _JSON_INTEGER_ERRORS:
+ return error_response_json("SerializationException", _JSON_INTEGER_ERRORS[type(raw)], 400,
+ message_key="Message")
+ max_results = int(raw or 0)
+ if not 0 <= max_results <= _AUTH_EVENTS_MAX_RESULTS:
+ bound = ("greater than or equal to 0" if max_results < 0
+ else f"less than or equal to {_AUTH_EVENTS_MAX_RESULTS}")
+ return error_response_json(
+ "InvalidParameterException",
+ f"1 validation error detected: Value '{max_results}' at 'maxResults' failed to satisfy"
+ f" constraint: Member must have value {bound}",
+ 400,
+ )
+ max_results = max_results or _AUTH_EVENTS_MAX_RESULTS
pid = data.get("UserPoolId")
pool, err = _resolve_pool(pid)
if err:
return err
- if (pool.get("UserPoolAddOns") or {}).get("AdvancedSecurityMode", "OFF") == "OFF":
- return error_response_json(
- "UserPoolAddOnNotEnabledException",
- "This is an add on feature. Please update AdvancedSecurityMode"
- " for your user pool to access this API.",
- 400,
- )
+ err = _auth_events_add_on_error(pool)
+ if err:
+ return err
username = data.get("Username")
user, _ = _resolve_user(pool, username)
if user is None:
@@ -4025,7 +4098,78 @@ def _admin_list_user_auth_events(data):
return error_response_json(
"UserNotFoundException", "User does not exist.", 400,
)
- return json_response({"AuthEvents": []})
+ events = user.get("_auth_events", [])[::-1]
+ # The token names the last event listed, as AWS's does: <EventId>#<CreationDate>.
+ after = (data.get("NextToken") or "").split("#", 1)[0]
+ start = next((i + 1 for i, event in enumerate(events) if event["EventId"] == after), 0)
+ page = [{k: v for k, v in event.items() if not k.startswith("_")}
+ for event in events[start:start + max_results]]
+ resp = {"AuthEvents": page}
+ if start + max_results < len(events):
+ last = page[-1]
+ stamp = datetime.fromtimestamp(last["CreationDate"], timezone.utc).isoformat(timespec="milliseconds")
+ resp["NextToken"] = f"{last['EventId']}#{stamp.replace('+00:00', 'Z')}"
+ return json_response(resp)
+
+
+def _auth_event_feedback_error(data: dict):
+ """The input validation AWS applies to EventId and FeedbackValue."""
+ value = data.get("FeedbackValue")
+ if value not in ("Invalid", "Valid"):
+ return error_response_json(
+ "InvalidParameterException",
+ f"1 validation error detected: Value '{value}' at 'feedbackValue' failed to satisfy"
+ " constraint: Member must satisfy enum value set: [Invalid, Valid]",
+ 400,
+ )
+ event_id = data.get("EventId") or ""
+ if not _AUTH_EVENT_ID_RE.fullmatch(event_id):
+ return error_response_json(
+ "InvalidParameterException",
+ f"1 validation error detected: Value '{event_id}' at 'eventId' failed to satisfy"
+ " constraint: Member must satisfy regular expression pattern: [\\w+-]+",
+ 400,
+ )
+ return None
+
+
+def _admin_update_auth_event_feedback(data):
+ """Record the admin's Valid or Invalid verdict on one of a user's auth events."""
+ err = _auth_event_feedback_error(data)
+ if err:
+ return err
+ pool, err = _resolve_pool(data.get("UserPoolId"))
+ if err:
+ return err
+ err = _auth_events_add_on_error(pool)
+ if err:
+ return err
+ user, _ = _resolve_user(pool, data.get("Username"))
+ if user is None:
+ return error_response_json("NotAuthorizedException", "Incorrect username or password.", 400)
+ event = next((e for e in user.get("_auth_events", []) if e["EventId"] == data["EventId"]), None)
+ if event is None:
+ return error_response_json("InvalidParameterException", "EventId is invalid", 400)
+ event["EventFeedback"] = {
+ "FeedbackValue": data["FeedbackValue"],
+ "Provider": "Admin",
+ "FeedbackDate": round(_now_epoch(), 3),
+ }
+ return json_response({})
+
+
+def _update_auth_event_feedback(data):
+ """User feedback by a notification email's token; no notification is sent here, so no token is valid."""
+ err = _auth_event_feedback_error(data)
+ if err:
+ return err
+ pool, err = _resolve_pool(data.get("UserPoolId"))
+ if err:
+ return err
+ err = _auth_events_add_on_error(pool)
+ if err:
+ return err
+ return error_response_json("NotAuthorizedException", "Invalid session provided", 400)
def _admin_add_user_to_group(data):
@@ -4120,8 +4264,13 @@ 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):
+ client_metadata: dict | None = None, data: dict | None = None):
"""What a verified password answers: NEW_PASSWORD_REQUIRED, an MFA challenge or tokens."""
+ mfa_challenge = None
+ if user.get("UserStatus") != "FORCE_CHANGE_PASSWORD":
+ mfa_challenge = _mfa_challenge_for_user(pool, user, pid, username)
+ _record_auth_event(pool, user, data or {}, "SignIn", "InProgress" if mfa_challenge else "Pass",
+ (("Password", "Success"),), (mfa_challenge or {}).get("Session"))
if user.get("UserStatus") == "FORCE_CHANGE_PASSWORD":
session = base64.b64encode(secrets.token_bytes(32)).decode()
return json_response({
@@ -4133,7 +4282,6 @@ def _password_auth_result(pool: dict, pid: str, cid: str, user: dict, username:
"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(
@@ -4209,6 +4357,8 @@ def _respond_to_password_verifier(data: dict, cid: str):
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):
+ if user is not None and not custom:
+ _record_auth_event(pool, user, data, "SignIn", "Fail", (("Password", "Failure"),))
return denied
refused = _password_signin_refused(user)
if refused:
@@ -4218,7 +4368,7 @@ def _respond_to_password_verifier(data: dict, cid: str):
client_metadata = data.get("ClientMetadata", {})
if not custom:
return _password_auth_result(pool, session["pool_id"], cid, user, user["Username"],
- client_metadata)
+ client_metadata, data)
_append_challenge_to_session(session, "PASSWORD_VERIFIER", True, None, {}, {})
session["pending_builtin_challenge"] = None
user_attrs = _attr_list_to_dict(user.get("Attributes", []))
@@ -4261,11 +4411,12 @@ def _admin_initiate_auth(data):
if refused:
return refused
if user.get("_password") and user["_password"] != password:
+ _record_auth_event(pool, user, data, "SignIn", "Fail", (("Password", "Failure"),))
return error_response_json("NotAuthorizedException", "Incorrect username or password.", 400)
# Only a correct password learns that a reset is required.
if user.get("UserStatus") == "RESET_REQUIRED":
return _password_reset_required()
- return _password_auth_result(pool, pid, cid, user, username)
+ return _password_auth_result(pool, pid, cid, user, username, data=data)
if auth_flow == "USER_SRP_AUTH":
return _initiate_user_srp_auth(pool, pid, cid, auth_params)
@@ -4423,6 +4574,7 @@ def _admin_respond_to_auth_challenge(data):
user["_password"] = new_password
user["UserStatus"] = "CONFIRMED"
user["UserLastModifiedDate"] = _now_epoch()
+ _record_auth_event(pool, user, data, "PasswordChange", "Pass")
return json_response({"AuthenticationResult": _build_auth_result(
pid, cid, user, client_metadata=client_metadata)})
@@ -4448,8 +4600,10 @@ def _admin_respond_to_auth_challenge(data):
totp_secret = user.get("_totp_secret")
if totp_secret and not _totp_matches(
totp_secret, responses.get("SOFTWARE_TOKEN_MFA_CODE", "")):
+ _finish_auth_event(user, data.get("Session"), "Mfa", False)
return error_response_json(
"CodeMismatchException", "Invalid code received for user", 400)
+ _finish_auth_event(user, data.get("Session"), "Mfa", True)
return json_response({"AuthenticationResult": _build_auth_result(
pid, cid, user, client_metadata=client_metadata)})
@@ -4579,11 +4733,12 @@ def _initiate_auth(data):
if refused:
return refused
if user.get("_password") and user["_password"] != password:
+ _record_auth_event(pool, user, data, "SignIn", "Fail", (("Password", "Failure"),))
return error_response_json("NotAuthorizedException", "Incorrect username or password.", 400)
# Only a correct password learns that a reset is required.
if user.get("UserStatus") == "RESET_REQUIRED":
return _password_reset_required()
- return _password_auth_result(pool, pid, cid, user, username)
+ return _password_auth_result(pool, pid, cid, user, username, data=data)
if auth_flow in ("REFRESH_TOKEN_AUTH", "REFRESH_TOKEN"):
result, err = _refresh_auth_result(pool, pid, cid, auth_params.get("REFRESH_TOKEN", ""))
@@ -4743,6 +4898,7 @@ def _respond_to_auth_challenge(data):
user["_password"] = new_password
user["UserStatus"] = "CONFIRMED"
user["UserLastModifiedDate"] = _now_epoch()
+ _record_auth_event(pool, user, data, "PasswordChange", "Pass")
return json_response({"AuthenticationResult": _build_auth_result(
pid, cid, user, client_metadata=client_metadata)})
@@ -4759,8 +4915,10 @@ def _respond_to_auth_challenge(data):
totp_secret = user.get("_totp_secret")
if totp_secret and not _totp_matches(
totp_secret, responses.get("SOFTWARE_TOKEN_MFA_CODE", "")):
+ _finish_auth_event(user, data.get("Session"), "Mfa", False)
return error_response_json(
"CodeMismatchException", "Invalid code received for user", 400)
+ _finish_auth_event(user, data.get("Session"), "Mfa", True)
return json_response({"AuthenticationResult": _build_auth_result(
pid, cid, user, client_metadata=client_metadata)})
@@ -5062,6 +5220,7 @@ def _change_password(data):
return pw_err
user["_password"] = proposed
user["UserLastModifiedDate"] = _now_epoch()
+ _record_auth_event(pool, user, data, "PasswordChange", "Pass")
return json_response({})
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index f7053bd6..49c4c8e3 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -699,6 +699,274 @@ def test_cognito_admin_list_user_auth_events_requires_addons(cognito_idp):
assert exc.value.response["Error"]["Code"] == "UserNotFoundException"
assert exc.value.response["Error"]["Message"] == "User does not exist."
+
+def _auth_events_pool(cognito_idp, name, mode="AUDIT"):
+ """A pool with threat protection in `mode`, a client for every password flow and user 'eve'."""
+ pid = cognito_idp.create_user_pool(
+ PoolName=name, UserPoolAddOns={"AdvancedSecurityMode": mode},
+ )["UserPool"]["Id"]
+ cid = cognito_idp.create_user_pool_client(
+ UserPoolId=pid, ClientName="events",
+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_ADMIN_USER_PASSWORD_AUTH",
+ "ALLOW_USER_SRP_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
+ )["UserPoolClient"]["ClientId"]
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="eve", MessageAction="SUPPRESS")
+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="eve", Password="Correct1!", Permanent=True)
+ return pid, cid
+
+
+def _auth_event_summary(event):
+ return (event["EventType"], event["EventResponse"],
+ [(c["ChallengeName"], c["ChallengeResponse"]) for c in event["ChallengeResponses"]])
+
+
[email protected]("mode", ["AUDIT", "ENFORCED"])
+def test_cognito_auth_events_record_sign_ins(cognito_idp, mode):
+ """Password, admin and SRP sign-ins are logged newest first; a refresh and an unknown user are not."""
+ pid, cid = _auth_events_pool(cognito_idp, f"AuthEventsSignIn{mode}", mode)
+ password_auth = {"ClientId": cid, "AuthFlow": "USER_PASSWORD_AUTH"}
+ tokens = cognito_idp.initiate_auth(
+ **password_auth, AuthParameters={"USERNAME": "eve", "PASSWORD": "Correct1!"})["AuthenticationResult"]
+ with pytest.raises(ClientError):
+ cognito_idp.initiate_auth(**password_auth, AuthParameters={"USERNAME": "eve", "PASSWORD": "Wrong1!x"})
+ cognito_idp.admin_initiate_auth(
+ UserPoolId=pid, ClientId=cid, AuthFlow="ADMIN_USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "eve", "PASSWORD": "Correct1!"},
+ ContextData={"IpAddress": "203.0.113.10", "ServerName": "app.example.com", "ServerPath": "/login",
+ "HttpHeaders": [{"headerName": "User-Agent", "headerValue": "test"}]})
+ with pytest.raises(ClientError):
+ cognito_idp.admin_initiate_auth(
+ UserPoolId=pid, ClientId=cid, AuthFlow="ADMIN_USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "eve", "PASSWORD": "Wrong1!x"})
+ assert "AuthenticationResult" in _srp_sign_in(cognito_idp, pid, cid, "eve", "Correct1!")[1]
+ with pytest.raises(ClientError):
+ _srp_sign_in(cognito_idp, pid, cid, "eve", "Wrong1!x")
+ cognito_idp.initiate_auth(ClientId=cid, AuthFlow="REFRESH_TOKEN_AUTH",
+ AuthParameters={"REFRESH_TOKEN": tokens["RefreshToken"]})
+ with pytest.raises(ClientError):
+ cognito_idp.initiate_auth(**password_auth, AuthParameters={"USERNAME": "nobody", "PASSWORD": "Correct1!"})
+
+ events = cognito_idp.admin_list_user_auth_events(UserPoolId=pid, Username="eve")["AuthEvents"]
+ passed, failed = [("Password", "Success")], [("Password", "Failure")]
+ assert [_auth_event_summary(e) for e in events] == [
+ ("SignIn", "Fail", failed), ("SignIn", "Pass", passed),
+ ("SignIn", "Fail", failed), ("SignIn", "Pass", passed),
+ ("SignIn", "Fail", failed), ("SignIn", "Pass", passed),
+ ]
+ assert [e["CreationDate"] for e in events] == sorted((e["CreationDate"] for e in events), reverse=True)
+ for event in events:
+ assert str(_uuid_mod.UUID(event["EventId"])) == event["EventId"]
+ assert event["EventRisk"] == {"RiskDecision": "NoRisk", "CompromisedCredentialsDetected": False}
+ assert event["EventContextData"]["City"] == event["EventContextData"]["Country"] == "null"
+ assert "EventFeedback" not in event
+ ips = [e["EventContextData"]["IpAddress"] for e in events]
+ assert ips[3] == "203.0.113.10"
+ assert ips[0] and ips[0] != "203.0.113.10" and len(set(ips[:3] + ips[4:])) == 1
+
+ # The events belong to the user record: a user created again under the name has none.
+ cognito_idp.admin_delete_user(UserPoolId=pid, Username="eve")
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="eve", MessageAction="SUPPRESS")
+ assert cognito_idp.admin_list_user_auth_events(UserPoolId=pid, Username="eve")["AuthEvents"] == []
+
+
+def test_cognito_auth_events_mfa_and_password_changes(cognito_idp):
+ """An MFA sign-in is InProgress until answered; new and changed passwords log PasswordChange."""
+ pid, cid = _auth_events_pool(cognito_idp, "AuthEventsMfa")
+
+ def summaries(username):
+ events = cognito_idp.admin_list_user_auth_events(UserPoolId=pid, Username=username)["AuthEvents"]
+ return [_auth_event_summary(e) for e in events]
+
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="temp", MessageAction="SUPPRESS",
+ TemporaryPassword="Temporary1!")
+ started = cognito_idp.initiate_auth(ClientId=cid, AuthFlow="USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "temp", "PASSWORD": "Temporary1!"})
+ assert started["ChallengeName"] == "NEW_PASSWORD_REQUIRED"
+ tokens = cognito_idp.respond_to_auth_challenge(
+ ClientId=cid, ChallengeName="NEW_PASSWORD_REQUIRED", Session=started["Session"],
+ ChallengeResponses={"USERNAME": "temp", "NEW_PASSWORD": "Changed1!"})["AuthenticationResult"]
+ cognito_idp.change_password(AccessToken=tokens["AccessToken"], PreviousPassword="Changed1!",
+ ProposedPassword="Changed2!")
+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="temp", Password="Changed3!", Permanent=True)
+ assert summaries("temp") == [("PasswordChange", "Pass", []), ("PasswordChange", "Pass", []),
+ ("SignIn", "Pass", [("Password", "Success")])]
+
+ cognito_idp.set_user_pool_mfa_config(UserPoolId=pid, SoftwareTokenMfaConfiguration={"Enabled": True},
+ MfaConfiguration="OPTIONAL")
+ access = cognito_idp.initiate_auth(ClientId=cid, AuthFlow="USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "eve", "PASSWORD": "Correct1!"},
+ )["AuthenticationResult"]["AccessToken"]
+ secret = cognito_idp.associate_software_token(AccessToken=access)["SecretCode"]
+ cognito_idp.verify_software_token(AccessToken=access, UserCode=_totp_code(secret))
+ cognito_idp.admin_set_user_mfa_preference(UserPoolId=pid, Username="eve",
+ SoftwareTokenMfaSettings={"Enabled": True, "PreferredMfa": True})
+
+ def mfa_started():
+ started = cognito_idp.initiate_auth(ClientId=cid, AuthFlow="USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "eve", "PASSWORD": "Correct1!"})
+ assert started["ChallengeName"] == "SOFTWARE_TOKEN_MFA"
+ assert summaries("eve")[0] == ("SignIn", "InProgress", [("Password", "Success")])
+ return started["Session"]
+
+ def answer(session, code):
+ cognito_idp.respond_to_auth_challenge(
+ ClientId=cid, ChallengeName="SOFTWARE_TOKEN_MFA", Session=session,
+ ChallengeResponses={"USERNAME": "eve", "SOFTWARE_TOKEN_MFA_CODE": code})
+
+ # Two sign-ins wait on MFA at once: each answer closes its own session's event.
+ first, second = mfa_started(), mfa_started()
+ answer(first, _totp_code(secret))
+ assert summaries("eve")[:2] == [
+ ("SignIn", "InProgress", [("Password", "Success")]),
+ ("SignIn", "Pass", [("Password", "Success"), ("Mfa", "Success")]),
+ ]
+ with pytest.raises(ClientError) as exc:
+ answer(second, "000000" if _totp_code(secret) != "000000" else "111111")
+ assert exc.value.response["Error"]["Code"] == "CodeMismatchException"
+ cognito_idp.admin_disable_user(UserPoolId=pid, Username="eve")
+ with pytest.raises(ClientError):
+ cognito_idp.initiate_auth(ClientId=cid, AuthFlow="USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "eve", "PASSWORD": "Correct1!"})
+ assert summaries("eve") == [
+ ("SignIn", "Fail", [("Password", "Success"), ("Mfa", "Failure")]),
+ ("SignIn", "Pass", [("Password", "Success"), ("Mfa", "Success")]),
+ ("SignIn", "Pass", [("Password", "Success")]),
+ ]
+
+
+def test_cognito_auth_events_paging(cognito_idp):
+ """MaxResults pages (0 or absent means 60, outside 0-60 is refused); an unknown NextToken starts over."""
+ pid, cid = _auth_events_pool(cognito_idp, "AuthEventsPaging")
+ for _ in range(5):
+ cognito_idp.admin_initiate_auth(UserPoolId=pid, ClientId=cid, AuthFlow="ADMIN_USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "eve", "PASSWORD": "Correct1!"})
+ every = cognito_idp.admin_list_user_auth_events(UserPoolId=pid, Username="eve")
+ assert len(every["AuthEvents"]) == 5 and "NextToken" not in every
+ assert cognito_idp.admin_list_user_auth_events(
+ UserPoolId=pid, Username="eve", MaxResults=0)["AuthEvents"] == every["AuthEvents"]
+
+ pages, token = [], None
+ while True:
+ page = cognito_idp.admin_list_user_auth_events(
+ UserPoolId=pid, Username="eve", MaxResults=2, **({"NextToken": token} if token else {}))
+ pages.append([e["EventId"] for e in page["AuthEvents"]])
+ token = page.get("NextToken")
+ if not token:
+ break
+ assert token.startswith(page["AuthEvents"][-1]["EventId"] + "#") and token.endswith("Z")
+ assert pages == [[e["EventId"] for e in every["AuthEvents"][i:i + 2]] for i in (0, 2, 4)]
+ assert cognito_idp.admin_list_user_auth_events(
+ UserPoolId=pid, Username="eve", NextToken="not-a-token")["AuthEvents"] == every["AuthEvents"]
+
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.admin_list_user_auth_events(UserPoolId=pid, Username="eve", MaxResults=61)
+ assert exc.value.response["Error"]["Code"] == "InvalidParameterException"
+ assert exc.value.response["Error"]["Message"] == (
+ "1 validation error detected: Value '61' at 'maxResults' failed to satisfy constraint:"
+ " Member must have value less than or equal to 60")
+
+ def raw_list(max_results):
+ """Sent raw and signed: botocore refuses these values client-side."""
+ from botocore.auth import SigV4Auth
+ from botocore.awsrequest import AWSRequest
+ from botocore.credentials import Credentials
+
+ body = json.dumps({"UserPoolId": pid, "Username": "eve", "MaxResults": max_results})
+ signed = AWSRequest(method="POST", url=ENDPOINT, data=body, headers={
+ "Content-Type": "application/x-amz-json-1.1",
+ "X-Amz-Target": "AWSCognitoIdentityProviderService.AdminListUserAuthEvents"})
+ SigV4Auth(Credentials("test", "test"), "cognito-idp", "us-east-1").add_auth(signed)
+ request = urllib.request.Request(ENDPOINT, data=body.encode(), headers=dict(signed.headers), method="POST")
+ try:
+ with urllib.request.urlopen(request, timeout=10) as resp:
+ return resp.status, len(json.loads(resp.read())["AuthEvents"])
+ except urllib.error.HTTPError as err:
+ return err.code, json.loads(err.read())
+
+ assert raw_list(-1) == (400, {
+ "__type": "InvalidParameterException",
+ "message": "1 validation error detected: Value '-1' at 'maxResults' failed to satisfy constraint:"
+ " Member must have value greater than or equal to 0"})
+ assert raw_list(61.5)[1]["message"].startswith("1 validation error detected: Value '61' at")
+ assert raw_list(2.5) == (200, 2)
+ for value, message in (("5", "STRING_VALUE can not be converted to an Integer"),
+ (True, "TRUE_VALUE can not be converted to an Integer"),
+ ([], "Start of list found where not expected")):
+ status, error = raw_list(value)
+ assert (status, error["__type"], error["Message"]) == (
+ 400, "SerializationException", message)
+
+
+def test_cognito_auth_event_feedback(cognito_idp):
+ """AdminUpdateAuthEventFeedback sets EventFeedback; UpdateAuthEventFeedback has no valid token here."""
+ pid, cid = _auth_events_pool(cognito_idp, "AuthEventsFeedback")
+ cognito_idp.initiate_auth(ClientId=cid, AuthFlow="USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "eve", "PASSWORD": "Correct1!"})
+ event_id = cognito_idp.admin_list_user_auth_events(
+ UserPoolId=pid, Username="eve")["AuthEvents"][0]["EventId"]
+
+ for value in ("Valid", "Invalid"):
+ cognito_idp.admin_update_auth_event_feedback(
+ UserPoolId=pid, Username="eve", EventId=event_id, FeedbackValue=value)
+ feedback = cognito_idp.admin_list_user_auth_events(
+ UserPoolId=pid, Username="eve")["AuthEvents"][0]["EventFeedback"]
+ assert (feedback["FeedbackValue"], feedback["Provider"]) == (value, "Admin")
+ assert isinstance(feedback["FeedbackDate"], datetime.datetime)
+
+ def refused(call, **kwargs):
+ with pytest.raises(ClientError) as exc:
+ call(**{"UserPoolId": pid, "Username": "eve", "EventId": event_id, "FeedbackValue": "Valid",
+ **kwargs})
+ return exc.value.response["Error"]["Code"], exc.value.response["Error"]["Message"]
+
+ admin = cognito_idp.admin_update_auth_event_feedback
+ assert refused(admin, FeedbackValue="valid") == (
+ "InvalidParameterException",
+ "1 validation error detected: Value 'valid' at 'feedbackValue' failed to satisfy constraint:"
+ " Member must satisfy enum value set: [Invalid, Valid]")
+ assert refused(admin, EventId="not an id") == (
+ "InvalidParameterException",
+ "1 validation error detected: Value 'not an id' at 'eventId' failed to satisfy constraint:"
+ " Member must satisfy regular expression pattern: [\\w+-]+")
+ assert refused(admin, EventId=str(_uuid_mod.uuid4())) == ("InvalidParameterException", "EventId is invalid")
+ assert refused(admin, Username="nobody") == ("NotAuthorizedException", "Incorrect username or password.")
+ user = cognito_idp.update_auth_event_feedback
+ assert refused(user, FeedbackToken="made-up") == ("NotAuthorizedException", "Invalid session provided")
+
+ off = cognito_idp.create_user_pool(PoolName="AuthEventsFeedbackOff")["UserPool"]["Id"]
+ cognito_idp.admin_create_user(UserPoolId=off, Username="eve", MessageAction="SUPPRESS")
+ for call, extra in ((admin, {}), (user, {"FeedbackToken": "made-up"})):
+ assert refused(call, UserPoolId=off, **extra)[0] == "UserPoolAddOnNotEnabledException"
+
+
+def test_cognito_auth_events_survive_restore(_enable_persistence):
+ """Events live on the user record, so they survive a warm boot through load_persisted_state."""
+ mod = _cognito_module()
+ try:
+ mod.reset()
+ _, _, body = mod._create_user_pool({"PoolName": "AuthEventsRestore",
+ "UserPoolAddOns": {"AdvancedSecurityMode": "AUDIT"}})
+ pid = json.loads(body)["UserPool"]["Id"]
+ _, _, body = mod._create_user_pool_client({"UserPoolId": pid, "ClientName": "c",
+ "ExplicitAuthFlows": ["ALLOW_ADMIN_USER_PASSWORD_AUTH"]})
+ cid = json.loads(body)["UserPoolClient"]["ClientId"]
+ mod._admin_create_user({"UserPoolId": pid, "Username": "eve", "MessageAction": "SUPPRESS"})
+ mod._admin_set_user_password({"UserPoolId": pid, "Username": "eve", "Password": "Correct1!",
+ "Permanent": True})
+ mod._admin_initiate_auth({"UserPoolId": pid, "ClientId": cid, "AuthFlow": "ADMIN_USER_PASSWORD_AUTH",
+ "AuthParameters": {"USERNAME": "eve", "PASSWORD": "Correct1!"}})
+ listing = {"UserPoolId": pid, "Username": "eve"}
+ event_id = json.loads(mod._admin_list_user_auth_events(listing)[2])["AuthEvents"][0]["EventId"]
+ mod._admin_update_auth_event_feedback({**listing, "EventId": event_id, "FeedbackValue": "Valid"})
+ before = json.loads(mod._admin_list_user_auth_events(listing)[2])
+
+ _cognito_round_trip(mod)
+
+ assert json.loads(mod._admin_list_user_auth_events(listing)[2]) == before
+ assert before["AuthEvents"][0]["EventFeedback"]["FeedbackValue"] == "Valid"
+ finally:
+ mod.reset()
+
def test_cognito_domain_crud(cognito_idp):
pid = cognito_idp.create_user_pool(PoolName="DomainPool")["UserPool"]["Id"]
resp = cognito_idp.create_user_pool_domain(UserPoolId=pid, Domain="my-test-domain")