Files
floci/compatibility-tests/sdk-test-python/tests/test_cognito.py
T
Brian Taylor b8f1e22c74 feat(cognito): implement log delivery configuration (#2867)
* feat(cognito): implement log delivery configuration

SetLogDeliveryConfiguration and GetLogDeliveryConfiguration were unsupported, so a
config declaring `aws_cognito_log_delivery_configuration` could not be applied
against Floci.

The configuration is stored on the user pool and validated the way the live API
validates it:

- LogLevel accepts ERROR or INFO, EventSource accepts userNotification or
  userAuthEvents, both reported with AWS's 1-based member path
- every entry must name a CloudWatch, Firehose or S3 destination
- Set replaces the list rather than merging, so an empty list clears it
- Get always returns LogConfigurations, as [] when nothing is configured

Floci stores the configuration and delivers nothing: the destination is neither
written to nor required to exist, and the pricing-tier gate AWS applies to
userAuthEvents is not reproduced.

Closes #2855

* fix(cognito): reject a null LogConfigurations instead of clearing the configuration

SetLogDeliveryConfiguration treated an omitted, null or wrongly typed
LogConfigurations as an empty replacement, so a malformed request returned 200
and erased the pool's stored configuration.

AWS rejects all three. An omitted or null member fails validation, and a value of
the wrong JSON type fails deserialization:

  omitted / null -> InvalidParameterException: 1 validation error detected: Value
                    null at 'logConfigurations' failed to satisfy constraint:
                    Member must not be null
  wrong type     -> SerializationException: Expected list or null

Also drops two em-dashes from the docs, per AGENTS.md.

* fix(cognito): translate malformed LogConfigurations elements the way AWS does

A scalar inside the array reached Jackson's convertValue directly, so an
IllegalArgumentException escaped as a 500 InternalFailure instead of a client
error, and a null element would have failed on the validation loop.

AWS answers both without a 500:

  [1, 2] / ["a string"] -> SerializationException: Expected null
  [null]                -> 200, the null element is dropped

Elements are now checked before conversion: nulls are skipped and non-objects
raise SerializationException.

* fix(cognito): bound LogConfigurations and reject a repeated event source

SetLogDeliveryConfiguration validated each element but never checked the list
itself, so a request with three or more well-formed configurations, or two
naming the same event source, was accepted and stored where AWS rejects it.

Measured against Cognito in ap-southeast-1:

  3 well-formed configs   InvalidParameterException, length constraint on
                          'logConfigurations', max 2
  2 duplicate sources     InvalidParameterException, "appear more then once"
  3 configs, one bad enum 2 validation errors, the length one reported first
  unknown pool, bad enum  the validation error, not ResourceNotFoundException
  0 configs               200 OK

The shape checks now run before the pool lookup, matching that last row, and
collect every violation into one message instead of throwing on the first.
The duplicate and missing-destination complaints share one message with the
missing-destination clause first, and each event source is named once however
many configurations carry it, as measured.

"more then once" is the service's own spelling, kept so the message matches.

The length message embeds the request model's toString, which the emulator now
reproduces for all three destination shapes and for an absent destination.
2026-09-02 11:44:18 -04:00

363 lines
14 KiB
Python

"""Cognito Identity Provider integration tests."""
import pytest
class TestCognitoUserPool:
"""Test Cognito user pool operations."""
def test_create_user_pool(self, cognito_client, unique_name):
"""Test CreateUserPool creates a pool."""
pool_name = f"pytest-pool-{unique_name}"
try:
response = cognito_client.create_user_pool(PoolName=pool_name)
pool_id = response["UserPool"]["Id"]
assert pool_id
finally:
cognito_client.delete_user_pool(UserPoolId=response["UserPool"]["Id"])
def test_delete_user_pool(self, cognito_client, unique_name):
"""Test DeleteUserPool removes pool."""
pool_name = f"pytest-pool-{unique_name}"
response = cognito_client.create_user_pool(PoolName=pool_name)
pool_id = response["UserPool"]["Id"]
cognito_client.delete_user_pool(UserPoolId=pool_id)
# If no exception, test passes
class TestCognitoUserPoolClient:
"""Test Cognito user pool client operations."""
def test_create_user_pool_client(self, cognito_client, unique_name):
"""Test CreateUserPoolClient creates a client."""
pool_name = f"pytest-pool-{unique_name}"
client_name = f"pytest-client-{unique_name}"
response = cognito_client.create_user_pool(PoolName=pool_name)
pool_id = response["UserPool"]["Id"]
try:
response = cognito_client.create_user_pool_client(
UserPoolId=pool_id, ClientName=client_name
)
client_id = response["UserPoolClient"]["ClientId"]
assert client_id
finally:
cognito_client.delete_user_pool(UserPoolId=pool_id)
def test_delete_user_pool_client(self, cognito_client, unique_name):
"""Test DeleteUserPoolClient removes client."""
pool_name = f"pytest-pool-{unique_name}"
client_name = f"pytest-client-{unique_name}"
pool_response = cognito_client.create_user_pool(PoolName=pool_name)
pool_id = pool_response["UserPool"]["Id"]
client_response = cognito_client.create_user_pool_client(
UserPoolId=pool_id, ClientName=client_name
)
client_id = client_response["UserPoolClient"]["ClientId"]
try:
cognito_client.delete_user_pool_client(
UserPoolId=pool_id, ClientId=client_id
)
# If no exception, test passes
finally:
cognito_client.delete_user_pool(UserPoolId=pool_id)
class TestCognitoUser:
"""Test Cognito user operations."""
def test_admin_create_user(self, cognito_client, unique_name):
"""Test AdminCreateUser creates a user."""
pool_name = f"pytest-pool-{unique_name}"
username = f"pytest-user-{unique_name}"
pool_response = cognito_client.create_user_pool(PoolName=pool_name)
pool_id = pool_response["UserPool"]["Id"]
try:
response = cognito_client.admin_create_user(
UserPoolId=pool_id,
Username=username,
UserAttributes=[{"Name": "email", "Value": "pytest@example.com"}],
)
assert response["User"]["Username"] == username
finally:
cognito_client.admin_delete_user(UserPoolId=pool_id, Username=username)
cognito_client.delete_user_pool(UserPoolId=pool_id)
def test_admin_delete_user(self, cognito_client, unique_name):
"""Test AdminDeleteUser removes user."""
pool_name = f"pytest-pool-{unique_name}"
username = f"pytest-user-{unique_name}"
pool_response = cognito_client.create_user_pool(PoolName=pool_name)
pool_id = pool_response["UserPool"]["Id"]
cognito_client.admin_create_user(
UserPoolId=pool_id,
Username=username,
UserAttributes=[{"Name": "email", "Value": "pytest@example.com"}],
)
try:
cognito_client.admin_delete_user(UserPoolId=pool_id, Username=username)
# If no exception, test passes
finally:
cognito_client.delete_user_pool(UserPoolId=pool_id)
class TestCognitoAuth:
"""Test Cognito authentication operations."""
def test_admin_initiate_auth(self, cognito_client, unique_name):
"""Test AdminInitiateAuth returns tokens."""
pool_name = f"pytest-pool-{unique_name}"
client_name = f"pytest-client-{unique_name}"
username = f"pytest-user-{unique_name}"
pool_response = cognito_client.create_user_pool(PoolName=pool_name)
pool_id = pool_response["UserPool"]["Id"]
client_response = cognito_client.create_user_pool_client(
UserPoolId=pool_id, ClientName=client_name
)
client_id = client_response["UserPoolClient"]["ClientId"]
cognito_client.admin_create_user(
UserPoolId=pool_id,
Username=username,
UserAttributes=[{"Name": "email", "Value": "pytest@example.com"}],
)
try:
response = cognito_client.admin_initiate_auth(
UserPoolId=pool_id,
ClientId=client_id,
AuthFlow="ADMIN_NO_SRP_AUTH",
AuthParameters={"USERNAME": username, "PASSWORD": "any"},
)
access_token = response["AuthenticationResult"]["AccessToken"]
assert access_token
finally:
cognito_client.admin_delete_user(UserPoolId=pool_id, Username=username)
cognito_client.delete_user_pool_client(
UserPoolId=pool_id, ClientId=client_id
)
cognito_client.delete_user_pool(UserPoolId=pool_id)
def test_get_user(self, cognito_client, unique_name):
"""Test GetUser returns user details from access token."""
pool_name = f"pytest-pool-{unique_name}"
client_name = f"pytest-client-{unique_name}"
username = f"pytest-user-{unique_name}"
pool_response = cognito_client.create_user_pool(PoolName=pool_name)
pool_id = pool_response["UserPool"]["Id"]
client_response = cognito_client.create_user_pool_client(
UserPoolId=pool_id, ClientName=client_name
)
client_id = client_response["UserPoolClient"]["ClientId"]
cognito_client.admin_create_user(
UserPoolId=pool_id,
Username=username,
UserAttributes=[{"Name": "email", "Value": "pytest@example.com"}],
)
auth_response = cognito_client.admin_initiate_auth(
UserPoolId=pool_id,
ClientId=client_id,
AuthFlow="ADMIN_NO_SRP_AUTH",
AuthParameters={"USERNAME": username, "PASSWORD": "any"},
)
access_token = auth_response["AuthenticationResult"]["AccessToken"]
try:
response = cognito_client.get_user(AccessToken=access_token)
assert response["Username"] == username
finally:
cognito_client.admin_delete_user(UserPoolId=pool_id, Username=username)
cognito_client.delete_user_pool_client(
UserPoolId=pool_id, ClientId=client_id
)
cognito_client.delete_user_pool(UserPoolId=pool_id)
class TestCognitoLogDeliveryConfiguration:
"""Test Cognito log delivery configuration operations.
``LogConfigurations`` is always present on the response, as ``[]`` when nothing
is configured, and ``SetLogDeliveryConfiguration`` replaces the list rather than
merging into it.
"""
LOG_GROUP_ARN = "arn:aws:logs:us-east-1:000000000000:log-group:pytest-cognito-logs"
@pytest.fixture
def pool_id(self, cognito_client, unique_name):
response = cognito_client.create_user_pool(PoolName=f"pytest-log-pool-{unique_name}")
pool_id = response["UserPool"]["Id"]
yield pool_id
cognito_client.delete_user_pool(UserPoolId=pool_id)
def test_get_returns_an_empty_list_before_anything_is_configured(
self, cognito_client, pool_id
):
"""An unconfigured pool still returns the LogConfigurations member."""
config = cognito_client.get_log_delivery_configuration(UserPoolId=pool_id)[
"LogDeliveryConfiguration"
]
assert config["UserPoolId"] == pool_id
assert config["LogConfigurations"] == []
def test_set_round_trips_and_replaces(self, cognito_client, pool_id):
"""Set stores the configuration, and a second Set replaces rather than merges."""
cognito_client.set_log_delivery_configuration(
UserPoolId=pool_id,
LogConfigurations=[
{
"LogLevel": "ERROR",
"EventSource": "userNotification",
"CloudWatchLogsConfiguration": {"LogGroupArn": self.LOG_GROUP_ARN},
}
],
)
config = cognito_client.get_log_delivery_configuration(UserPoolId=pool_id)[
"LogDeliveryConfiguration"
]
assert len(config["LogConfigurations"]) == 1
assert config["LogConfigurations"][0]["EventSource"] == "userNotification"
assert (
config["LogConfigurations"][0]["CloudWatchLogsConfiguration"]["LogGroupArn"]
== self.LOG_GROUP_ARN
)
cognito_client.set_log_delivery_configuration(
UserPoolId=pool_id,
LogConfigurations=[
{
"LogLevel": "INFO",
"EventSource": "userAuthEvents",
"CloudWatchLogsConfiguration": {"LogGroupArn": self.LOG_GROUP_ARN},
}
],
)
replaced = cognito_client.get_log_delivery_configuration(UserPoolId=pool_id)[
"LogDeliveryConfiguration"
]
assert len(replaced["LogConfigurations"]) == 1
assert replaced["LogConfigurations"][0]["EventSource"] == "userAuthEvents"
def test_empty_list_clears_the_configuration(self, cognito_client, pool_id):
"""An empty LogConfigurations clears what was stored."""
cognito_client.set_log_delivery_configuration(
UserPoolId=pool_id,
LogConfigurations=[
{
"LogLevel": "ERROR",
"EventSource": "userNotification",
"CloudWatchLogsConfiguration": {"LogGroupArn": self.LOG_GROUP_ARN},
}
],
)
cognito_client.set_log_delivery_configuration(UserPoolId=pool_id, LogConfigurations=[])
config = cognito_client.get_log_delivery_configuration(UserPoolId=pool_id)[
"LogDeliveryConfiguration"
]
assert config["LogConfigurations"] == []
def test_set_rejects_a_configuration_with_no_destination(self, cognito_client, pool_id):
"""Every event source in the request must name a destination."""
with pytest.raises(cognito_client.exceptions.InvalidParameterException):
cognito_client.set_log_delivery_configuration(
UserPoolId=pool_id,
LogConfigurations=[{"LogLevel": "ERROR", "EventSource": "userNotification"}],
)
def test_set_rejects_more_than_two_configurations(self, cognito_client, pool_id):
"""LogConfigurations is bounded at 2 entries."""
config = {
"LogLevel": "ERROR",
"EventSource": "userNotification",
"CloudWatchLogsConfiguration": {"LogGroupArn": self.LOG_GROUP_ARN},
}
with pytest.raises(cognito_client.exceptions.InvalidParameterException) as excinfo:
cognito_client.set_log_delivery_configuration(
UserPoolId=pool_id, LogConfigurations=[config, config, config]
)
assert "Member must have length less than or equal to 2" in str(excinfo.value)
def test_set_rejects_a_repeated_event_source(self, cognito_client, pool_id):
"""An event source may appear at most once across the configurations."""
config = {
"LogLevel": "ERROR",
"EventSource": "userNotification",
"CloudWatchLogsConfiguration": {"LogGroupArn": self.LOG_GROUP_ARN},
}
with pytest.raises(cognito_client.exceptions.InvalidParameterException) as excinfo:
cognito_client.set_log_delivery_configuration(
UserPoolId=pool_id, LogConfigurations=[config, config]
)
assert "appear more then once in a request" in str(excinfo.value)
def test_a_rejected_request_leaves_the_configuration_alone(self, cognito_client, pool_id):
"""An oversized request must not be stored."""
config = {
"LogLevel": "ERROR",
"EventSource": "userNotification",
"CloudWatchLogsConfiguration": {"LogGroupArn": self.LOG_GROUP_ARN},
}
with pytest.raises(cognito_client.exceptions.InvalidParameterException):
cognito_client.set_log_delivery_configuration(
UserPoolId=pool_id, LogConfigurations=[config, config, config]
)
stored = cognito_client.get_log_delivery_configuration(UserPoolId=pool_id)[
"LogDeliveryConfiguration"
]
assert stored["LogConfigurations"] == []
class TestCognitoDescribeUserPoolStandardAttributes:
"""DescribeUserPool must return all 20 standard OIDC attributes."""
STANDARD_ATTRIBUTES = [
"sub", "name", "given_name", "family_name", "middle_name", "nickname",
"preferred_username", "profile", "picture", "website", "email",
"email_verified", "gender", "birthdate", "zoneinfo", "locale",
"phone_number", "phone_number_verified", "address", "updated_at",
]
def test_describe_user_pool_returns_all_standard_schema_attributes(self, cognito_client, unique_name):
response = cognito_client.create_user_pool(PoolName=f"pytest-schema-{unique_name}")
pool_id = response["UserPool"]["Id"]
try:
described = cognito_client.describe_user_pool(UserPoolId=pool_id)
schema = described["UserPool"]["SchemaAttributes"]
names = [a["Name"] for a in schema]
assert len(schema) == 20
for attr in self.STANDARD_ATTRIBUTES:
assert attr in names, f"Missing standard attribute: {attr}"
sub = next(a for a in schema if a["Name"] == "sub")
assert sub["Required"] is True
assert sub["Mutable"] is False
finally:
cognito_client.delete_user_pool(UserPoolId=pool_id)