Skip to content

Commit

Permalink
feat(cognito): user pool: send emails using Amazon SES (aws#17117)
Browse files Browse the repository at this point in the history
add support for SES integration by introducing a new property for
configuring email settings for a user pool. This feature supports both
types of integration with SES.

1. Using the COGNITO_DEFAULT sending account, but providing a custom
   email address
2. Using the DEVELOPER sending account

This feature does not automate any configuration on SES since that is
not currently possible with CloudFormation and requires a manual
verification step. To use the SES integration introduced in this feature
the user will have had to already configured a verified email address in
Amazon SES and followed the steps outlined here:
https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-email.html

closes aws#6768

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
  • Loading branch information
corymhall authored and mpvosseller committed Nov 16, 2021
1 parent 610215d commit 977b10f
Show file tree
Hide file tree
Showing 5 changed files with 539 additions and 16 deletions.
48 changes: 37 additions & 11 deletions packages/@aws-cdk/aws-cognito/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -314,29 +314,55 @@ 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 will send emails
from `no-reply@verificationemail.com`. If you want to use a custom email address you can configure
Cognito to send emails through Amazon SES, which is detailed below.

```ts
new cognito.UserPool(this, 'myuserpool', {
// ...
emailSettings: {
from: 'noreply@myawesomeapp.com',
email: UserPoolEmail.withCognito('support@myawesomeapp.com'),
});
```

For typical production environments, the default email limit is below the required delivery volume.
To enable a higher delivery volume, you can configure the UserPool to send emails through Amazon SES. To do
so, follow 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 the account out of the SES sandbox, and grant Cognito email permissions via an
authorization policy.

Once the SES setup is complete, the UserPool can be configured to use the SES email.

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

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.
Sending emails through SES requires that SES be configured (as described above) in one of the regions - `us-east-1`, `us-west-1`, or `eu-west-1`.
If the UserPool is being created in a different region, `sesRegion` must be used to specify the correct SES region.

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

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.
```

### Device Tracking

Expand Down
1 change: 1 addition & 0 deletions packages/@aws-cdk/aws-cognito/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export * from './user-pool';
export * from './user-pool-attr';
export * from './user-pool-client';
export * from './user-pool-domain';
export * from './user-pool-email';
export * from './user-pool-idp';
export * from './user-pool-idps';
export * from './user-pool-resource-server';
203 changes: 203 additions & 0 deletions packages/@aws-cdk/aws-cognito/lib/user-pool-email.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
import { Stack, Token } from '@aws-cdk/core';
import { Construct } from 'constructs';
import { toASCII as punycodeEncode } from 'punycode/';

/**
* The valid Amazon SES configuration regions
*/
const REGIONS = ['us-east-1', 'us-west-2', 'eu-west-1'];

/**
* Configuration for Cognito sending emails via Amazon SES
*/
export interface UserPoolSESOptions {
/**
* 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.
*
* @see 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 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.
*
* Must be 'us-east-1', 'us-west-2', or 'eu-west-1'
*
* @default - The same region as the Cognito UserPool
*/
readonly sesRegion?: string;
}

/**
* Result of binding email settings with a user pool
*/
interface UserPoolEmailConfig {
/**
* The name of the configuration set in SES.
*
* @default - none
*/
readonly configurationSet?: string;

/**
* Specifies whether to use Cognito's built in email functionality
* or SES.
*
* @default - Cognito built in email functionality
*/
readonly emailSendingAccount?: string;

/**
* Identifies either the sender's email address or the sender's
* name with their email address.
*
* If emailSendingAccount is DEVELOPER then this cannot be specified.
*
* @default 'no-reply@verificationemail.com'
*/
readonly from?: string;

/**
* The destination to which the receiver of the email should reply to.
*
* @default - same as `from`
*/
readonly replyToEmailAddress?: string;

/**
* The ARN of a verified email address in Amazon SES.
*
* required if emailSendingAccount is DEVELOPER or if
* 'from' is provided.
*
* @default - none
*/
readonly sourceArn?: string;
}

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

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


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

}

class CognitoEmail extends UserPoolEmail {
constructor(private readonly replyTo?: string) {
super();
}

public _bind(_scope: Construct): UserPoolEmailConfig {
return {
replyToEmailAddress: encodeAndTest(this.replyTo),
emailSendingAccount: 'COGNITO_DEFAULT',
};

}
}

class SESEmail extends UserPoolEmail {
constructor(private readonly options: UserPoolSESOptions) {
super();
}

public _bind(scope: Construct): UserPoolEmailConfig {
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 && !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 && !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 {
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,
}),
};
}
}

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;
}
}
22 changes: 18 additions & 4 deletions packages/@aws-cdk/aws-cognito/lib/user-pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { StandardAttributeNames } from './private/attr-names';
import { ICustomAttribute, StandardAttribute, StandardAttributes } from './user-pool-attr';
import { UserPoolClient, UserPoolClientOptions } from './user-pool-client';
import { UserPoolDomain, UserPoolDomainOptions } from './user-pool-domain';
import { UserPoolEmail } from './user-pool-email';
import { IUserPoolIdentityProvider } from './user-pool-idp';
import { UserPoolResourceServer, UserPoolResourceServerOptions } from './user-pool-resource-server';

Expand Down Expand Up @@ -570,10 +571,18 @@ export interface UserPoolProps {

/**
* Email settings for a user pool.
*
* @default - see defaults on each property of EmailSettings.
* @deprecated Use 'email' instead.
*/
readonly emailSettings?: EmailSettings;

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

/**
* 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 +797,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) : 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 +822,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
Loading

0 comments on commit 977b10f

Please sign in to comment.