diff --git a/compatibility-tests/sdk-test-python/requirements.txt b/compatibility-tests/sdk-test-python/requirements.txt index 64cfc393c6..8015a62fe5 100644 --- a/compatibility-tests/sdk-test-python/requirements.txt +++ b/compatibility-tests/sdk-test-python/requirements.txt @@ -1,6 +1,7 @@ boto3==1.43.108 botocore==1.43.108 cryptography>=42.0.0 +aws-encryption-sdk==4.0.7 pytest>=8.0.0 pytest-timeout>=2.3.0 cramjam==2.12.1 diff --git a/compatibility-tests/sdk-test-python/tests/test_cognito_custom_email_sender.py b/compatibility-tests/sdk-test-python/tests/test_cognito_custom_email_sender.py new file mode 100644 index 0000000000..5f046d055c --- /dev/null +++ b/compatibility-tests/sdk-test-python/tests/test_cognito_custom_email_sender.py @@ -0,0 +1,152 @@ +"""Cognito CustomEmailSender trigger, decrypted with the AWS Encryption SDK as a real function would.""" + +import base64 +import io +import json +import time +import zipfile + +import aws_encryption_sdk +import botocore.session +import pytest +from aws_encryption_sdk.identifiers import CommitmentPolicy + +# Forwards the event it receives to SQS, so the test can read what Cognito sent. +SENDER_CODE = ( + "const { SQSClient, SendMessageCommand } = require('@aws-sdk/client-sqs');\n" + "exports.handler = async (event) => {\n" + " await new SQSClient({ useQueueUrlAsEndpoint: false }).send(new SendMessageCommand({\n" + " QueueUrl: process.env.QUEUE_URL, MessageBody: JSON.stringify(event) }));\n" + "};\n" +) + + +def _sender_zip(): + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as zf: + zf.writestr("index.js", SENDER_CODE) + return buf.getvalue() + + +def _next_event(sqs_client, queue_url, timeout=90): + deadline = time.time() + timeout + while time.time() < deadline: + messages = sqs_client.receive_message( + QueueUrl=queue_url, MaxNumberOfMessages=1, WaitTimeSeconds=5 + ).get("Messages", []) + if messages: + sqs_client.delete_message( + QueueUrl=queue_url, ReceiptHandle=messages[0]["ReceiptHandle"] + ) + return json.loads(messages[0]["Body"]) + raise AssertionError("the CustomEmailSender function was not invoked") + + +@pytest.fixture +def decrypt(aws_config, monkeypatch): + """Decrypts a code with the Encryption SDK's strict KMS master key provider, KMS being Floci's.""" + monkeypatch.setenv("AWS_ENDPOINT_URL_KMS", aws_config["endpoint_url"]) + session = botocore.session.Session() + session.set_credentials( + aws_config["aws_access_key_id"], aws_config["aws_secret_access_key"] + ) + client = aws_encryption_sdk.EncryptionSDKClient( + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT + ) + + def _decrypt(code, key_arn): + provider = aws_encryption_sdk.StrictAwsKmsMasterKeyProvider( + key_ids=[key_arn], botocore_session=session + ) + plaintext, header = client.decrypt(source=base64.b64decode(code), key_provider=provider) + return plaintext.decode("utf-8"), header.encryption_context + + return _decrypt + + +@pytest.fixture +def sender_pool(cognito_client, kms_client, lambda_client, sqs_client, unique_name): + queue_url = sqs_client.create_queue(QueueName=f"sender-{unique_name}")["QueueUrl"] + function_arn = lambda_client.create_function( + FunctionName=f"sender-{unique_name}", + Runtime="nodejs20.x", + Role="arn:aws:iam::000000000000:role/lambda-role", + Handler="index.handler", + Timeout=30, + Code={"ZipFile": _sender_zip()}, + Environment={"Variables": {"QUEUE_URL": queue_url}}, + )["FunctionArn"] + key_arn = kms_client.create_key(Description="custom sender codes")["KeyMetadata"][ + "Arn" + ] + pool_id = cognito_client.create_user_pool( + PoolName=f"sender-{unique_name}", + AutoVerifiedAttributes=["email"], + LambdaConfig={ + "KMSKeyID": key_arn, + "CustomEmailSender": {"LambdaArn": function_arn, "LambdaVersion": "V1_0"}, + }, + )["UserPool"]["Id"] + client_id = cognito_client.create_user_pool_client( + UserPoolId=pool_id, + ClientName="app", + ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"], + )["UserPoolClient"]["ClientId"] + + yield { + "pool_id": pool_id, + "client_id": client_id, + "key_arn": key_arn, + "queue_url": queue_url, + } + + cognito_client.delete_user_pool(UserPoolId=pool_id) + lambda_client.delete_function(FunctionName=function_arn) + sqs_client.delete_queue(QueueUrl=queue_url) + + +class TestCognitoCustomEmailSender: + @pytest.mark.timeout(240) + def test_sign_up_and_forgot_password_codes_decrypt_with_the_encryption_sdk( + self, cognito_client, sqs_client, sender_pool, decrypt + ): + pool_id = sender_pool["pool_id"] + client_id = sender_pool["client_id"] + cognito_client.sign_up( + ClientId=client_id, + Username="alice", + Password="Passw0rd!", + UserAttributes=[{"Name": "email", "Value": "alice@example.com"}], + ) + + event = _next_event(sqs_client, sender_pool["queue_url"]) + assert event["triggerSource"] == "CustomEmailSender_SignUp" + assert event["userPoolId"] == pool_id + assert event["userName"] == "alice" + assert event["callerContext"]["clientId"] == client_id + assert event["request"]["type"] == "customEmailSenderRequestV1" + assert event["request"]["userAttributes"]["email"] == "alice@example.com" + + code, context = decrypt(event["request"]["code"], sender_pool["key_arn"]) + assert context["userpool-id"] == pool_id + cognito_client.confirm_sign_up( + ClientId=client_id, Username="alice", ConfirmationCode=code + ) + + cognito_client.forgot_password(ClientId=client_id, Username="alice") + event = _next_event(sqs_client, sender_pool["queue_url"]) + assert event["triggerSource"] == "CustomEmailSender_ForgotPassword" + code, _ = decrypt(event["request"]["code"], sender_pool["key_arn"]) + cognito_client.confirm_forgot_password( + ClientId=client_id, + Username="alice", + ConfirmationCode=code, + Password="N3wPassw0rd!", + ) + + result = cognito_client.initiate_auth( + ClientId=client_id, + AuthFlow="USER_PASSWORD_AUTH", + AuthParameters={"USERNAME": "alice", "PASSWORD": "N3wPassw0rd!"}, + ) + assert result["AuthenticationResult"]["AccessToken"] diff --git a/docs/services/cognito.md b/docs/services/cognito.md index a17c761207..42964dc13c 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -520,6 +520,44 @@ empty list, matching AWS. It is enforced as if it had `ALLOW_REFRESH_TOKEN_AUTH` the stored or returned value. A client that signs in with `USER_PASSWORD_AUTH`, `ADMIN_USER_PASSWORD_AUTH` or `USER_AUTH` must list the matching `ALLOW_` value. +## Custom Email Sender Trigger + +A pool whose `LambdaConfig` names a `CustomEmailSender` function (`{"LambdaArn": ..., "LambdaVersion": "V1_0"}`) +and a `KMSKeyID` hands its email codes to that function instead of sending them through SES, as AWS +does. Floci invokes the function asynchronously (`InvocationType=Event`), as Cognito invokes custom +sender triggers, with the documented event: the common trigger parameters and a `request` with +`type` `customEmailSenderRequestV1`, `code`, `clientMetadata` and `userAttributes`. The CustomMessage +trigger does not fire for these messages, since Cognito sends no message for it to shape. + +`code` is encrypted the way Cognito encrypts it: a base64 AWS Encryption SDK message (algorithm suite +`0x0378`, signed with ECDSA P-384) whose data key comes from Floci KMS `GenerateDataKey` under the +pool's `KMSKeyID`, with the encryption context `userpool-id` set to the pool ID. A function decrypts +it with the AWS Encryption SDK and a KMS keyring pointed at Floci (`AWS_ENDPOINT_URL` reaches it from a +Floci Lambda container), with a commitment policy that allows decrypting it, `REQUIRE_ENCRYPT_ALLOW_DECRYPT`, +as in the [AWS example](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-email-sender.html#custom-email-sender-code-examples). + +| Trigger source | Sent by | +|---|---| +| `CustomEmailSender_SignUp` | `SignUp` | +| `CustomEmailSender_ResendCode` | `ResendConfirmationCode` | +| `CustomEmailSender_ForgotPassword` | `ForgotPassword` | +| `CustomEmailSender_UpdateUserAttribute` | `UpdateUserAttributes` changing `email` | +| `CustomEmailSender_VerifyUserAttribute` | `GetUserAttributeVerificationCode` for `email` | +| `CustomEmailSender_Authentication` | the `EMAIL_OTP` sign-in code of `USER_AUTH` and managed login | + +`userAttributes` includes `cognito:user_status`, and `clientMetadata` is the request's +`ClientMetadata`, or `null` when it carries none. A sign-in code's event carries none even when the +`InitiateAuth` does, as in the events Cognito sends. +`CreateUserPool` and `UpdateUserPool` refuse a custom sender trigger without a `KMSKeyID`, and +`CreateUserPool` a key that does not exist. A key that cannot encrypt fails the request, a sign-in +included, with `CodeDeliveryFailureException` ("Caller needs to enable the configured KMS Key" for a +disabled key, "Unable to encrypt CustomEmailSender/CustomSMSSender code using the configured KMS +Key" otherwise) and keeps a sign-up's user; a function that cannot be invoked fails it with +`UnexpectedLambdaException`. What the function does once invoked does not reach the caller. +`CustomEmailSender_AdminCreateUser` and `CustomEmailSender_AccountTakeOverNotification` are not +emulated, since Floci sends no invitations and has no threat protection, and neither is the +`CustomSMSSender` trigger: SMS codes still go through SNS. + ## User Attribute Update Verification `UpdateUserAttributes` and `AdminUpdateUserAttributes` delete attributes submitted with a blank value, including whitespace-only values. Deleting an email or phone number also removes its verified flag and pending value. Admin updates invalidate the matching pending verification code. diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java index e0ca1e75be..2da7c8b604 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java @@ -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 customMessage = fireCustomMessage(pool, client, user, "CustomMessage_Authentication", - Map.of()); + Map customMessage = customEmailSenderTakesOver(pool, deliveryMedium) ? Map.of() + : fireCustomMessage(pool, client, user, "CustomMessage_Authentication", Map.of()); Map 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 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 req = new HashMap<>(request); - if (user != null) { - Map 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 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 triggerEvent(UserPool pool, String clientId, CognitoUser user, String triggerKey, + String triggerSource, Map request) { + Map 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 req = new HashMap<>(request); + if (user != null) { + Map 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 clientMetadata) { + Map 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 clientMetadata, String triggerSource, List 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 customMessage = fireCustomMessage(pool, client, user, "CustomMessage_Authentication", - Map.of()); - Map parameters = new HashMap<>(service.issueMfaCode(pool, user, + Map customMessage = customEmailSenderTakesOver(pool, sms ? "SMS" : "EMAIL") ? Map.of() + : fireCustomMessage(pool, client, user, "CustomMessage_Authentication", Map.of()); + Map 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 diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java index 5ffe96cddc..455e223d77 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java @@ -1038,7 +1038,8 @@ public class CognitoJsonHandler { private Response handleResendConfirmationCode(JsonNode request) { Map 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 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 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 attrs = readNameValuePairs(request, "UserAttributes"); List> 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(); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index fdafb21af7..c18ed5e7bb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java @@ -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 poolStore, StorageBackend 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 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 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 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 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 resendConfirmationCode(String clientId, String username) { + return resendConfirmationCode(clientId, username, Map.of()); + } + + public Map resendConfirmationCode(String clientId, String username, + Map 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 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 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 forgotPassword(String clientId, String username) { + return forgotPassword(clientId, username, Map.of()); + } + + public Map forgotPassword(String clientId, String username, Map 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 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 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 getUserAttributeVerificationCode(String accessToken, String attributeName) { + return getUserAttributeVerificationCode(accessToken, attributeName, Map.of()); + } + + public Map getUserAttributeVerificationCode(String accessToken, String attributeName, + Map 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 getUserAttributeVerificationCodeUnderUserLock( - String poolId, String username, String attributeName) { + String poolId, String username, String clientId, String attributeName, Map 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> updateUserAttributes(String accessToken, Map attributes) { + return updateUserAttributes(accessToken, attributes, Map.of()); + } + + public List> updateUserAttributes(String accessToken, Map attributes, + Map 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> updateUserAttributesUnderUserLock( - String poolId, String username, Map attributes) { + String poolId, String username, String clientId, Map attributes, + Map 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 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 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 issueSignInOtp(UserPool pool, CognitoUser user, VerificationCode.Purpose purpose, - String attributeName, String deliveryMedium, Map customMessageResponse) { + Map issueSignInOtp(UserPool pool, UserPoolClient client, CognitoUser user, + VerificationCode.Purpose purpose, String attributeName, String deliveryMedium, + Map 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 issueMfaCode(UserPool pool, CognitoUser user, VerificationCode.Purpose purpose, - String attributeName, String deliveryMedium, + Map issueMfaCode(UserPool pool, UserPoolClient client, CognitoUser user, + VerificationCode.Purpose purpose, String attributeName, String deliveryMedium, Map 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; diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CustomSenderCodeEncryptor.java b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CustomSenderCodeEncryptor.java new file mode 100644 index 0000000000..53237d74bd --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CustomSenderCodeEncryptor.java @@ -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": }}, so a function decrypts it with the Encryption SDK's KMS + * keyring or master key provider exactly as it would on AWS. + * + *

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 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 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 sortedContext) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(bytes); + out.writeShort(sortedContext.size()); + for (Map.Entry 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); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomEmailSenderTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomEmailSenderTest.java new file mode 100644 index 0000000000..35e98ceb77 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomEmailSenderTest.java @@ -0,0 +1,551 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.config.TlsCertificateManager; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.acm.AcmService; +import io.github.hectorvent.floci.services.cognito.model.UserPool; +import io.github.hectorvent.floci.services.cognito.model.UserPoolClient; +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.VerificationCodeService; +import io.github.hectorvent.floci.services.kms.KmsService; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.lambda.model.InvocationType; +import io.github.hectorvent.floci.services.ses.SesService; +import io.github.hectorvent.floci.services.sns.SnsService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import javax.crypto.Cipher; +import javax.crypto.Mac; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.AlgorithmParameters; +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.Signature; +import java.security.spec.ECFieldFp; +import java.security.spec.ECGenParameterSpec; +import java.security.spec.ECParameterSpec; +import java.security.spec.ECPoint; +import java.security.spec.ECPublicKeySpec; +import java.time.Clock; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * The CustomEmailSender trigger: Cognito hands its email codes, encrypted under the pool's KMS key + * as AWS Encryption SDK messages, to a Lambda function instead of sending the email itself. + */ +class CognitoCustomEmailSenderTest { + private static final String REGION = "us-east-1"; + private static final String ACCOUNT_ID = "000000000000"; + private static final String SENDER = "arn:aws:lambda:us-east-1:000000000000:function:email-sender"; + private static final String CUSTOM_MESSAGE = "arn:aws:lambda:us-east-1:000000000000:function:custom-message"; + private static final List AUTH_FLOWS = List.of("ALLOW_USER_PASSWORD_AUTH", "ALLOW_USER_AUTH", + "ALLOW_REFRESH_TOKEN_AUTH"); + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private KmsService kms; + private String keyArn; + private LambdaService lambda; + private SesService ses; + private SnsService sns; + private CognitoService service; + + @BeforeEach + void setUp() { + RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT_ID); + StorageFactory storageFactory = new InMemoryStorageFactory(); + kms = new KmsService(storageFactory, regionResolver); + keyArn = kms.createKey("custom sender codes", REGION).getArn(); + lambda = mock(LambdaService.class); + ses = mock(SesService.class); + sns = mock(SnsService.class); + service = new CognitoService( + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + "http://localhost:4566", "cloudfront.net", regionResolver, lambda, mock(AcmService.class), + new VerificationCodeService(storageFactory, Clock.systemUTC()), + new CognitoMessageDispatcher(ses, sns, REGION), mock(TlsCertificateManager.class), + Clock.systemUTC(), true, new CustomSenderCodeEncryptor(kms)); + } + + @Test + @SuppressWarnings("unchecked") + void signUpHandsTheEncryptedCodeToTheFunctionInsteadOfSendingEmail() throws Exception { + UserPool pool = pool(Map.of("KMSKeyID", keyArn, "CustomEmailSender", sender(), + "CustomMessage", CUSTOM_MESSAGE), List.of("email")); + UserPoolClient client = client(pool); + + service.signUp(client.getClientId(), "alice", "Passw0rd!", Map.of("email", "alice@example.com"), Map.of(), Map.of()); + + Map event = senderEvent(); + assertEquals("1", event.get("version")); + assertEquals("CustomEmailSender_SignUp", event.get("triggerSource")); + assertEquals(REGION, event.get("region")); + assertEquals(pool.getId(), event.get("userPoolId")); + assertEquals("alice", event.get("userName")); + assertEquals(client.getClientId(), ((Map) event.get("callerContext")).get("clientId")); + Map request = (Map) event.get("request"); + assertEquals("customEmailSenderRequestV1", request.get("type")); + assertTrue(request.containsKey("clientMetadata")); + assertNull(request.get("clientMetadata")); + Map userAttributes = (Map) request.get("userAttributes"); + assertEquals("alice@example.com", userAttributes.get("email")); + assertEquals("UNCONFIRMED", userAttributes.get("cognito:user_status")); + + verify(ses, never()).sendEmail(any()); + verify(lambda, never()).invoke(anyString(), eq(CUSTOM_MESSAGE), any(byte[].class), any()); + + service.confirmSignUp(client.getClientId(), "alice", decrypt(request).plaintext()); + assertEquals("CONFIRMED", service.adminGetUser(pool.getId(), "alice").getUserStatus()); + } + + @Test + void theCodeIsAnEncryptionSdkMessageUnderThePoolKey() throws Exception { + UserPool pool = pool(Map.of("KMSKeyID", keyArn, "CustomEmailSender", sender()), List.of("email")); + UserPoolClient client = client(pool); + + service.signUp(client.getClientId(), "alice", "Passw0rd!", Map.of("email", "alice@example.com"), Map.of(), Map.of()); + + DecryptedMessage message = decrypt(request(senderEvent())); + assertEquals(0x0378, message.algorithmSuiteId()); + assertEquals("aws-kms", message.keyProviderId()); + assertEquals(keyArn, message.keyProviderInfo()); + assertEquals(pool.getId(), message.encryptionContext().get("userpool-id")); + assertTrue(message.encryptionContext().containsKey("aws-crypto-public-key")); + assertEquals(103, message.signatureLength()); + assertTrue(message.plaintext().matches("\\d{6}"), message.plaintext()); + } + + @Test + void resendAndForgotPasswordCodesNameTheirTriggerSources() throws Exception { + UserPool pool = pool(Map.of("KMSKeyID", keyArn, "CustomEmailSender", sender()), List.of("email")); + UserPoolClient client = client(pool); + service.signUp(client.getClientId(), "alice", "Passw0rd!", Map.of("email", "alice@example.com"), Map.of(), Map.of()); + + service.resendConfirmationCode(client.getClientId(), "alice"); + Map resent = senderEvent(); + assertEquals("CustomEmailSender_ResendCode", resent.get("triggerSource")); + service.confirmSignUp(client.getClientId(), "alice", decrypt(request(resent)).plaintext()); + + service.forgotPassword(client.getClientId(), "alice"); + Map forgot = senderEvent(); + assertEquals("CustomEmailSender_ForgotPassword", forgot.get("triggerSource")); + service.confirmForgotPassword(client.getClientId(), "alice", decrypt(request(forgot)).plaintext(), + "N3wPassw0rd!"); + assertNotNull(signIn(client, "alice", "N3wPassw0rd!")); + verify(ses, never()).sendEmail(any()); + } + + /** + * Measured (eu-west-1, 2026-10-20): SignUp, ResendConfirmationCode, ForgotPassword, + * GetUserAttributeVerificationCode and UpdateUserAttributes hand the function the request's + * ClientMetadata; a request without one gives it null (2026-10-16). + */ + @Test + void theRequestsClientMetadataReachesTheFunction() throws Exception { + UserPool pool = pool(Map.of("KMSKeyID", keyArn, "CustomEmailSender", sender()), List.of("email")); + UserPoolClient client = client(pool); + + service.signUp(client.getClientId(), "alice", "Passw0rd!", Map.of("email", "alice@example.com"), Map.of(), + Map.of("from", "SignUp")); + assertEquals(Map.of("from", "SignUp"), request(senderEvent()).get("clientMetadata")); + service.resendConfirmationCode(client.getClientId(), "alice", Map.of("from", "Resend")); + Map resent = senderEvent(); + assertEquals(Map.of("from", "Resend"), request(resent).get("clientMetadata")); + service.confirmSignUp(client.getClientId(), "alice", decrypt(request(resent)).plaintext()); + service.forgotPassword(client.getClientId(), "alice", Map.of("from", "ForgotPassword")); + assertEquals(Map.of("from", "ForgotPassword"), request(senderEvent()).get("clientMetadata")); + + service.getUserAttributeVerificationCode(signIn(client, "alice", "Passw0rd!"), "email", + Map.of("from", "GetUserAttributeVerificationCode")); + assertEquals(Map.of("from", "GetUserAttributeVerificationCode"), request(senderEvent()).get("clientMetadata")); + service.adminCreateUser(pool.getId(), "bob", Map.of("email", "bob@example.com"), null); + service.adminSetUserPassword(pool.getId(), "bob", "Passw0rd!", true); + service.updateUserAttributes(signIn(client, "bob", "Passw0rd!"), Map.of("email", "bob@example.org"), + Map.of("from", "UpdateUserAttributes")); + assertEquals(Map.of("from", "UpdateUserAttributes"), request(senderEvent()).get("clientMetadata")); + } + + @Test + @SuppressWarnings("unchecked") + void attributeVerificationCodesGoToTheFunction() throws Exception { + UserPool pool = pool(Map.of("KMSKeyID", keyArn, "CustomEmailSender", sender()), List.of()); + UserPoolClient client = client(pool); + for (String username : List.of("alice", "bob")) { + service.adminCreateUser(pool.getId(), username, Map.of("email", username + "@example.com"), null); + service.adminSetUserPassword(pool.getId(), username, "Passw0rd!", true); + } + + String aliceToken = signIn(client, "alice", "Passw0rd!"); + service.updateUserAttributes(aliceToken, Map.of("email", "alice@example.org")); + Map updated = senderEvent(); + assertEquals("CustomEmailSender_UpdateUserAttribute", updated.get("triggerSource")); + assertEquals(client.getClientId(), ((Map) updated.get("callerContext")).get("clientId")); + assertEquals("alice@example.org", + ((Map) request(updated).get("userAttributes")).get("email")); + service.verifyUserAttribute(aliceToken, "email", decrypt(request(updated)).plaintext()); + assertEquals("true", service.adminGetUser(pool.getId(), "alice").getAttributes().get("email_verified")); + + String bobToken = signIn(client, "bob", "Passw0rd!"); + service.getUserAttributeVerificationCode(bobToken, "email"); + Map verification = senderEvent(); + assertEquals("CustomEmailSender_VerifyUserAttribute", verification.get("triggerSource")); + assertEquals("bob", verification.get("userName")); + service.verifyUserAttribute(bobToken, "email", decrypt(request(verification)).plaintext()); + assertEquals("true", service.adminGetUser(pool.getId(), "bob").getAttributes().get("email_verified")); + verify(ses, never()).sendEmail(any()); + } + + @Test + @SuppressWarnings("unchecked") + void anEmailSignInCodeGoesToTheFunctionWithANullClientMetadata() throws Exception { + Map request = new HashMap<>(); + request.put("PoolName", "sender-pool"); + request.put("Policies", Map.of("SignInPolicy", + Map.of("AllowedFirstAuthFactors", List.of("PASSWORD", "EMAIL_OTP")))); + request.put("LambdaConfig", Map.of("KMSKeyID", keyArn, "CustomEmailSender", sender())); + UserPool pool = service.createUserPool(request, REGION); + UserPoolClient client = client(pool); + service.adminCreateUser(pool.getId(), "alice", + Map.of("email", "alice@example.com", "email_verified", "true"), null); + service.adminSetUserPassword(pool.getId(), "alice", "Passw0rd!", true); + + Map challenge = service.initiateAuth(client.getClientId(), "USER_AUTH", + Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "EMAIL_OTP"), Map.of("app", "web")); + assertEquals("EMAIL_OTP", challenge.get("ChallengeName")); + Map event = senderEvent(); + assertEquals("CustomEmailSender_Authentication", event.get("triggerSource")); + // Measured (eu-west-1, 2026-10-20): a sign-in code's event carries no ClientMetadata, though + // InitiateAuth sends one. + assertNull(request(event).get("clientMetadata")); + + Map result = service.respondToAuthChallenge(client.getClientId(), "EMAIL_OTP", + (String) challenge.get("Session"), + Map.of("USERNAME", "alice", "EMAIL_OTP_CODE", decrypt(request(event)).plaintext())); + assertNotNull(result.get("AuthenticationResult")); + verify(ses, never()).sendEmail(any()); + } + + @Test + void smsCodesStillGoThroughSns() { + UserPool pool = pool(Map.of("KMSKeyID", keyArn, "CustomEmailSender", sender()), List.of("phone_number")); + UserPoolClient client = client(pool); + + service.signUp(client.getClientId(), "alice", "Passw0rd!", Map.of("phone_number", "+15555550100"), Map.of(), Map.of()); + + verify(sns).publish(any(), any(), eq("+15555550100"), anyString(), any(), any(), eq(REGION)); + verify(lambda, never()).invoke(anyString(), anyString(), any(byte[].class), any()); + } + + /** + * Measured (eu-west-1, 2026-10-16): CreateUserPool and UpdateUserPool refuse a custom sender + * without a KMSKeyID, and CreateUserPool one whose key does not exist. + */ + @Test + void aCustomSenderNeedsAKmsKeyThatExists() { + AwsException noKey = assertThrows(AwsException.class, () -> pool(Map.of("CustomEmailSender", sender()), List.of("email"))); + assertEquals("InvalidParameterException", noKey.getErrorCode()); + assertEquals("KMSKeyId parameter is required when Custom SMS/Email Lambda trigger is used.", noKey.getMessage()); + + String missing = "arn:aws:kms:" + REGION + ":000000000000:key/00000000-0000-0000-0000-000000000000"; + AwsException missingKey = assertThrows(AwsException.class, + () -> pool(Map.of("KMSKeyID", missing, "CustomEmailSender", sender()), List.of("email"))); + assertEquals("InvalidParameterException", missingKey.getErrorCode()); + assertEquals("Encountered error when CreateGrant was attempted on the input KMS key - Key '" + missing + + "' does not exist", missingKey.getMessage()); + + UserPool pool = pool(Map.of(), List.of("email")); + AwsException update = assertThrows(AwsException.class, () -> service.updateUserPool( + Map.of("UserPoolId", pool.getId(), "LambdaConfig", Map.of("CustomEmailSender", sender())), REGION)); + assertEquals("KMSKeyId parameter is required when Custom SMS/Email Lambda trigger is used.", update.getMessage()); + verify(lambda, never()).invoke(anyString(), anyString(), any(byte[].class), any()); + } + + /** + * Measured: a disabled key fails the delivery, the sign-up kept and the sign-in code refused with + * the same CodeDeliveryFailureException; a key pending deletion with another message. + */ + @Test + void aKeyThatCannotEncryptFailsTheDeliveryAndKeepsTheSignUp() { + UserPool pool = pool(Map.of("KMSKeyID", keyArn, "CustomEmailSender", sender()), List.of("email")); + UserPoolClient client = client(pool); + kms.disableKey(keyArn, REGION); + + AwsException signUp = assertThrows(AwsException.class, () -> service.signUp(client.getClientId(), "alice", + "Passw0rd!", Map.of("email", "alice@example.com"), Map.of(), Map.of())); + assertEquals("CodeDeliveryFailureException", signUp.getErrorCode()); + assertEquals("Caller needs to enable the configured KMS Key", signUp.getMessage()); + assertNotNull(service.adminGetUser(pool.getId(), "alice")); + + Map request = new HashMap<>(); + request.put("PoolName", "sign-in-pool"); + request.put("Policies", Map.of("SignInPolicy", Map.of("AllowedFirstAuthFactors", List.of("PASSWORD", "EMAIL_OTP")))); + request.put("LambdaConfig", Map.of("KMSKeyID", keyArn, "CustomEmailSender", sender())); + UserPool signInPool = service.createUserPool(request, REGION); + UserPoolClient signInClient = client(signInPool); + service.adminCreateUser(signInPool.getId(), "bob", Map.of("email", "bob@example.com", "email_verified", "true"), null); + service.adminSetUserPassword(signInPool.getId(), "bob", "Passw0rd!", true); + AwsException signIn = assertThrows(AwsException.class, () -> service.initiateAuth(signInClient.getClientId(), + "USER_AUTH", Map.of("USERNAME", "bob", "PREFERRED_CHALLENGE", "EMAIL_OTP"), Map.of())); + assertEquals("CodeDeliveryFailureException", signIn.getErrorCode()); + assertEquals("Caller needs to enable the configured KMS Key", signIn.getMessage()); + + String pendingKey = kms.createKey("pending deletion", REGION).getArn(); + UserPool pendingPool = pool(Map.of("KMSKeyID", pendingKey, "CustomEmailSender", sender()), List.of("email")); + UserPoolClient pendingClient = client(pendingPool); + kms.scheduleKeyDeletion(pendingKey, 7, REGION); + AwsException pending = assertThrows(AwsException.class, () -> service.signUp(pendingClient.getClientId(), + "carol", "Passw0rd!", Map.of("email", "carol@example.com"), Map.of(), Map.of())); + assertEquals("CodeDeliveryFailureException", pending.getErrorCode()); + assertEquals("Unable to encrypt CustomEmailSender/CustomSMSSender code using the configured KMS Key", + pending.getMessage()); + verify(lambda, never()).invoke(anyString(), anyString(), any(byte[].class), any()); + } + + /** + * Measured (eu-west-1, 2026-10-20): Cognito hands out a code again at once, on a healthy pool + * and once a key that could not encrypt is enabled again. The code a failed delivery issued is + * withdrawn, so it does not hold back a resend, a password reset or an attribute code asked for + * right after, and each delivers a code that works. + */ + @Test + void anUndeliveredCodeDoesNotHoldBackTheNextOne() throws Exception { + UserPool pool = pool(Map.of("KMSKeyID", keyArn, "CustomEmailSender", sender()), List.of("email")); + UserPoolClient client = client(pool); + service.adminCreateUser(pool.getId(), "bob", Map.of("email", "bob@example.com", "email_verified", "true"), null); + service.adminSetUserPassword(pool.getId(), "bob", "Passw0rd!", true); + String bobToken = signIn(client, "bob", "Passw0rd!"); + kms.disableKey(keyArn, REGION); + assertThrows(AwsException.class, () -> service.signUp(client.getClientId(), "alice", "Passw0rd!", + Map.of("email", "alice@example.com"), Map.of(), Map.of())); + assertThrows(AwsException.class, () -> service.forgotPassword(client.getClientId(), "bob")); + assertThrows(AwsException.class, () -> service.getUserAttributeVerificationCode(bobToken, "email")); + kms.enableKey(keyArn, REGION); + + service.resendConfirmationCode(client.getClientId(), "alice"); + Map resent = senderEvent(); + assertEquals("CustomEmailSender_ResendCode", resent.get("triggerSource")); + service.confirmSignUp(client.getClientId(), "alice", decrypt(request(resent)).plaintext()); + service.forgotPassword(client.getClientId(), "bob"); + Map forgot = senderEvent(); + assertEquals("CustomEmailSender_ForgotPassword", forgot.get("triggerSource")); + service.confirmForgotPassword(client.getClientId(), "bob", decrypt(request(forgot)).plaintext(), "N3w-Passw0rd!"); + service.getUserAttributeVerificationCode(bobToken, "email"); + assertEquals("CustomEmailSender_VerifyUserAttribute", senderEvent().get("triggerSource")); + } + + @Test + void aFunctionThatCannotBeInvokedFailsTheDelivery() { + UserPool pool = pool(Map.of("KMSKeyID", keyArn, "CustomEmailSender", sender()), List.of()); + UserPoolClient client = client(pool); + service.adminCreateUser(pool.getId(), "alice", + Map.of("email", "alice@example.com", "email_verified", "true"), null); + when(lambda.invoke(anyString(), eq(SENDER), any(byte[].class), eq(InvocationType.Event))) + .thenThrow(new AwsException("ResourceNotFoundException", "Function not found: " + SENDER, 404)); + + // Measured: a function that is gone, or that Cognito may not invoke, answers this. + AwsException e = assertThrows(AwsException.class, + () -> service.forgotPassword(client.getClientId(), "alice")); + assertEquals("UnexpectedLambdaException", e.getErrorCode()); + assertEquals("CustomEmailSender invocation failed due to error AccessDeniedException.", e.getMessage()); + } + + private static Map sender() { + return Map.of("LambdaArn", SENDER, "LambdaVersion", "V1_0"); + } + + private UserPool pool(Map lambdaConfig, List autoVerifiedAttributes) { + Map request = new HashMap<>(); + request.put("PoolName", "sender-pool"); + request.put("AutoVerifiedAttributes", autoVerifiedAttributes); + request.put("LambdaConfig", lambdaConfig); + return service.createUserPool(request, REGION); + } + + private UserPoolClient client(UserPool pool) { + return service.createUserPoolClient(pool.getId(), "app", false, false, List.of(), List.of(), + null, List.of(), null, AUTH_FLOWS, null, null, List.of(), null, List.of(), null, + null, null, List.of(), null, null); + } + + @SuppressWarnings("unchecked") + private String signIn(UserPoolClient client, String username, String password) { + Map result = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", username, "PASSWORD", password)); + return (String) ((Map) result.get("AuthenticationResult")).get("AccessToken"); + } + + /** The event of the latest CustomEmailSender invocation, which must have been asynchronous. */ + private Map senderEvent() throws Exception { + ArgumentCaptor payload = ArgumentCaptor.forClass(byte[].class); + verify(lambda, atLeastOnce()) + .invoke(eq(REGION), eq(SENDER), payload.capture(), eq(InvocationType.Event)); + return MAPPER.readValue(payload.getValue(), new TypeReference<>() {}); + } + + @SuppressWarnings("unchecked") + private static Map request(Map event) { + return (Map) event.get("request"); + } + + private DecryptedMessage decrypt(Map request) throws Exception { + return EncryptionSdkReader.decrypt((String) request.get("code"), kms, REGION); + } + + record DecryptedMessage(int algorithmSuiteId, Map encryptionContext, String keyProviderId, + String keyProviderInfo, int signatureLength, String plaintext) {} + + /** + * Reads an AWS Encryption SDK message (format version 1, framed, suite 0x0378) the way the + * SDK's decrypt does: it unwraps the data key with KMS under the header's encryption context and + * checks the header tag, the frame tag and the ECDSA P-384 signature over the whole message. + */ + static final class EncryptionSdkReader { + private EncryptionSdkReader() {} + + static DecryptedMessage decrypt(String base64Message, KmsService kms, String region) throws Exception { + byte[] message = Base64.getDecoder().decode(base64Message); + ByteBuffer in = ByteBuffer.wrap(message); + assertEquals(1, in.get(), "version"); + assertEquals((byte) 0x80, in.get(), "type"); + int suiteId = Short.toUnsignedInt(in.getShort()); + byte[] messageId = bytes(in, 16); + int contextLength = Short.toUnsignedInt(in.getShort()); + int contextEnd = in.position() + contextLength; + Map context = new LinkedHashMap<>(); + for (int pairs = Short.toUnsignedInt(in.getShort()); pairs > 0; pairs--) { + context.put(text(in), text(in)); + } + assertEquals(contextEnd, in.position(), "encryption context length"); + assertEquals(1, in.getShort(), "encrypted data keys"); + String providerId = text(in); + String providerInfo = text(in); + byte[] encryptedDataKey = bytes(in, Short.toUnsignedInt(in.getShort())); + assertEquals(2, in.get(), "framed content"); + assertEquals(0, in.getInt(), "reserved"); + int ivLength = in.get(); + int frameLength = in.getInt(); + byte[] headerBody = Arrays.copyOf(message, in.position()); + byte[] headerIv = bytes(in, ivLength); + byte[] headerTag = bytes(in, 16); + + byte[] dataKey = kms.decrypt(encryptedDataKey, context, region); + SecretKeySpec key = deriveKey(dataKey, suiteId, messageId); + open(key, headerIv, headerBody, headerTag); + + assertEquals(0xFFFFFFFF, in.getInt(), "final frame"); + int sequenceNumber = in.getInt(); + byte[] frameIv = bytes(in, ivLength); + int contentLength = in.getInt(); + assertTrue(contentLength <= frameLength); + byte[] sealed = bytes(in, contentLength + 16); + byte[] frameAad = ByteBuffer.allocate(16 + 34 + 4 + 8) + .put(messageId) + .put("AWSKMSEncryptionClient Final Frame".getBytes(StandardCharsets.UTF_8)) + .putInt(sequenceNumber) + .putLong(contentLength) + .array(); + byte[] plaintext = open(key, frameIv, frameAad, sealed); + + byte[] signed = Arrays.copyOf(message, in.position()); + byte[] signature = bytes(in, Short.toUnsignedInt(in.getShort())); + assertFalse(in.hasRemaining(), "trailing bytes"); + Signature verifier = Signature.getInstance("SHA384withECDSA"); + verifier.initVerify(publicKey(context.get("aws-crypto-public-key"))); + verifier.update(signed); + assertTrue(verifier.verify(signature), "message signature"); + + return new DecryptedMessage(suiteId, context, providerId, providerInfo, signature.length, + new String(plaintext, StandardCharsets.UTF_8)); + } + + private static SecretKeySpec deriveKey(byte[] dataKey, int suiteId, byte[] messageId) throws Exception { + Mac mac = Mac.getInstance("HmacSHA384"); + mac.init(new SecretKeySpec(new byte[48], "HmacSHA384")); + byte[] pseudoRandomKey = mac.doFinal(dataKey); + mac.init(new SecretKeySpec(pseudoRandomKey, "HmacSHA384")); + mac.update(new byte[] {(byte) (suiteId >> 8), (byte) suiteId}); + mac.update(messageId); + mac.update((byte) 1); + return new SecretKeySpec(Arrays.copyOf(mac.doFinal(), 32), "AES"); + } + + private static byte[] open(SecretKeySpec key, byte[] iv, byte[] aad, byte[] sealed) throws Exception { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, iv)); + cipher.updateAAD(aad); + return cipher.doFinal(sealed); + } + + /** Decompresses the base64 P-384 point the SDK stores under {@code aws-crypto-public-key}. */ + private static PublicKey publicKey(String base64Point) throws Exception { + byte[] point = Base64.getDecoder().decode(base64Point); + AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC"); + parameters.init(new ECGenParameterSpec("secp384r1")); + ECParameterSpec spec = parameters.getParameterSpec(ECParameterSpec.class); + BigInteger p = ((ECFieldFp) spec.getCurve().getField()).getP(); + BigInteger x = new BigInteger(1, Arrays.copyOfRange(point, 1, point.length)); + BigInteger rhs = x.pow(3).add(spec.getCurve().getA().multiply(x)).add(spec.getCurve().getB()).mod(p); + BigInteger y = rhs.modPow(p.add(BigInteger.ONE).shiftRight(2), p); + if (y.testBit(0) != (point[0] == 0x03)) { + y = p.subtract(y); + } + return KeyFactory.getInstance("EC").generatePublic(new ECPublicKeySpec(new ECPoint(x, y), spec)); + } + + private static byte[] bytes(ByteBuffer in, int length) { + byte[] value = new byte[length]; + in.get(value); + return value; + } + + private static String text(ByteBuffer in) { + return new String(bytes(in, Short.toUnsignedInt(in.getShort())), StandardCharsets.UTF_8); + } + } + + private static final class InMemoryStorageFactory extends StorageFactory { + private InMemoryStorageFactory() { + super(null, null); + } + + @Override + public AccountAwareStorageBackend create(String serviceName, String fileName, + TypeReference> typeReference) { + return AccountAwareStorageBackend.inMemory(ACCOUNT_ID); + } + } +}