Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cognito): user pool: send emails using Amazon SES #17117

Merged
merged 10 commits into from Nov 15, 2021
65 changes: 58 additions & 7 deletions packages/@aws-cdk/aws-cognito/README.md
Expand Up @@ -314,11 +314,66 @@ new cognito.UserPool(this, 'UserPool', {
The default for account recovery is by phone if available and by email otherwise.
A user will not be allowed to reset their password via phone if they are also using it for MFA.


### Emails

Cognito sends emails to users in the user pool, when particular actions take place, such as welcome emails, invitation
emails, password resets, etc. The address from which these emails are sent can be configured on the user pool.
Read more about [email settings here](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-email.html).
Read more at [Email settings for User Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-email.html).

By default, user pools are configured to use Cognito's built in email capability, which by default will send emails
from `no-reply@verificationemail.com`. If you want to customize the from address, while still using the Cognito built-in
corymhall marked this conversation as resolved.
Show resolved Hide resolved
email capability, you can do so by specifying a custom email address that has been configured in Amazon SES.

```ts
new cognito.UserPool(this, 'myuserpool', {
email: Email.withCognito({
fromEmail: 'noreply@myawesomeapp.com',
replyTo: 'support@myawesomeapp.com',
}),
});
```

In the above example a custom email address is specified as `noreply@myawesomeapp.com`. In order for this to work
this email must be a verified email address in Amazon SES, and that email address must have an authorization policy
corymhall marked this conversation as resolved.
Show resolved Hide resolved
that allows Cognito to send emails. Read more at [Configuring Email for your User Pool](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-email.html#user-pool-email-configure).


For production applications it is recommended to configure your UserPool to send emails through Amazon SES. To do
so you must first have followed the steps in the [Cognito Developer Guide](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-email.html#user-pool-email-developer)
to verify an email address, move your account out of the SES sandbox, and grant Cognito email permissions via an
authorization policy.
nija-at marked this conversation as resolved.
Show resolved Hide resolved

Once the SES setup is complete, you can configure your UserPool to use the email configured in SES.

```ts
new cognito.UserPool(this, 'myuserpool', {
email: Email.withSES({
fromEmail: 'noreply@myawesomeapp.com',
fromName: 'Awesome App',
replyTo: 'support@myawesomeapp.com',
}),
});
```

Sending emails through SES requires that SES be configured in either `us-east-1`, `us-west-1`, or `eu-west-1`.
corymhall marked this conversation as resolved.
Show resolved Hide resolved
corymhall marked this conversation as resolved.
Show resolved Hide resolved
If your UserPool is being created in a different region you must specify which SES region to use.

```ts
new cognito.UserPool(this, 'myuserpool', {
email: Email.withSES({
sesRegion: SESRegion.US_EAST_1,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need an enum for this. Region is just a string in the cdk. We can just add a validation for the list of valid regions.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still show as an enum. README needs to be updated.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah sorry, should be fixed now.

fromEmail: 'noreply@myawesomeapp.com',
fromName: 'Awesome App',
replyTo: 'support@myawesomeapp.com',
corymhall marked this conversation as resolved.
Show resolved Hide resolved
}),
});

```

#### Emails (Legacy)
corymhall marked this conversation as resolved.
Show resolved Hide resolved

The legacy `emailSettings` can still be used for Cognito default settings.

```ts
new cognito.UserPool(this, 'myuserpool', {
Expand All @@ -330,13 +385,9 @@ new cognito.UserPool(this, 'myuserpool', {
});
```

By default, user pools are configured to use Cognito's built-in email capability, but it can also be configured to use
Amazon SES, however, support for Amazon SES is not available in the CDK yet. If you would like this to be implemented,
give [this issue](https://github.com/aws/aws-cdk/issues/6768) a +1. Until then, you can use the [cfn
layer](https://docs.aws.amazon.com/cdk/latest/guide/cfn_layer.html) to configure this.

If an email address contains non-ASCII characters, it will be encoded using the [punycode
encoding](https://en.wikipedia.org/wiki/Punycode) when generating the template for Cloudformation.
encoding](https://en.wikipedia.org/wiki/Punycode) when generating the template for CloudFormation.


### Device Tracking

Expand Down
263 changes: 259 additions & 4 deletions packages/@aws-cdk/aws-cognito/lib/user-pool.ts
Expand Up @@ -370,6 +370,239 @@ export interface PasswordPolicy {
readonly requireSymbols?: boolean;
}

/**
corymhall marked this conversation as resolved.
Show resolved Hide resolved
* Valid Amazon SES configuration regions
*/
export enum SESRegion {
/**
* Amazon SES region in 'us-east-1'
*/
US_EAST_1 = 'us-east-1',

/**
* Amazon SES region in 'us-west-2'
*/
US_WEST_2 = 'us-west-2',

/**
* Amazon SES region in 'eu-west-1'
*/
EU_WEST_1 = 'eu-west-1',
}

/**
* Configuration for Cognito sending emails via Amazon SES
*/
export interface SESOptions {
/**
* The verified Amazon SES email address that Cognito should
* use to send emails.
*
* The email address used must be a verified email address
* in Amazon SES and must be configured to allow Cognito to
* send emails.
*
* https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-email.html
*/
readonly fromEmail: string;

/**
* An optional name that should be used as the sender's name
* along with the email.
*
* @default - no name
*/
readonly fromName?: string;

/**
* The destination to which the receiver of the email should reploy to.
*
* @default - same as the fromEmail
*/
readonly replyTo?: string;

/**
* The name of a configuration set in SES that should
* be applied to emails sent via Cognito.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* The name of a configuration set in SES that should
* be applied to emails sent via Cognito.
* The name of a configuration set in Amazon SES that should
* be applied to emails sent via Cognito.
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-emailconfiguration.html#cfn-cognito-userpool-emailconfiguration-configurationset

*
* @default - no configuration set
*/
readonly configurationSetName?: string;

/**
* Required if the UserPool region is different than the SES region.
*
* If sending emails with a Amazon SES verified email address,
* and the region that SES is configured is different than the
* region in which the UserPool is deployed, you must specify that
* region here.
*
* @default - The same region as the Cognito UserPool
*/
readonly sesRegion?: SESRegion;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens if this property is not specified and the region is not the expected SES region?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

then it will throw an error telling the user to provide this property.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"it" here being CloudFormation deployment?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have validation logic to validate that a correct region is is provided and the library will throw an error if it is not a valid region.

https://github.com/aws/aws-cdk/pull/17117/files#diff-46f225425155cdae9873139ac778b85e5312e63ed690512df01a449a9f45c1a6R195

}

/**
* Configuration settings for Cognito default email
*/
export interface CognitoEmailOptions {
/**
* The verified email address in Amazon SES that
* Cognito will use to send emails. You must have already
* configured Amazon SES to allow Cognito to send Emails
* through this address.
*
* https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-email.html
*
* @default - Cognito default email address will be used
* 'no-reply@verificationemail.com'
*/
readonly fromEmail?: string;

/**
* The destination to which the receiver of the email should reploy to.
*
* @default - same as the fromEmail
*/
readonly replyTo?: string;

/**
* Required if the UserPool region is different than the SES region.
*
* If sending emails with a Amazon SES verified email address,
* and the region that SES is configured is different than the
* region in which the UserPool is deployed, you must specify that
* region here.
*
* @default - The same region as the Cognito UserPool
*/
readonly sesRegion?: SESRegion;
}

/**
* Configuration for Cognito email settings
*/
export interface EmailConfiguration {
/**
* UserPool CFN configuration for email configuration
*/
readonly emailConfig: CfnUserPool.EmailConfigurationProperty;
corymhall marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* Configure how Cognito sends emails
*/
export abstract class Email {
/**
* Send email using Cognito
*/
public static withCognito(options?: CognitoEmailOptions): Email {
return new CognitoEmail(options);
}

/**
* Send email using SES
*/
public static withSES(options: SESOptions): Email {
return new SESEmail(options);
}

/**
* The valid Amazon SES configuration regions
*/
protected readonly regions = ['us-east-1', 'us-west-2', 'eu-west-1'];
corymhall marked this conversation as resolved.
Show resolved Hide resolved

/**
* Returns the email configuration for a Cognito UserPool
* that controls how Cognito will send emails
*/
public abstract bind(scope: Construct): EmailConfiguration;

}

class CognitoEmail extends Email {
constructor(private readonly options?: CognitoEmailOptions) {
super();
}

public bind(scope: Construct): EmailConfiguration {
const region = Stack.of(scope).region;

// if a custom email is provided that means that cognito is going to use an SES email
// and we need to provide the sourceArn which requires a valid region
let sourceArn: string | undefined = undefined;
if (this.options?.fromEmail) {
if (this.options.fromEmail != 'no-reply@verificationemail.com') {
corymhall marked this conversation as resolved.
Show resolved Hide resolved
if (Token.isUnresolved(region) && !this.options.sesRegion) {
throw new Error('Your stack region cannot be determined so "sesRegion" is required in CognitoEmailOptions');
}
if (this.options?.sesRegion && !this.regions.includes(this.options.sesRegion)) {
throw new Error(`sesRegion must be one of 'us-east-1', 'us-west-2', 'eu-west-1'. received ${this.options.sesRegion}`);
} else if (!this.options?.sesRegion && !this.regions.includes(region)) {
throw new Error(`Your stack is in ${region}, which is not a SES Region. Please provide a valid value for 'sesRegion'`);
}
sourceArn = Stack.of(scope).formatArn({
service: 'ses',
resource: 'identity',
resourceName: encodeAndTest(this.options.fromEmail),
region: this.options.sesRegion ?? region,
});
}
}


return {
emailConfig: {
replyToEmailAddress: encodeAndTest(this.options?.replyTo),
emailSendingAccount: 'COGNITO_DEFAULT',
sourceArn,
},
};

}
}

class SESEmail extends Email {
constructor(private readonly options: SESOptions) {
super();
}

public bind(scope: Construct): EmailConfiguration {
const region = Stack.of(scope).region;

if (Token.isUnresolved(region) && !this.options.sesRegion) {
throw new Error('Your stack region cannot be determined so "sesRegion" is required in SESOptions');
}

if (this.options.sesRegion && !this.regions.includes(this.options.sesRegion)) {
throw new Error(`sesRegion must be one of 'us-east-1', 'us-west-2', 'eu-west-1'. received ${this.options.sesRegion}`);
} else if (!this.options.sesRegion && !this.regions.includes(region)) {
throw new Error(`Your stack is in ${region}, which is not a SES Region. Please provide a valid value for 'sesRegion'`);
}

let from = this.options.fromEmail;
if (this.options.fromName) {
from = `${this.options.fromName} <${this.options.fromEmail}>`;
}

return {
emailConfig: {
from: encodeAndTest(from),
replyToEmailAddress: encodeAndTest(this.options.replyTo),
configurationSet: this.options.configurationSetName,
emailSendingAccount: 'DEVELOPER',
sourceArn: Stack.of(scope).formatArn({
service: 'ses',
resource: 'identity',
resourceName: encodeAndTest(this.options.fromEmail),
region: this.options.sesRegion ?? region,
}),
},
};
}
}


/**
* Email settings for the user pool.
*/
Expand Down Expand Up @@ -574,6 +807,12 @@ export interface UserPoolProps {
*/
readonly emailSettings?: EmailSettings;

/**
* Email settings for a user pool.
* @default - cognito will use the default email configuration
*/
readonly email?: Email;

/**
* Lambda functions to use for supported Cognito triggers.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html
Expand Down Expand Up @@ -788,6 +1027,14 @@ export class UserPool extends UserPoolBase {

const passwordPolicy = this.configurePasswordPolicy(props);

if (props.email && props.emailSettings) {
throw new Error('you must either provide "email" or "emailSettings", but not both');
}
const emailConfiguration = props.email ? props.email.bind(this).emailConfig : undefinedIfNoKeys({
from: encodePuny(props.emailSettings?.from),
replyToEmailAddress: encodePuny(props.emailSettings?.replyTo),
});

const userPool = new CfnUserPool(this, 'Resource', {
userPoolName: props.userPoolName,
usernameAttributes: signIn.usernameAttrs,
Expand All @@ -805,10 +1052,7 @@ export class UserPool extends UserPoolBase {
mfaConfiguration: props.mfa,
enabledMfas: this.mfaConfiguration(props),
policies: passwordPolicy !== undefined ? { passwordPolicy } : undefined,
emailConfiguration: undefinedIfNoKeys({
from: encodePuny(props.emailSettings?.from),
replyToEmailAddress: encodePuny(props.emailSettings?.replyTo),
}),
emailConfiguration,
usernameConfiguration: undefinedIfNoKeys({
caseSensitive: props.signInCaseSensitive,
}),
Expand Down Expand Up @@ -1111,6 +1355,17 @@ export class UserPool extends UserPoolBase {
}
}

function encodeAndTest(input: string | undefined): string | undefined {
if (input) {
const local = input.split('@')[0];
if (!/[\p{ASCII}]+/u.test(local)) {
throw new Error('the local part of the email address must use ASCII characters only');
}
return punycodeEncode(input);
} else {
return undefined;
}
}
function undefinedIfNoKeys(struct: object): object | undefined {
const allUndefined = Object.values(struct).every(val => val === undefined);
return allUndefined ? undefined : struct;
Expand Down