feat(cognito): hand email codes to the CustomEmailSender trigger (#6031)

* feat(cognito): hand email codes to the CustomEmailSender trigger

* test(cognito): decrypt CustomEmailSender codes with the AWS Encryption SDK

* docs(cognito): document the CustomEmailSender trigger

* fix(cognito): fail a CustomEmailSender delivery as Cognito does

Measured on Cognito (eu-west-1, 2026-10-16), with the events a real sender
received:
- CreateUserPool and UpdateUserPool refuse a custom sender trigger without
  a KMSKeyID ("KMSKeyId parameter is required when Custom SMS/Email Lambda
  trigger is used."), and CreateUserPool a key that does not exist
  ("Encountered error when CreateGrant was attempted on the input KMS key -
  Key '<id>' does not exist"), both InvalidParameterException.
- A disabled key fails the request with CodeDeliveryFailureException
  "Caller needs to enable the configured KMS Key", a key pending deletion
  with "Unable to encrypt CustomEmailSender/CustomSMSSender code using the
  configured KMS Key". The sign-up is kept, unlike a failed SES delivery,
  and InitiateAuth answers the same error rather than InternalErrorException.
- A function that is gone, or that Cognito may not invoke, answers
  UnexpectedLambdaException "CustomEmailSender invocation failed due to
  error AccessDeniedException."
- request.clientMetadata is null for every source, InitiateAuth's
  ClientMetadata included, so the parameter that carried it is gone.

The branch also follows main since it was written: CognitoService takes
enforceTokenValidityLimits, and signUp ValidationData and ClientMetadata.

* fix(cognito): withdraw a code the CustomEmailSender could not take

Review of #6031: when the handover failed, the code issued for it stayed
live in SignUp, ForgotPassword and both attribute flows, so asking for a
code again within 30 seconds answered LimitExceededException. Measured
on Cognito (eu-west-1): it hands out a code again at once, on a healthy
pool and once a key that could not encrypt is enabled again, for
ResendConfirmationCode and ForgotPassword alike.

sendThroughCustomEmailSender now withdraws the code before it fails, for
every flow, and the two catches that withdrew it by hand (resend and the
sign-in OTP) leave that to it.

* fix(cognito): hand the CustomEmailSender the request's ClientMetadata

Review of #6031: the developer guide lists ClientMetadata for the
sign-up, forgot-password and sign-in sources, and the branch passed null
for every one on the strength of InitiateAuth alone. Measured on Cognito
(eu-west-1): SignUp, ResendConfirmationCode, ForgotPassword,
GetUserAttributeVerificationCode and UpdateUserAttributes each hand the
function the request's ClientMetadata; only the sign-in code's event has
none, even when InitiateAuth sends one. A request without ClientMetadata
gives null, as measured before.

ResendConfirmationCode, ForgotPassword and the two attribute calls now
take the request's ClientMetadata through the service, with overloads
that keep their previous signatures. resolveTriggerArn's custom sender
branch gets its braces.

---------

Co-authored-by: outof-place <contact@outofplace.space>
This commit is contained in:
Alessandro Lattaoandoutof-place authored and GitHub committed 2026-10-20 06:44:20 -04:00
1 parent 0e6db1f2b3
commit 47f570a821
8 files changed
+1209 -66

No files matched your search

@@ -1004,10 +1004,10 @@ final class CognitoAuthFlowHandler {
firePreAuthentication(pool, client, user, null, clientMetadata, false);
VerificationCode.Purpose purpose = "EMAIL_OTP".equals(challengeName)
? VerificationCode.Purpose.EMAIL_OTP : VerificationCode.Purpose.SMS_OTP;
Map<String, Object> customMessage = fireCustomMessage(pool, client, user, "CustomMessage_Authentication",
Map.of());
Map<String, Object> customMessage = customEmailSenderTakesOver(pool, deliveryMedium) ? Map.of()
: fireCustomMessage(pool, client, user, "CustomMessage_Authentication", Map.of());
Map<String, String> challengeParams = new HashMap<>(
service.issueSignInOtp(pool, user, purpose, attributeName, deliveryMedium, customMessage));
service.issueSignInOtp(pool, client, user, purpose, attributeName, deliveryMedium, customMessage));
challengeParams.put("USERNAME", user.getUsername());
return userAuthChallengeResponse(pool, client, user, challengeName, available, challengeParams);
}
@@ -1648,29 +1648,8 @@ final class CognitoAuthFlowHandler {
if (functionRef == null) return TriggerResult.notConfigured();
String region = regionForPool(pool);
Map<String, Object> event = new HashMap<>();
event.put("version", "1");
event.put("region", region);
event.put("userPoolId", pool.getId());
event.put("userName", user == null ? null : user.getUsername());
event.put("callerContext", Map.of(
"awsSdkVersion", "floci",
"clientId", client == null ? CLIENT_ID_NOT_APPLICABLE : client.getClientId()));
event.put("triggerSource", triggerSource);
Map<String, Object> req = new HashMap<>(request);
if (user != null) {
Map<String, String> userAttributes = new LinkedHashMap<>();
if (user.getAttributes() != null) {
userAttributes.putAll(user.getAttributes());
}
if ("PreAuthentication".equals(triggerKey)) {
userAttributes.put("cognito:user_status", user.getUserStatus());
}
req.put("userAttributes", userAttributes);
}
event.put("request", req);
event.put("response", new HashMap<>());
String clientId = client == null ? CLIENT_ID_NOT_APPLICABLE : client.getClientId();
Map<String, Object> event = triggerEvent(pool, clientId, user, triggerKey, triggerSource, request);
try {
byte[] payload = MAPPER.writeValueAsBytes(event);
@@ -1714,6 +1693,34 @@ final class CognitoAuthFlowHandler {
}
}
/** The event every trigger receives: the common parameters around the trigger's own request. */
private Map<String, Object> triggerEvent(UserPool pool, String clientId, CognitoUser user, String triggerKey,
String triggerSource, Map<String, Object> request) {
Map<String, Object> event = new HashMap<>();
event.put("version", "1");
event.put("region", regionForPool(pool));
event.put("userPoolId", pool.getId());
event.put("userName", user == null ? null : user.getUsername());
event.put("callerContext", Map.of(
"awsSdkVersion", "floci",
"clientId", clientId));
event.put("triggerSource", triggerSource);
Map<String, Object> req = new HashMap<>(request);
if (user != null) {
Map<String, String> userAttributes = new LinkedHashMap<>();
if (user.getAttributes() != null) {
userAttributes.putAll(user.getAttributes());
}
if ("PreAuthentication".equals(triggerKey) || "CustomEmailSender".equals(triggerKey)) {
userAttributes.put("cognito:user_status", user.getUserStatus());
}
req.put("userAttributes", userAttributes);
}
event.put("request", req);
event.put("response", new HashMap<>());
return event;
}
private static String lambdaFunctionErrorMessage(InvokeResult result) {
byte[] payload = result.getPayload();
if (payload == null || payload.length == 0) {
@@ -1891,6 +1898,40 @@ final class CognitoAuthFlowHandler {
return result.response();
}
boolean hasCustomEmailSender(UserPool pool) {
return lambdaService != null && resolveTriggerArn(pool, "CustomEmailSender") != null;
}
/** Whether a code going by {@code deliveryMedium} goes to the CustomEmailSender, so no CustomMessage shapes it. */
private boolean customEmailSenderTakesOver(UserPool pool, String deliveryMedium) {
return "EMAIL".equals(deliveryMedium) && hasCustomEmailSender(pool);
}
/**
* Hands an encrypted code to the pool's CustomEmailSender function, which delivers the email in
* Cognito's place. Cognito invokes custom sender triggers asynchronously, so the function's own
* outcome never reaches the caller; a function that cannot be invoked at all throws.
* {@code clientMetadata} is the request's ClientMetadata, or null when it carries none; the
* caller passes null for a sign-in code, whose event Cognito sends without InitiateAuth's
* (measured, eu-west-1, 2026-10-16 and 2026-10-20).
*/
void fireCustomEmailSender(UserPool pool, String clientId, CognitoUser user, String triggerSource,
String encryptedCode, Map<String, String> clientMetadata) {
Map<String, Object> req = new HashMap<>();
req.put("type", "customEmailSenderRequestV1");
req.put("code", encryptedCode);
req.put("clientMetadata", clientMetadata == null || clientMetadata.isEmpty() ? null : clientMetadata);
byte[] payload;
try {
payload = MAPPER.writeValueAsBytes(
triggerEvent(pool, clientId, user, "CustomEmailSender", triggerSource, req));
} catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot serialize the CustomEmailSender event", e);
}
lambdaService.invoke(regionForPool(pool), resolveTriggerArn(pool, "CustomEmailSender"), payload,
InvocationType.Event);
}
private CognitoService.ClaimsOverride firePreTokenGeneration(UserPool pool, UserPoolClient client, CognitoUser user,
Map<String, String> clientMetadata, String triggerSource,
List<String> scopes) {
@@ -2132,9 +2173,9 @@ final class CognitoAuthFlowHandler {
return totpChallenge(pool, client, user, TotpPhase.CODE_REQUIRED, triggerSource, metadata);
}
boolean sms = "SMS_MFA".equals(factor);
Map<String, Object> customMessage = fireCustomMessage(pool, client, user, "CustomMessage_Authentication",
Map.of());
Map<String, String> parameters = new HashMap<>(service.issueMfaCode(pool, user,
Map<String, Object> customMessage = customEmailSenderTakesOver(pool, sms ? "SMS" : "EMAIL") ? Map.of()
: fireCustomMessage(pool, client, user, "CustomMessage_Authentication", Map.of());
Map<String, String> parameters = new HashMap<>(service.issueMfaCode(pool, client, user,
sms ? VerificationCode.Purpose.SMS_MFA : VerificationCode.Purpose.EMAIL_MFA,
sms ? "phone_number" : "email", sms ? "SMS" : "EMAIL", customMessage));
parameters.put("USERNAME", user.getUsername());
@@ -2307,6 +2348,10 @@ final class CognitoAuthFlowHandler {
if (cfg == null) return null;
Object v = cfg.get(triggerKey);
if (v instanceof String s && !s.isBlank()) return s;
// Custom sender triggers are configured as { LambdaArn, LambdaVersion }.
if (v instanceof Map<?, ?> m && m.get("LambdaArn") instanceof String arn && !arn.isBlank()) {
return arn;
}
// V2 form: PreTokenGeneration is configured under "PreTokenGenerationConfig"
// as { LambdaArn, LambdaVersion } (UpdateUserPool / UpdateUserPoolClient
// API). Fall through so callers using the V1 key still work, and pick up
@@ -1038,7 +1038,8 @@ public class CognitoJsonHandler {
private Response handleResendConfirmationCode(JsonNode request) {
Map<String, String> deliveryDetails = service.resendConfirmationCode(
request.path("ClientId").asText(),
request.path("Username").asText()
request.path("Username").asText(),
clientMetadata(request)
);
ObjectNode response = objectMapper.createObjectNode();
ObjectNode delivery = response.putObject("CodeDeliveryDetails");
@@ -1070,7 +1071,8 @@ public class CognitoJsonHandler {
private Response handleForgotPassword(JsonNode request) {
Map<String, Object> deliveryDetails = service.forgotPassword(
request.path("ClientId").asText(),
request.path("Username").asText()
request.path("Username").asText(),
clientMetadata(request)
);
ObjectNode response = objectMapper.createObjectNode();
ObjectNode delivery = response.putObject("CodeDeliveryDetails");
@@ -1105,7 +1107,8 @@ public class CognitoJsonHandler {
private Response handleGetUserAttributeVerificationCode(JsonNode request) {
Map<String, Object> deliveryDetails = service.getUserAttributeVerificationCode(
request.path("AccessToken").asText(),
request.path("AttributeName").asText()
request.path("AttributeName").asText(),
clientMetadata(request)
);
ObjectNode response = objectMapper.createObjectNode();
ObjectNode delivery = response.putObject("CodeDeliveryDetails");
@@ -1127,7 +1130,7 @@ public class CognitoJsonHandler {
private Response handleUpdateUserAttributes(JsonNode request) {
Map<String, String> attrs = readNameValuePairs(request, "UserAttributes");
List<Map<String, Object>> deliveryDetails = service.updateUserAttributes(
request.path("AccessToken").asText(), attrs);
request.path("AccessToken").asText(), attrs, clientMetadata(request));
ObjectNode response = objectMapper.createObjectNode();
response.set("CodeDeliveryDetailsList", objectMapper.valueToTree(deliveryDetails));
return Response.ok(response).build();
@@ -47,9 +47,11 @@ import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain;
import io.github.hectorvent.floci.services.cognito.model.WebAuthnConfiguration;
import io.github.hectorvent.floci.services.cognito.model.WebAuthnCredential;
import io.github.hectorvent.floci.services.cognito.verification.CognitoMessageDispatcher;
import io.github.hectorvent.floci.services.cognito.verification.CustomSenderCodeEncryptor;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCode;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeException;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeService;
import io.github.hectorvent.floci.services.kms.KmsService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.secretsmanager.RandomPasswordGenerator;
import io.github.hectorvent.floci.services.ses.SesService;
@@ -178,6 +180,7 @@ public class CognitoService implements ResourceProvider {
private final AcmService acmService;
private final VerificationCodeService verificationCodeService;
private final CognitoMessageDispatcher messageDispatcher;
private final CustomSenderCodeEncryptor customSenderCodeEncryptor;
private final TlsCertificateManager certificateManager;
private final boolean enforceTokenValidityLimits;
private final Object[] userLocks = newUserLockStripes();
@@ -204,7 +207,7 @@ public class CognitoService implements ResourceProvider {
@Inject
public CognitoService(StorageFactory storageFactory, EmulatorConfig emulatorConfig,
RegionResolver regionResolver, LambdaService lambdaService, AcmService acmService,
SesService sesService, SnsService snsService, Clock clock,
SesService sesService, SnsService snsService, KmsService kmsService, Clock clock,
TlsCertificateManager certificateManager) {
this(
storageFactory.create("cognito", "cognito-pools.json",
@@ -232,7 +235,8 @@ public class CognitoService implements ResourceProvider {
new CognitoMessageDispatcher(sesService, snsService, regionResolver.getDefaultRegion()),
certificateManager,
clock,
emulatorConfig.services().cognito().enforceTokenValidityLimits()
emulatorConfig.services().cognito().enforceTokenValidityLimits(),
new CustomSenderCodeEncryptor(kmsService)
);
}
@@ -326,7 +330,7 @@ public class CognitoService implements ResourceProvider {
Clock clock) {
this(poolStore, clientStore, resourceServerStore, domainStore, identityProviderStore, userStore,
groupStore, revokedTokenStore, baseUrl, cloudFrontDomainSuffix, regionResolver, lambdaService,
acmService, verificationCodeService, messageDispatcher, certificateManager, clock, true);
acmService, verificationCodeService, messageDispatcher, certificateManager, clock, true, null);
}
/**
@@ -335,6 +339,8 @@ public class CognitoService implements ResourceProvider {
*
* @param enforceTokenValidityLimits whether an app client's token validity must be within AWS's
* limits; see {@link #validateTokenValidityLimits}
* @param customSenderCodeEncryptor encrypts the codes handed to custom sender triggers, which
* stay unavailable without it
*/
CognitoService(StorageBackend<String, UserPool> poolStore,
StorageBackend<String, UserPoolClient> clientStore,
@@ -351,7 +357,8 @@ public class CognitoService implements ResourceProvider {
CognitoMessageDispatcher messageDispatcher,
TlsCertificateManager certificateManager,
Clock clock,
boolean enforceTokenValidityLimits) {
boolean enforceTokenValidityLimits,
CustomSenderCodeEncryptor customSenderCodeEncryptor) {
this.poolStore = poolStore;
this.clientStore = clientStore;
this.resourceServerStore = resourceServerStore;
@@ -367,6 +374,7 @@ public class CognitoService implements ResourceProvider {
this.acmService = acmService;
this.verificationCodeService = verificationCodeService;
this.messageDispatcher = messageDispatcher;
this.customSenderCodeEncryptor = customSenderCodeEncryptor;
this.certificateManager = certificateManager;
this.enforceTokenValidityLimits = enforceTokenValidityLimits;
this.authFlowHandler = new CognitoAuthFlowHandler(this, lambdaService, regionResolver, clock);
@@ -391,6 +399,7 @@ public class CognitoService implements ResourceProvider {
pool.setClientIdOverride(getClientIdOverride(userPoolTags));
pool.setClientSecretOverride(ReservedTags.extractOverrideCognitoClientSecret(userPoolTags));
populateUserPool(pool, request);
requireCustomSenderKey(pool, true, region);
ensureJwtSigningKeys(pool);
ensureRefreshTokenSecret(pool);
@@ -399,6 +408,26 @@ public class CognitoService implements ResourceProvider {
return pool;
}
/**
* Measured (eu-west-1, 2026-10-16): a custom sender trigger needs a KMSKeyID, on CreateUserPool
* and UpdateUserPool alike, and CreateUserPool refuses a key that does not exist, since the grant
* Cognito creates on it fails.
*/
private void requireCustomSenderKey(UserPool pool, boolean create, String region) {
Map<String, Object> config = pool.getLambdaConfig();
if (config == null || (!config.containsKey("CustomEmailSender") && !config.containsKey("CustomSMSSender"))) {
return;
}
if (!(config.get("KMSKeyID") instanceof String keyId) || keyId.isBlank()) {
throw new AwsException("InvalidParameterException",
"KMSKeyId parameter is required when Custom SMS/Email Lambda trigger is used.", 400);
}
if (create && customSenderCodeEncryptor != null && !customSenderCodeEncryptor.keyExists(keyId, region)) {
throw new AwsException("InvalidParameterException", "Encountered error when CreateGrant was attempted"
+ " on the input KMS key - Key '" + keyId + "' does not exist", 400);
}
}
private @Nullable String getClientIdOverride(Map<String, String> userPoolTags) {
String overrideMode = ReservedTags.extractOverrideCognitoClientId(userPoolTags);
if (overrideMode != null &&
@@ -414,6 +443,9 @@ public class CognitoService implements ResourceProvider {
UserPool updatedPool = MAPPER.convertValue(pool, UserPool.class);
populateUserPool(updatedPool, request);
if (request.containsKey("LambdaConfig")) {
requireCustomSenderKey(updatedPool, false, region);
}
if (request.get("PoolName") instanceof String poolName && !poolName.isBlank()) {
updatedPool.setName(poolName);
}
@@ -3382,13 +3414,19 @@ public class CognitoService implements ResourceProvider {
try {
String code = verificationCodeService.issue(pool.getId(), user.getUsername(),
VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));
Map<String, Object> customMessage = authFlowHandler.fireCustomMessage(
pool, client, triggerUser, "CustomMessage_SignUp", clientMetadata);
messageDispatcher.dispatch(pool, triggerUser, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
code, List.of(deliveryTarget.deliveryMedium()), customMessage);
if (!sendThroughCustomEmailSender(pool, client.getClientId(), triggerUser,
deliveryTarget.deliveryMedium(), "CustomEmailSender_SignUp",
VerificationCode.Purpose.SIGNUP_CONFIRMATION, code, clientMetadata)) {
Map<String, Object> customMessage = authFlowHandler.fireCustomMessage(
pool, client, triggerUser, "CustomMessage_SignUp", clientMetadata);
messageDispatcher.dispatch(pool, triggerUser, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
code, List.of(deliveryTarget.deliveryMedium()), customMessage);
}
} catch (VerificationCodeException e) {
rollbackSignUpConfirmationArtifacts(user);
throw mapVerificationCodeException(e);
} catch (CustomEmailSenderException e) {
throw e;
} catch (RuntimeException e) {
rollbackSignUpConfirmationArtifacts(user);
throw new AwsException("CodeDeliveryFailureException",
@@ -3483,6 +3521,11 @@ public class CognitoService implements ResourceProvider {
}
public Map<String, String> resendConfirmationCode(String clientId, String username) {
return resendConfirmationCode(clientId, username, Map.of());
}
public Map<String, String> resendConfirmationCode(String clientId, String username,
Map<String, String> clientMetadata) {
UserPoolClient client = clientStore.get(clientId)
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found",
400));
@@ -3509,12 +3552,18 @@ public class CognitoService implements ResourceProvider {
try {
String code = verificationCodeService.issue(pool.getId(), user.getUsername(),
VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));
Map<String, Object> customMessage = authFlowHandler.fireCustomMessage(
pool, client, user, "CustomMessage_ResendCode", Map.of());
messageDispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
code, List.of(deliveryTarget.deliveryMedium()), customMessage);
if (!sendThroughCustomEmailSender(pool, client.getClientId(), user,
deliveryTarget.deliveryMedium(), "CustomEmailSender_ResendCode",
VerificationCode.Purpose.SIGNUP_CONFIRMATION, code, clientMetadata)) {
Map<String, Object> customMessage = authFlowHandler.fireCustomMessage(
pool, client, user, "CustomMessage_ResendCode", Map.of());
messageDispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
code, List.of(deliveryTarget.deliveryMedium()), customMessage);
}
} catch (VerificationCodeException e) {
throw mapVerificationCodeException(e);
} catch (CustomEmailSenderException e) {
throw e;
} catch (RuntimeException e) {
verificationCodeService.invalidatePrevious(pool.getId(), user.getUsername(),
VerificationCode.Purpose.SIGNUP_CONFIRMATION);
@@ -3897,6 +3946,10 @@ public class CognitoService implements ResourceProvider {
}
public Map<String, Object> forgotPassword(String clientId, String username) {
return forgotPassword(clientId, username, Map.of());
}
public Map<String, Object> forgotPassword(String clientId, String username, Map<String, String> clientMetadata) {
UserPoolClient client = clientStore.get(clientId)
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 400));
UserPool pool = describeUserPool(client.getUserPoolId());
@@ -3910,10 +3963,14 @@ public class CognitoService implements ResourceProvider {
try {
String code = verificationCodeService.issue(pool.getId(), user.getUsername(),
VerificationCode.Purpose.PASSWORD_RESET, Duration.ofHours(1));
Map<String, Object> customMessage = authFlowHandler.fireCustomMessage(
pool, client, user, "CustomMessage_ForgotPassword", Map.of());
messageDispatcher.dispatch(pool, user, VerificationCode.Purpose.PASSWORD_RESET, code,
List.of(deliveryTarget.deliveryMedium()), customMessage);
if (!sendThroughCustomEmailSender(pool, client.getClientId(), user,
deliveryTarget.deliveryMedium(), "CustomEmailSender_ForgotPassword",
VerificationCode.Purpose.PASSWORD_RESET, code, clientMetadata)) {
Map<String, Object> customMessage = authFlowHandler.fireCustomMessage(
pool, client, user, "CustomMessage_ForgotPassword", Map.of());
messageDispatcher.dispatch(pool, user, VerificationCode.Purpose.PASSWORD_RESET, code,
List.of(deliveryTarget.deliveryMedium()), customMessage);
}
} catch (VerificationCodeException e) {
throw mapVerificationCodeException(e);
}
@@ -3992,6 +4049,11 @@ public class CognitoService implements ResourceProvider {
}
public Map<String, Object> getUserAttributeVerificationCode(String accessToken, String attributeName) {
return getUserAttributeVerificationCode(accessToken, attributeName, Map.of());
}
public Map<String, Object> getUserAttributeVerificationCode(String accessToken, String attributeName,
Map<String, String> clientMetadata) {
VerifiedAccessToken token;
try {
token = verifyAccessToken(accessToken);
@@ -4007,12 +4069,13 @@ public class CognitoService implements ResourceProvider {
String poolId = token.poolId();
synchronized (userLock(poolId, username)) {
return getUserAttributeVerificationCodeUnderUserLock(poolId, username, attributeName);
return getUserAttributeVerificationCodeUnderUserLock(poolId, username, token.clientId(), attributeName,
clientMetadata);
}
}
private Map<String, Object> getUserAttributeVerificationCodeUnderUserLock(
String poolId, String username, String attributeName) {
String poolId, String username, String clientId, String attributeName, Map<String, String> clientMetadata) {
if (!"email".equals(attributeName) && !"phone_number".equals(attributeName)) {
throw new AwsException("InvalidParameterException",
"Invalid attribute name. Only phone_number and email can be verified.", 400);
@@ -4037,7 +4100,8 @@ public class CognitoService implements ResourceProvider {
try {
String code = verificationCodeService.issue(poolId, user.getUsername(),
purpose, Duration.ofHours(24));
dispatchAttributeVerificationCode(pool, user, attributeName, destination, purpose, code);
dispatchAttributeVerificationCode(pool, clientId, user, attributeName, destination, purpose, code,
"CustomEmailSender_VerifyUserAttribute", clientMetadata);
} catch (VerificationCodeException e) {
throw mapVerificationCodeException(e);
}
@@ -4107,6 +4171,11 @@ public class CognitoService implements ResourceProvider {
}
public List<Map<String, Object>> updateUserAttributes(String accessToken, Map<String, String> attributes) {
return updateUserAttributes(accessToken, attributes, Map.of());
}
public List<Map<String, Object>> updateUserAttributes(String accessToken, Map<String, String> attributes,
Map<String, String> clientMetadata) {
VerifiedAccessToken token = verifyAccessToken(accessToken);
requireScope(accessToken, USER_ADMIN_SCOPE);
String username = token.username();
@@ -4123,12 +4192,13 @@ public class CognitoService implements ResourceProvider {
}
synchronized (userLock(poolId, username)) {
return updateUserAttributesUnderUserLock(poolId, username, attributes);
return updateUserAttributesUnderUserLock(poolId, username, token.clientId(), attributes, clientMetadata);
}
}
private List<Map<String, Object>> updateUserAttributesUnderUserLock(
String poolId, String username, Map<String, String> attributes) {
String poolId, String username, String clientId, Map<String, String> attributes,
Map<String, String> clientMetadata) {
UserPool pool = describeUserPool(poolId);
CognitoUser currentUser = adminGetUser(poolId, username);
validateEmailAttribute(attributes, true);
@@ -4171,8 +4241,8 @@ public class CognitoService implements ResourceProvider {
ensureVerificationWiring();
String verificationCode = verificationCodeService.issue(
poolId, currentUser.getUsername(), purpose, Duration.ofHours(24));
dispatchAttributeVerificationCode(pool, currentUser, attributeName, value,
purpose, verificationCode);
dispatchAttributeVerificationCode(pool, clientId, currentUser, attributeName, value,
purpose, verificationCode, "CustomEmailSender_UpdateUserAttribute", clientMetadata);
if (requiresVerificationBeforeUpdate(pool, attributeName)) {
updatedUser.getPendingAttributes().put(attributeName, value);
@@ -5903,13 +5973,76 @@ public class CognitoService implements ResourceProvider {
return configured instanceof List<?> attributes && attributes.contains(attributeName);
}
private void dispatchAttributeVerificationCode(UserPool pool, CognitoUser user,
private void dispatchAttributeVerificationCode(UserPool pool, String clientId, CognitoUser user,
String attributeName, String destination,
VerificationCode.Purpose purpose, String code) {
VerificationCode.Purpose purpose, String code,
String customEmailSenderSource,
Map<String, String> clientMetadata) {
CognitoUser deliveryUser = MAPPER.convertValue(user, CognitoUser.class);
deliveryUser.getAttributes().put(attributeName, destination);
messageDispatcher.dispatch(pool, deliveryUser, purpose, code,
List.of(deliveryMedium(attributeName)));
if (!sendThroughCustomEmailSender(pool, clientId, deliveryUser, deliveryMedium(attributeName),
customEmailSenderSource, purpose, code, clientMetadata)) {
messageDispatcher.dispatch(pool, deliveryUser, purpose, code,
List.of(deliveryMedium(attributeName)));
}
}
/**
* Hands {@code code} to the pool's CustomEmailSender function when the pool has one and the
* code goes by email, in place of the message Cognito would send and of the CustomMessage
* trigger that would shape it. Returns whether it did. The code is encrypted under the pool's
* {@code KMSKeyID}; a key that cannot encrypt, or a function that cannot be invoked, fails the
* delivery and withdraws the code, issued for {@code purpose}, so it can be asked for again at
* once, as on Cognito (measured).
*/
private boolean sendThroughCustomEmailSender(UserPool pool, String clientId, CognitoUser user,
String deliveryMedium, String triggerSource,
VerificationCode.Purpose purpose, String code,
Map<String, String> clientMetadata) {
if (!"EMAIL".equals(deliveryMedium) || !authFlowHandler.hasCustomEmailSender(pool)) {
return false;
}
if (customSenderCodeEncryptor == null) {
throw new IllegalStateException("custom sender encryption is not configured");
}
String encryptedCode;
try {
encryptedCode = customSenderCodeEncryptor.encrypt((String) pool.getLambdaConfig().get("KMSKeyID"),
pool.getId(), code, AwsArnUtils.regionOrDefault(pool.getArn(), regionResolver.getDefaultRegion()));
} catch (AwsException e) {
// Measured (eu-west-1, 2026-10-16): a disabled key and one pending deletion fail the
// request, sign-in included, with these CodeDeliveryFailureExceptions.
LOG.warnv("Cannot encrypt a {0} code for pool {1}: {2}", triggerSource, pool.getId(), e.getMessage());
throw undelivered(pool, user, purpose, "CodeDeliveryFailureException",
"DisabledException".equals(e.getErrorCode())
? "Caller needs to enable the configured KMS Key"
: "Unable to encrypt CustomEmailSender/CustomSMSSender code using the configured KMS Key");
}
try {
authFlowHandler.fireCustomEmailSender(pool, clientId, user, triggerSource, encryptedCode, clientMetadata);
} catch (AwsException e) {
// Measured: a function that is gone, or that Cognito may not invoke, answers this.
LOG.warnv("Cannot invoke the CustomEmailSender of pool {0}: {1}", pool.getId(), e.getMessage());
throw undelivered(pool, user, purpose, "UnexpectedLambdaException",
"CustomEmailSender invocation failed due to error AccessDeniedException.");
}
return true;
}
private CustomEmailSenderException undelivered(UserPool pool, CognitoUser user, VerificationCode.Purpose purpose,
String errorCode, String message) {
verificationCodeService.invalidatePrevious(pool.getId(), user.getUsername(), purpose);
return new CustomEmailSenderException(errorCode, message);
}
/**
* The CustomEmailSender could not take a code: the request fails with this, and unlike a failed
* SES or SNS delivery a sign-up is kept (measured), since only the code was not delivered.
*/
private static final class CustomEmailSenderException extends AwsException {
CustomEmailSenderException(String errorCode, String message) {
super(errorCode, message, 400);
}
}
private void ensureAliasAvailable(UserPool pool, CognitoUser currentUser,
@@ -6032,16 +6165,23 @@ public class CognitoService implements ResourceProvider {
* the SignUp/ForgotPassword code-delivery path. Returns the masked CODE_DELIVERY challenge
* parameters for the InitiateAuth/RespondToAuthChallenge response.
*/
Map<String, String> issueSignInOtp(UserPool pool, CognitoUser user, VerificationCode.Purpose purpose,
String attributeName, String deliveryMedium, Map<String, Object> customMessageResponse) {
Map<String, String> issueSignInOtp(UserPool pool, UserPoolClient client, CognitoUser user,
VerificationCode.Purpose purpose, String attributeName, String deliveryMedium,
Map<String, Object> customMessageResponse) {
ensureVerificationWiring();
String destination = user.getAttributes().get(attributeName);
String code;
try {
code = verificationCodeService.issue(pool.getId(), user.getUsername(), purpose, Duration.ofMinutes(5));
messageDispatcher.dispatch(pool, user, purpose, code, List.of(deliveryMedium), customMessageResponse);
if (!sendThroughCustomEmailSender(pool, client.getClientId(), user, deliveryMedium,
"CustomEmailSender_Authentication", purpose, code, null)) {
messageDispatcher.dispatch(pool, user, purpose, code, List.of(deliveryMedium), customMessageResponse);
}
} catch (VerificationCodeException e) {
throw mapVerificationCodeException(e);
} catch (CustomEmailSenderException e) {
// Measured: InitiateAuth answers the sender's own error, not InternalErrorException.
throw e;
} catch (RuntimeException e) {
// The code was already issued and stored before dispatch failed; invalidate it so
// the rate limiter doesn't block an immediate retry for a code the user never
@@ -6383,11 +6523,11 @@ public class CognitoService implements ResourceProvider {
* moments ago is still live, that one, since each sign-in asks for a code and the code store
* paces new ones. Returns the CODE_DELIVERY challenge parameters.
*/
Map<String, String> issueMfaCode(UserPool pool, CognitoUser user, VerificationCode.Purpose purpose,
String attributeName, String deliveryMedium,
Map<String, String> issueMfaCode(UserPool pool, UserPoolClient client, CognitoUser user,
VerificationCode.Purpose purpose, String attributeName, String deliveryMedium,
Map<String, Object> customMessageResponse) {
try {
return issueSignInOtp(pool, user, purpose, attributeName, deliveryMedium, customMessageResponse);
return issueSignInOtp(pool, client, user, purpose, attributeName, deliveryMedium, customMessageResponse);
} catch (AwsException e) {
if (!"LimitExceededException".equals(e.getErrorCode())) {
throw e;
@@ -0,0 +1,213 @@
package io.github.hectorvent.floci.services.cognito.verification;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.kms.KmsService;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECGenParameterSpec;
import java.util.Arrays;
import java.util.Base64;
import java.util.Map;
import java.util.TreeMap;
/**
* Encrypts the secrets Cognito hands to a custom sender Lambda trigger the way Cognito does: as an
* AWS Encryption SDK message under the pool's KMS key, with the encryption context
* {@code {"userpool-id": <pool id>}}, so a function decrypts it with the Encryption SDK's KMS
* keyring or master key provider exactly as it would on AWS.
*
* <p>The message uses the SDK's default suite for a non-committing client, the one Cognito's
* ciphertexts carry: format version 1, algorithm suite {@code 0x0378} (AES-256-GCM under a key
* derived with HKDF-SHA384, signed with ECDSA P-384), one {@code aws-kms} encrypted data key from
* {@code GenerateDataKey}, and the secret in a single final frame.
*/
public final class CustomSenderCodeEncryptor {
public static final String USER_POOL_ID_CONTEXT_KEY = "userpool-id";
private static final short ALGORITHM_SUITE_ID = 0x0378;
private static final int MESSAGE_ID_LENGTH = 16;
private static final int DATA_KEY_LENGTH = 32;
private static final int IV_LENGTH = 12;
private static final int TAG_BITS = 128;
private static final int FRAME_LENGTH = 4096;
private static final int P384_FIELD_LENGTH = 48;
// The Encryption SDK writes every P-384 signature at this length; DER encodings vary by a byte.
private static final int SIGNATURE_LENGTH = 103;
private static final int MAX_SIGNING_ATTEMPTS = 64;
private static final String PUBLIC_KEY_CONTEXT_KEY = "aws-crypto-public-key";
private static final byte[] KMS_PROVIDER_ID = "aws-kms".getBytes(StandardCharsets.UTF_8);
private static final byte[] FINAL_FRAME_CONTENT = "AWSKMSEncryptionClient Final Frame"
.getBytes(StandardCharsets.UTF_8);
private final KmsService kms;
private final SecureRandom random = new SecureRandom();
public CustomSenderCodeEncryptor(KmsService kms) {
this.kms = kms;
}
/** Whether {@code kmsKeyId} names a key KMS has, which Cognito checks when it creates its grant. */
public boolean keyExists(String kmsKeyId, String region) {
try {
kms.describeKey(kmsKeyId, region);
return true;
} catch (AwsException e) {
if ("NotFoundException".equals(e.getErrorCode())) {
return false;
}
throw e;
}
}
/** Returns the base64 Encryption SDK message that carries {@code secret}, as the event's {@code code}. */
public String encrypt(String kmsKeyId, String userPoolId, String secret, String region) {
try {
KeyPair signingKey = signingKeyPair();
Map<String, String> encryptionContext = new TreeMap<>();
encryptionContext.put(USER_POOL_ID_CONTEXT_KEY, userPoolId);
encryptionContext.put(PUBLIC_KEY_CONTEXT_KEY,
Base64.getEncoder().encodeToString(compressedPoint((ECPublicKey) signingKey.getPublic())));
Map<String, Object> dataKey = kms.generateDataKey(kmsKeyId, "AES_256", null, encryptionContext, region);
byte[] plaintextDataKey = (byte[]) dataKey.get("Plaintext");
byte[] messageId = new byte[MESSAGE_ID_LENGTH];
random.nextBytes(messageId);
SecretKeySpec cipherKey = deriveKey(plaintextDataKey, messageId);
Arrays.fill(plaintextDataKey, (byte) 0);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream message = new DataOutputStream(bytes);
message.writeByte(1);
message.writeByte(0x80);
message.writeShort(ALGORITHM_SUITE_ID);
message.write(messageId);
byte[] serializedContext = serialize(encryptionContext);
message.writeShort(serializedContext.length);
message.write(serializedContext);
message.writeShort(1);
writeWithLength(message, KMS_PROVIDER_ID);
writeWithLength(message, ((String) dataKey.get("KeyId")).getBytes(StandardCharsets.UTF_8));
writeWithLength(message, (byte[]) dataKey.get("CiphertextBlob"));
message.writeByte(2);
message.writeInt(0);
message.writeByte(IV_LENGTH);
message.writeInt(FRAME_LENGTH);
byte[] headerIv = new byte[IV_LENGTH];
byte[] headerTag = seal(cipherKey, headerIv, bytes.toByteArray(), new byte[0]);
message.write(headerIv);
message.write(headerTag);
byte[] content = secret.getBytes(StandardCharsets.UTF_8);
int sequenceNumber = 1;
byte[] frameIv = ByteBuffer.allocate(IV_LENGTH).putInt(IV_LENGTH - Integer.BYTES, sequenceNumber).array();
byte[] frameAad = ByteBuffer.allocate(MESSAGE_ID_LENGTH + FINAL_FRAME_CONTENT.length + Integer.BYTES + Long.BYTES)
.put(messageId)
.put(FINAL_FRAME_CONTENT)
.putInt(sequenceNumber)
.putLong(content.length)
.array();
message.writeInt(0xFFFFFFFF);
message.writeInt(sequenceNumber);
message.write(frameIv);
message.writeInt(content.length);
message.write(seal(cipherKey, frameIv, frameAad, content));
byte[] signature = sign(signingKey.getPrivate(), bytes.toByteArray());
message.writeShort(signature.length);
message.write(signature);
return Base64.getEncoder().encodeToString(bytes.toByteArray());
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (GeneralSecurityException e) {
throw new IllegalStateException("Cannot encrypt a custom sender code", e);
}
}
private KeyPair signingKeyPair() throws GeneralSecurityException {
KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
generator.initialize(new ECGenParameterSpec("secp384r1"), random);
return generator.generateKeyPair();
}
private static byte[] compressedPoint(ECPublicKey publicKey) {
byte[] point = new byte[1 + P384_FIELD_LENGTH];
point[0] = (byte) (publicKey.getW().getAffineY().testBit(0) ? 0x03 : 0x02);
byte[] x = unsigned(publicKey.getW().getAffineX());
System.arraycopy(x, 0, point, point.length - x.length, x.length);
return point;
}
private static byte[] unsigned(BigInteger value) {
byte[] bytes = value.toByteArray();
return bytes[0] == 0 && bytes.length > 1 ? Arrays.copyOfRange(bytes, 1, bytes.length) : bytes;
}
/** HKDF-SHA384 with no salt and the suite ID and message ID as info, per format version 1. */
private static SecretKeySpec deriveKey(byte[] dataKey, byte[] messageId) throws GeneralSecurityException {
Mac extract = Mac.getInstance("HmacSHA384");
extract.init(new SecretKeySpec(new byte[extract.getMacLength()], "HmacSHA384"));
byte[] pseudoRandomKey = extract.doFinal(dataKey);
Mac expand = Mac.getInstance("HmacSHA384");
expand.init(new SecretKeySpec(pseudoRandomKey, "HmacSHA384"));
expand.update(ByteBuffer.allocate(Short.BYTES).putShort(ALGORITHM_SUITE_ID).array());
expand.update(messageId);
expand.update((byte) 1);
return new SecretKeySpec(Arrays.copyOf(expand.doFinal(), DATA_KEY_LENGTH), "AES");
}
/** AES-GCM; returns the ciphertext followed by the tag. */
private static byte[] seal(SecretKeySpec key, byte[] iv, byte[] aad, byte[] plaintext)
throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, iv));
cipher.updateAAD(aad);
return cipher.doFinal(plaintext);
}
private static byte[] sign(PrivateKey key, byte[] data) throws GeneralSecurityException {
byte[] signature = null;
for (int attempt = 0; attempt < MAX_SIGNING_ATTEMPTS
&& (signature == null || signature.length != SIGNATURE_LENGTH); attempt++) {
Signature signer = Signature.getInstance("SHA384withECDSA");
signer.initSign(key);
signer.update(data);
signature = signer.sign();
}
return signature;
}
/** The key-value pairs in ascending key order, each length-prefixed, after their count. */
private static byte[] serialize(Map<String, String> sortedContext) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bytes);
out.writeShort(sortedContext.size());
for (Map.Entry<String, String> entry : sortedContext.entrySet()) {
writeWithLength(out, entry.getKey().getBytes(StandardCharsets.UTF_8));
writeWithLength(out, entry.getValue().getBytes(StandardCharsets.UTF_8));
}
return bytes.toByteArray();
}
private static void writeWithLength(DataOutputStream out, byte[] value) throws IOException {
out.writeShort(value.length);
out.write(value);
}
}