Skip to content

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

feat(cognito): invoke CustomMessage_AdminCreateUser Lambda trigger (#2034)

kjdevade5f7d18355
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index aceb5f60..24c542db 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -3067,6 +3067,17 @@ def _expand_template(template: str, username: str, code: str) -> str:
return template.replace("{username}", username or "").replace("{####}", code or "")
+def _template_username(pool: dict, username: str, attr_dict: dict) -> str:
+ """Value substituted for `{username}`. In a UsernameAttributes pool the
+ stored Username is an internal UUID, but the user-facing username is the
+ email / phone number they registered with."""
+ username_attrs = pool.get("UsernameAttributes") or []
+ for attr in ("email", "phone_number"):
+ if attr in username_attrs and (attr_dict or {}).get(attr):
+ return attr_dict[attr]
+ return username
+
+
def _resolve_invite_template(pool: dict) -> tuple:
"""Return (subject, message_text, message_html) for invitation mail."""
tpl = (pool.get("AdminCreateUserConfig") or {}).get("InviteMessageTemplate") or {}
@@ -3155,13 +3166,100 @@ def _wants_email_delivery(data: dict) -> bool:
return "EMAIL" in [str(m).upper() for m in mediums]
-def _send_invitation_email(pool, username, temp_password, attr_dict):
+class _CustomMessageRejected(Exception):
+ """Raised when a CustomMessage Lambda trigger fails or reports an error."""
+
+
+class _CustomMessageInvalid(Exception):
+ """Raised when a CustomMessage Lambda returns a message AWS would refuse."""
+
+
+def _custom_message_error(exc):
+ code = ("InvalidLambdaResponseException" if isinstance(exc, _CustomMessageInvalid)
+ else "UserLambdaValidationException")
+ return error_response_json(code, str(exc), 400)
+
+
+def _apply_custom_message_trigger(pool: dict, trigger_source: str, username: str,
+ user_attrs: dict, client_metadata=None,
+ username_parameter: str = "{username}") -> dict:
+ """Invoke the pool's CustomMessage Lambda and return its ``response`` block.
+
+ Fail-closed like AWS, where a CustomMessage Lambda that throws fails the
+ calling API with ``UserLambdaValidationException``. Returns ``{}`` when the
+ pool has no ``LambdaConfig.CustomMessage``.
+ """
+ arn = (pool.get("LambdaConfig") or {}).get("CustomMessage")
+ if not arn:
+ return {}
+ pool_id = pool.get("Id", "")
+ event = {
+ "version": "1",
+ "triggerSource": trigger_source,
+ "region": _pool_region(pool_id),
+ "userPoolId": pool_id,
+ "userName": username or "",
+ "callerContext": {
+ "awsSdkVersion": "ministack",
+ "clientId": "CLIENT_ID_NOT_APPLICABLE",
+ },
+ "request": {
+ "userAttributes": {k: v for k, v in (user_attrs or {}).items()
+ if isinstance(v, (str, int, float, bool))},
+ "codeParameter": "{####}",
+ "usernameParameter": username_parameter,
+ "clientMetadata": dict(client_metadata or {}),
+ },
+ "response": {"smsMessage": None, "emailMessage": None, "emailSubject": None},
+ }
+ try:
+ # Lazy import to avoid a circular dependency between cognito and lambda_svc.
+ from ministack.services import lambda_svc
+ record, config, _name = lambda_svc._get_func_record_for_ref(arn)
+ if record is None or config is None:
+ raise RuntimeError(f"CustomMessage Lambda not found: {arn}")
+ exec_record = lambda_svc._execution_record_for_config(record, config)
+ result = lambda_svc._execute_function_with_config_scope(exec_record, event)
+ except Exception as e:
+ logger.warning("CustomMessage Lambda invocation failed for pool %s: %s", pool_id, e)
+ raise _CustomMessageRejected(str(e)) from e
+
+ if isinstance(result, dict) and result.get("error"):
+ raise _CustomMessageRejected(
+ str(result.get("body") or "CustomMessage Lambda rejected the request."))
+ payload = result.get("body") if isinstance(result, dict) else result
+ return _extract_trigger_response(payload) or {}
+
+
+def _render_invitation_message(pool, username, temp_password, attr_dict,
+ client_metadata=None) -> tuple:
+ """Return the (subject, body) of an invitation email.
+
+ A CustomMessage Lambda's ``emailSubject`` / ``emailMessage`` replace the
+ pool's InviteMessageTemplate; either one left out falls back to the template.
+ Raises ``_CustomMessageRejected`` when the Lambda fails, and
+ ``_CustomMessageInvalid`` when its ``emailMessage`` lacks the ``{username}``
+ or ``{####}`` placeholder that AWS requires for AdminCreateUser messages.
+ """
+ subject_tpl, body_tpl, _ = _resolve_invite_template(pool)
+ custom = _apply_custom_message_trigger(
+ pool, "CustomMessage_AdminCreateUser", username, attr_dict, client_metadata,
+ )
+ custom_body = custom.get("emailMessage")
+ if custom_body and not ("{####}" in custom_body and "{username}" in custom_body):
+ raise _CustomMessageInvalid(
+ "CustomMessage emailMessage must contain both {username} and {####}.")
+ subject_tpl = custom.get("emailSubject") or subject_tpl
+ body_tpl = custom_body or body_tpl
+ display = _template_username(pool, username, attr_dict)
+ return (_expand_template(subject_tpl, display, temp_password),
+ _expand_template(body_tpl, display, temp_password))
+
+
+def _deliver_invitation_email(pool, username, attr_dict, subject, body):
email = (attr_dict or {}).get("email")
if not email:
return None
- subject_tpl, body_tpl, _ = _resolve_invite_template(pool)
- subject = _expand_template(subject_tpl, username, temp_password)
- body = _expand_template(body_tpl, username, temp_password)
return _deliver_cognito_email(
pool, email, subject, body,
type_name="CognitoInvitationMessage",
@@ -3179,8 +3277,9 @@ def _send_verification_email(pool, username, attr_dict, code, attribute_name="em
"DefaultEmailOption"
) == "CONFIRM_WITH_LINK"
subject_tpl, body_tpl = _resolve_verification_template(pool, by_link=by_link)
- subject = _expand_template(subject_tpl, username, code)
- body = _expand_template(body_tpl, username, code)
+ display = _template_username(pool, username, attr_dict)
+ subject = _expand_template(subject_tpl, display, code)
+ body = _expand_template(body_tpl, display, code)
return _deliver_cognito_email(
pool, email, subject, body,
type_name="CognitoVerificationMessage",
@@ -3188,13 +3287,17 @@ def _send_verification_email(pool, username, attr_dict, code, attribute_name="em
)
-def _send_email_otp(pool, username, email, code):
+def _send_email_otp(pool, username, attr_dict, code):
"""Send the EMAIL_OTP first-factor sign-in code. AWS has no template
configuration API for this message, so it always uses the built-in text."""
return _deliver_cognito_email(
- pool, email,
+ pool, attr_dict["email"],
_DEFAULT_EMAIL_OTP_SUBJECT,
- _expand_template(_DEFAULT_EMAIL_OTP_MESSAGE, username, code),
+ _expand_template(
+ _DEFAULT_EMAIL_OTP_MESSAGE,
+ _template_username(pool, username, attr_dict),
+ code,
+ ),
type_name="CognitoEmailOtpMessage",
extra={"Username": username},
)
@@ -3242,12 +3345,17 @@ def _admin_create_user(data):
return error_response_json(
"UserNotFoundException", "User does not exist.", 400,
)
- existing["UserLastModifiedDate"] = _now_epoch()
attr_dict = _attr_list_to_dict(existing.get("Attributes", []))
- if _wants_email_delivery(data):
- _send_invitation_email(
- pool, existing["Username"], existing.get("_password", ""), attr_dict,
- )
+ if _wants_email_delivery(data) and attr_dict.get("email"):
+ try:
+ subject, body = _render_invitation_message(
+ pool, existing["Username"], existing.get("_password", ""),
+ attr_dict, data.get("ClientMetadata"),
+ )
+ except (_CustomMessageRejected, _CustomMessageInvalid) as e:
+ return _custom_message_error(e)
+ _deliver_invitation_email(pool, existing["Username"], attr_dict, subject, body)
+ existing["UserLastModifiedDate"] = _now_epoch()
return json_response({"User": _user_out(existing)})
if existing:
@@ -3273,6 +3381,17 @@ def _admin_create_user(data):
real_username = username
attrs = _dict_to_attr_list(attr_dict)
+ # Rendered before the user is persisted: a failing CustomMessage Lambda
+ # fails the call without leaving the user behind, as on AWS.
+ invitation = None
+ if message_action != "SUPPRESS" and _wants_email_delivery(data) and attr_dict.get("email"):
+ try:
+ invitation = _render_invitation_message(
+ pool, real_username, temp_password, attr_dict, data.get("ClientMetadata"),
+ )
+ except (_CustomMessageRejected, _CustomMessageInvalid) as e:
+ return _custom_message_error(e)
+
user = {
"Username": real_username,
"Attributes": attrs,
@@ -3289,8 +3408,8 @@ def _admin_create_user(data):
pool["EstimatedNumberOfUsers"] = len(pool["_users"])
logger.info("Cognito: AdminCreateUser %s in pool %s", real_username, pid)
- if message_action != "SUPPRESS" and _wants_email_delivery(data):
- _send_invitation_email(pool, real_username, temp_password, attr_dict)
+ if invitation:
+ _deliver_invitation_email(pool, real_username, attr_dict, *invitation)
return json_response({"User": _user_out(user)})
@@ -6297,10 +6416,10 @@ def _begin_user_auth_challenge(pool, ua_token, session, challenge):
session["challenge"] = challenge
if challenge == "EMAIL_OTP":
user, _err = _resolve_user(pool, session["username"])
- email = _attr_list_to_dict(user.get("Attributes", [])).get("email") if user else ""
- if user and email:
+ attr_dict = _attr_list_to_dict(user.get("Attributes", [])) if user else {}
+ if user and attr_dict.get("email"):
session["otp_code"] = _EMAIL_OTP_CODE
- _send_email_otp(pool, session["username"], email, _EMAIL_OTP_CODE)
+ _send_email_otp(pool, session["username"], attr_dict, _EMAIL_OTP_CODE)
return _email_otp_page_html(ua_token)
return _password_page_html(ua_token, session["username"])
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index 4e19763b..fec8fda1 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -5362,6 +5362,266 @@ def test_cognito_admin_create_user_sends_invitation_email(cognito_idp):
assert msg["Source"] == "[email protected]"
+def _custom_message_pool(cognito_idp, lam, handler_code, **pool_kwargs):
+ fname = f"custommsg-{_uuid_mod.uuid4().hex[:8]}"
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", handler_code)
+ lam.create_function(
+ FunctionName=fname, Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler", Code={"ZipFile": buf.getvalue()},
+ )
+ fn_arn = f"arn:aws:lambda:us-east-1:000000000000:function:{fname}"
+ pid = cognito_idp.create_user_pool(
+ PoolName=f"pool-{fname}", LambdaConfig={"CustomMessage": fn_arn},
+ **pool_kwargs,
+ )["UserPool"]["Id"]
+ return pid, fname
+
+
+_CUSTOM_MESSAGE_HANDLER = (
+ "def handler(event, context):\n"
+ " assert event['triggerSource'] == 'CustomMessage_AdminCreateUser'\n"
+ " kind = event['request']['clientMetadata'].get('notification_type', 'none')\n"
+ " if kind == 'boom':\n"
+ " raise Exception('custom message failed')\n"
+ " p = event['request']\n"
+ " event['response']['emailSubject'] = 'Hello ' + kind\n"
+ " event['response']['emailMessage'] = (\n"
+ " kind + ' ' + p['usernameParameter'] + ' ' + p['codeParameter'])\n"
+ " return event\n"
+)
+
+
+def test_cognito_custom_message_replaces_invitation_email(cognito_idp, lam):
+ """CustomMessage_AdminCreateUser: the Lambda's emailSubject/emailMessage
+ replace the template, placeholders are expanded, ClientMetadata reaches
+ the event, and RESEND invokes it too."""
+ pid, fname = _custom_message_pool(cognito_idp, lam, _CUSTOM_MESSAGE_HANDLER)
+ try:
+ email = f"cm-{_uuid_mod.uuid4().hex[:8]}@example.com"
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="invitee",
+ UserAttributes=[{"Name": "email", "Value": email}],
+ TemporaryPassword="TempPw1!aa",
+ ClientMetadata={"notification_type": "invite"},
+ )
+ msgs = _messages_to(email, "CognitoInvitationMessage")
+ assert len(msgs) == 1
+ assert msgs[0]["Subject"] == "Hello invite"
+ assert (msgs[0]["BodyText"] or msgs[0]["BodyHtml"]) == "invite invitee TempPw1!aa"
+
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="invitee", MessageAction="RESEND",
+ ClientMetadata={"notification_type": "resend"},
+ )
+ msgs = _messages_to(email, "CognitoInvitationMessage")
+ assert [m["Subject"] for m in msgs] == ["Hello invite", "Hello resend"]
+ finally:
+ cognito_idp.delete_user_pool(UserPoolId=pid)
+ lam.delete_function(FunctionName=fname)
+
+
+def test_cognito_custom_message_username_is_email_in_username_attributes_pool(cognito_idp, lam):
+ """The {username} left in the Lambda's emailMessage expands to the email,
+ while the event's userName stays the internal Username."""
+ handler = (
+ "def handler(event, context):\n"
+ " p = event['request']\n"
+ " event['response']['emailSubject'] = 'Hello'\n"
+ " event['response']['emailMessage'] = (\n"
+ " 'name=' + p['usernameParameter'] + ' ' + p['codeParameter']\n"
+ " + ' event=' + event['userName'])\n"
+ " return event\n"
+ )
+ pid, fname = _custom_message_pool(
+ cognito_idp, lam, handler, UsernameAttributes=["email"],
+ )
+ try:
+ email = f"cmun-{_uuid_mod.uuid4().hex[:8]}@example.com"
+ user = cognito_idp.admin_create_user(
+ UserPoolId=pid, Username=email, TemporaryPassword="TempPw1!aa",
+ )["User"]
+ assert user["Username"] != email
+ msgs = _messages_to(email, "CognitoInvitationMessage")
+ assert len(msgs) == 1
+ body = msgs[0]["BodyText"] or msgs[0]["BodyHtml"]
+ assert body == f"name={email} TempPw1!aa event={user['Username']}"
+ finally:
+ cognito_idp.delete_user_pool(UserPoolId=pid)
+ lam.delete_function(FunctionName=fname)
+
+
+def test_cognito_custom_message_failure_fails_admin_create_user(cognito_idp, lam):
+ """A throwing CustomMessage Lambda fails AdminCreateUser with
+ UserLambdaValidationException and leaves no user behind."""
+ pid, fname = _custom_message_pool(cognito_idp, lam, _CUSTOM_MESSAGE_HANDLER)
+ try:
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="invitee",
+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],
+ ClientMetadata={"notification_type": "boom"},
+ )
+ assert exc.value.response["Error"]["Code"] == "UserLambdaValidationException"
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.admin_get_user(UserPoolId=pid, Username="invitee")
+ assert exc.value.response["Error"]["Code"] == "UserNotFoundException"
+ finally:
+ cognito_idp.delete_user_pool(UserPoolId=pid)
+ lam.delete_function(FunctionName=fname)
+
+
+def test_cognito_custom_message_without_required_placeholders_is_rejected(cognito_idp, lam):
+ """An emailMessage missing {username} or {####} fails AdminCreateUser with
+ InvalidLambdaResponseException and leaves no user behind."""
+ handler = (
+ "def handler(event, context):\n"
+ " event['response']['emailSubject'] = 'Hello'\n"
+ " event['response']['emailMessage'] = 'no placeholders'\n"
+ " return event\n"
+ )
+ pid, fname = _custom_message_pool(cognito_idp, lam, handler)
+ try:
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="invitee",
+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],
+ )
+ assert exc.value.response["Error"]["Code"] == "InvalidLambdaResponseException"
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.admin_get_user(UserPoolId=pid, Username="invitee")
+ assert exc.value.response["Error"]["Code"] == "UserNotFoundException"
+ finally:
+ cognito_idp.delete_user_pool(UserPoolId=pid)
+ lam.delete_function(FunctionName=fname)
+
+
+def test_cognito_custom_message_resend_failure_keeps_last_modified_date(cognito_idp, lam):
+ """A RESEND that the Lambda rejects must not touch UserLastModifiedDate."""
+ pid, fname = _custom_message_pool(cognito_idp, lam, _CUSTOM_MESSAGE_HANDLER)
+ try:
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="invitee",
+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],
+ ClientMetadata={"notification_type": "invite"},
+ )
+ before = cognito_idp.admin_get_user(
+ UserPoolId=pid, Username="invitee")["UserLastModifiedDate"]
+ time.sleep(1.1)
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="invitee", MessageAction="RESEND",
+ ClientMetadata={"notification_type": "boom"},
+ )
+ assert exc.value.response["Error"]["Code"] == "UserLambdaValidationException"
+ after = cognito_idp.admin_get_user(
+ UserPoolId=pid, Username="invitee")["UserLastModifiedDate"]
+ assert after == before
+ finally:
+ cognito_idp.delete_user_pool(UserPoolId=pid)
+ lam.delete_function(FunctionName=fname)
+
+
+def test_cognito_custom_message_suppress_does_not_invoke_lambda(cognito_idp, lam):
+ """MessageAction=SUPPRESS skips the Lambda: the handler would raise for
+ 'boom', so a successful call proves it was not invoked."""
+ pid, fname = _custom_message_pool(cognito_idp, lam, _CUSTOM_MESSAGE_HANDLER)
+ try:
+ email = f"cmsup-{_uuid_mod.uuid4().hex[:8]}@example.com"
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="invitee",
+ UserAttributes=[{"Name": "email", "Value": email}],
+ TemporaryPassword="TempPw1!aa",
+ MessageAction="SUPPRESS",
+ ClientMetadata={"notification_type": "boom"},
+ )
+ assert _messages_to(email) == []
+ finally:
+ cognito_idp.delete_user_pool(UserPoolId=pid)
+ lam.delete_function(FunctionName=fname)
+
+
+def test_cognito_custom_message_partial_response_falls_back_to_template(cognito_idp, lam):
+ """A Lambda returning only emailSubject keeps the pool template body."""
+ handler = (
+ "def handler(event, context):\n"
+ " event['response']['emailSubject'] = 'Only subject'\n"
+ " return event\n"
+ )
+ pid, fname = _custom_message_pool(cognito_idp, lam, handler)
+ try:
+ email = f"cmpart-{_uuid_mod.uuid4().hex[:8]}@example.com"
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="invitee",
+ UserAttributes=[{"Name": "email", "Value": email}],
+ TemporaryPassword="TempPw1!aa",
+ )
+ msgs = _messages_to(email, "CognitoInvitationMessage")
+ assert len(msgs) == 1
+ assert msgs[0]["Subject"] == "Only subject"
+ body = msgs[0]["BodyText"] or msgs[0]["BodyHtml"]
+ assert "invitee" in body and "TempPw1!aa" in body
+ finally:
+ cognito_idp.delete_user_pool(UserPoolId=pid)
+ lam.delete_function(FunctionName=fname)
+
+
+def test_cognito_without_custom_message_uses_default_invitation(cognito_idp):
+ pid = cognito_idp.create_user_pool(PoolName="NoCustomMsgPool")["UserPool"]["Id"]
+ try:
+ email = f"nocm-{_uuid_mod.uuid4().hex[:8]}@example.com"
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="invitee",
+ UserAttributes=[{"Name": "email", "Value": email}],
+ TemporaryPassword="TempPw1!aa",
+ )
+ msgs = _messages_to(email, "CognitoInvitationMessage")
+ assert len(msgs) == 1
+ assert "invitee" in (msgs[0]["BodyText"] or msgs[0]["BodyHtml"])
+ finally:
+ cognito_idp.delete_user_pool(UserPoolId=pid)
+
+
+def test_cognito_invitation_username_is_email_in_username_attributes_pool(cognito_idp):
+ pid = cognito_idp.create_user_pool(
+ PoolName="InviteEmailUsernamePool",
+ UsernameAttributes=["email"],
+ AdminCreateUserConfig={
+ "InviteMessageTemplate": {
+ "EmailSubject": "Welcome",
+ "EmailMessage": "Your username is {username}, password {####}.",
+ },
+ },
+ )["UserPool"]["Id"]
+
+ email = f"uname-{_uuid_mod.uuid4().hex[:8]}@example.com"
+ user = cognito_idp.admin_create_user(
+ UserPoolId=pid,
+ Username=email,
+ TemporaryPassword="TempPw1!aa",
+ DesiredDeliveryMediums=["EMAIL"],
+ )["User"]
+ assert user["Username"] != email
+
+ msgs = _messages_to(email, "CognitoInvitationMessage")
+ assert len(msgs) == 1
+ body = msgs[0]["BodyText"] or msgs[0]["BodyHtml"]
+ assert f"Your username is {email}," in body
+ assert user["Username"] not in body
+
+ cognito_idp.admin_create_user(
+ UserPoolId=pid,
+ Username=email,
+ MessageAction="RESEND",
+ DesiredDeliveryMediums=["EMAIL"],
+ )
+ resent = _messages_to(email, "CognitoInvitationMessage")
+ assert len(resent) == 2
+ assert f"Your username is {email}," in (resent[1]["BodyText"] or resent[1]["BodyHtml"])
+
+
def test_cognito_admin_create_user_suppress_skips_email(cognito_idp):
pid = cognito_idp.create_user_pool(PoolName="SuppressPool")["UserPool"]["Id"]