Skip to content

Latest commit

 

History

History
888 lines (548 loc) · 41.8 KB

README.md

File metadata and controls

888 lines (548 loc) · 41.8 KB

Build Status GitHub tag (latest SemVer) Terraform Version AWS Provider Version Join Slack

terraform-aws-cognito-user-pool

A Terraform module for deploying and managing Cognito User Pools on Amazon Web Services (AWS).

*This module supports Terraform v1.x, v0.15, v0.14, v0.13 as well as v0.12.20 and above and is compatible with the Terraform AWS provider v3.50 and above.

Module Features

In contrast to the plain cognito_user_pool resource this module has a more secure level of default settings.

While all settings can be customized as needed, best practices are pre-configured.

  • Default Security Settings: Per default, only administrators are allowed to create user profiles by setting allow_admin_create_user_only to true. This module comes with a strong default password policy.

Standard Cognito Features: Create a Cognito User Pool with pre-configured best practices. Create Cognito User Pool Clients. Create a Cognito User Pool Domain. Create Cognito User Pool Resource Servers as associated scopes.

Getting Started

Most basic usage just setting required arguments:

module "terraform-aws-cognito-user-pool" {
  source  = "mineiros-io/cognito-user-pool/aws"
  version = "~> 0.9.0"

  name = "application-userpool"
}

Advanced usage as found in examples/complete/main.tf setting all required and optional arguments to their default values.

Module Argument Reference

See variables.tf and examples/ for details and use-cases.

Top-level Arguments

Module Configuration

  • module_enabled: (Optional bool)

    Specifies whether resources in the module will be created.

    Default is true.

  • module_tags: (Optional map(string))

    A map of tags that will be applied to all created resources that accept tags. Tags defined with 'module_tags' can be overwritten by resource-specific tags.

    Default is {}.

    Example:

    module_tags = {
      environment = "staging"
      team        = "platform"
    }
  • module_depends_on: (Optional list(dependency))

    A list of dependencies. Any object can be assigned to this list to define a hidden external dependency.

    Example:

    module_depends_on = [
      aws_vpc.vpc
    ]

Cognito User Pool

  • name: (Required string)

    The name of the user pool. Forces new resource.

  • advanced_security_mode: (Optional string)

    The mode for advanced security, must be one of OFF, AUDIT or ENFORCED. Additional pricing applies for Amazon Cognito advanced security features. For details see https://aws.amazon.com/cognito/pricing/.

    Default is "OFF".

  • alias_attributes: (Optional set(string))

    Attributes supported as an alias for this user pool. Possible values: phone_number, email, or preferred_username. Conflicts with username_attributes. Default applies if username_attributes is not set.

  • username_attributes: (Optional set(string))

    Specifies whether email addresse or phone_number can be specified as usernames when a user signs up. Conflicts with alias_attributes. Default is to use alias_attributes.

  • allow_admin_create_user_only: (Optional bool)

    Set to True if only the administrator is allowed to create user profiles. Set to False if users can sign themselves up via an app.

    Default is true.

  • invite_email_subject: (Optional string)

    The message template for email messages.

    Default is "Your new account.".

  • invite_email_message: (Optional string)

    The message template for email messages. Must contain {username} and {####} placeholders, for username and temporary password, respectively.

    Default is "Your username is {username} and your temporary password is ' {####}'".

  • invite_sms_message: (Optional string)

    The message template for SMS messages. Must contain {username} and {####} placeholders, for username and temporary password, respectively.

    Default is "Your username is {username} and your temporary password is ' {####}'.".

  • auto_verified_attributes: (Optional set(string))

    The attributes to be auto-verified. Possible values: email, phone_number.

    Default is ["email"].

  • user_device_tracking: (Optional string)

    Configure tracking of user devices. Set to OFF to disable tracking, ALWAYS to track all devices or USER_OPT_IN to only track when user opts in.

    Default is "USER_OPT_IN".

  • challenge_required_on_new_device: (Optional bool)

    Indicates whether a challenge is required on a new device. Only applicable to a new device. Only applied when user_device_tracking is enabled.

    Default is true.

  • enable_username_case_sensitivity: (Optional bool)

    Specifies whether username case sensitivity will be applied to all users in the user pool through Cognito APIs.

    Default is false.

  • email_sending_account: (Optional string)

    The email delivery method to use. COGNITO_DEFAULT for the default email functionality built into Cognito or DEVELOPER to use your Amazon SES configuration.

    Default is "COGNITO_DEFAULT".

  • email_reply_to_address: (Optional string)

    The REPLY-TO email address.

  • email_source_arn: (Optional string)

    The ARN of the email source.

  • email_from_address: (Optional string)

    Sender’s email address or sender’s name with their email address (e.g. '[email protected]' or 'John Smith [email protected]').

  • mfa_configuration: (Optional string)

    Multi-Factor Authentication (MFA) configuration for the User Pool. Valid values: ON, OFF or OPTIONAL. ON and OPTIONAL require at least one of sms_configuration or software_token_mfa_configuration to be configured.

    Default is "OPTIONAL".

  • password_minimum_length: (Optional number)

    The minimum length of the password policy that you have set.

    Default is 20.

  • password_require_lowercase: (Optional bool)

    Whether you have required users to use at least one lowercase letter in their password.

    Default is true.

  • password_require_numbers: (Optional bool)

    Whether you have required users to use at least one number in their password.

    Default is true.

  • password_require_symbols: (Optional bool)

    Whether you have required users to use at least one symbol in their password.

    Default is true.

  • password_require_uppercase: (Optional bool)

    Whether you have required users to use at least one uppercase letter in their password.

    Default is true.

  • temporary_password_validity_days: (Optional number)

    In the password policy you have set, refers to the number of days a temporary password is valid. If the user does not sign in during this time, their password will need to be reset by an administrator.

    Default is 1.

  • allow_software_mfa_token: (Optional bool)

    Boolean whether to enable software token Multi-Factor Authentication (MFA) tokens, such as Time-Based One-Time Password (TOTP). To disable software token MFA when sms_configuration is not present, the mfa_configuration argument must be set to OFF and the software_token_mfa_configuration configuration block must be fully removed.

    Default is true.

  • sms_authentication_message: (Optional string)

    A string representing the SMS authentication message. The message must contain the {####} placeholder, which will be replaced with the authentication code.

    Default is "Your temporary password is {####}.".

  • lambda_create_auth_challenge: (Optional string)

    The ARN of an AWS Lambda creating an authentication challenge.

  • lambda_custom_message: (Optional string)

    The ARN of a custom message AWS Lambda trigger.

  • lambda_define_auth_challenge: (Optional string)

    The ARN of an AWS Lambda that defines the authentication challenge.

  • lambda_post_authentication: (Optional string)

    The ARN of an AWS Lambda that defines the authentication challenge.

  • lambda_post_confirmation: (Optional string)

    The ARN of a post-confirmation AWS Lambda trigger.

  • lambda_pre_authentication: (Optional string)

    The ARN of a pre-authentication AWS Lambda trigger.

  • lambda_pre_sign_up: (Optional string)

    The ARN of a pre-registration AWS Lambda trigger.

  • lambda_pre_token_generation: (Optional string)

    The ARN of an AWS Lambda that allows customization of identity token claims before token generation.

  • lambda_user_migration: (Optional string)

    The ARN of he user migration AWS Lambda config type.

  • lambda_verify_auth_challenge_response: (Optional string)

    The ARN of an AWS Lambda that verifies the authentication challenge response.

    Default is "true".

  • schema_attributes: (Optional list(schema_attribute))

    A list of schema attributes of a user pool. You can add a maximum of 25 custom attributes. Please note that only default attributes can be marked as required. Also an attribute cannot be switched between required and not required after a user pool has been created. For details please see the attributes docs.

    Default is [].

    Example:

    schema_attributes = [
      {
        name = "gender", # overwrites the default attribute 'gender'
        type = "String"
        required = true  # required can only be set for default attributes
      },
      {
        name       = "alternative_name"
        type       = "String"
        min_length = 0,
        max_length = 2048
      },
      {
        name      = "friends_count"
        type      = "Number"
        min_value = 0,
        max_value = 100
      },
      {
        name = "is_active"
        type = "Boolean"
      },
      {
        name = "last_seen"
        type = "DateTime"
      }
    ]
  • account_recovery_mechanisms: (Optional list(account_recovery_mechanism))

    A list of recovery_mechanisms to be inserted inside account_recovery_setting.

    Default is [].

    Example:

    account_recovery_mechanisms = [
      {
        name     = "verified_email"
        priority = 1
      },
      {
        name     = "verified_phone_number"
        priority = 2
      }
    ]

    Each account_recovery_mechanism object in the list accepts the following attributes:

    • name: (Required string)

      Recovery method for a user. Can be of the following: verified_email, verified_phone_number, and admin_only.

    • priority: (Required string)

      Positive integer specifying priority of a method with 1 being the highest priority.

  • sms_configuration: (Optional object(sms_configuration))

    The sms_configuration with the external_id parameter used in IAM role trust relationships and the sns_caller_arn parameter to set the ARN of the Amazon SNS caller. This is usually the IAM role that you have given AWS Cognito permission to assume.

    The sms_configuration object accepts the following attributes:

    • external_id: (Required string)

      External ID used in IAM role trust relationships.

    • sns_caller_arn: (Required string)

      ARN of the Amazon SNS caller. This is usually the IAM role that you've given Cognito permission to assume.

  • default_email_option: (Optional string)

    The default email option. Must be either CONFIRM_WITH_CODE or CONFIRM_WITH_LINK.

    Default is "CONFIRM_WITH_CODE".

  • email_message: (Optional string)

    The email message template. Must contain the {####} placeholder.

    Default is "Your verification code is {####}.".

  • email_message_by_link: (Optional string)

    The email message template for sending a confirmation link to the user, it must contain the {##Any Text##} placeholder.

    Default is "Please click the link below to verify your email address.{##Verify Email##}.".

  • email_subject: (Optional string)

    The subject line for the email message template.

    Default is "Your Verification Code".

  • email_subject_by_link: (Optional string)

    The subject line for the email message template for sending a confirmation link to the user.

    Default is "Your Verifiction Link".

  • sms_message: (Optional string)

    The SMS message template. Must contain the {####} placeholder, which will be replaced with the verification code. Can also contain the {username} placeholder which will be replaced with the username.

    Default is "Your verification code is {####}.".

  • tags: (Optional map(string))

    A mapping of tags to assign to the resource.

    Default is {}.

    Example:

    tags  = {
      CreatedAt = "2020-02-07",
      Alice     = "Bob"
    }

Cognito User Pool Domain

  • domain: (Optional string)

    The domain name that should be used. Can be set to a FQDN or prefix. If no FQDN and certificate_arn are set, the domain prefix will be used for the sign-up and sign-in pages that are hosted by Amazon Cognito, e.g. https://{YOUR_PREFIX}.auth.eu-west-1.amazoncognito.com. The prefix must be unique across the selected AWS Region. Domain names can only contain lower-case letters, numbers, and hyphens.

  • certificate_arn: (Optional string)

    The ARN of an ISSUED ACM certificate in us-east-1 for a custom domain.

Cognito User Pool Resource Servers

  • resource_servers: (Optional list(resource_server))

    A list of objects with resource server declarations.

    Default is [].

    Example:

    resource_servers = [
      {
        identifier = "https://api.resourceserver.com"
        name       = "API"
        scopes     = [
          {
            scope_name = "users:read"
            scope_description = "Read user data"
          },
          {
            scope_name = "users:write"
            scope_description = "Write user data"
          }
        ]
      }
    ]

    Each resource_server object in the list accepts the following attributes:

    • identifier: (Required string)

      An identifier for the resource server.

    • name: (Required string)

      A name for the resource server.

    • scope: (Optional list(scope))

      A list of Authorization Scope.

      Each scope object in the list accepts the following attributes:

Cognito User Pool Clients

  • clients: (Optional list(client))

    A list of objects with the clients definitions.

    Default is [].

    Example:

    clients = [
      {
        name                 = "android-mobile-client"
        read_attributes      = ["email", "email_verified", "preferred_username"]
        allowed_oauth_scopes = ["email", "openid"]
        allowed_oauth_flows  = ["implicit"]
        callback_urls        = ["https://mineiros.io/callback", "https://mineiros.io/anothercallback"]
        default_redirect_uri = "https://mineiros.io/callback"
        generate_secret      = true
      }
    ]

    Each client object in the list accepts the following attributes:

    • name: (Required string)

      Name of the application client.

    • user_pool_id: (Optional string)

      Name of the application client.

    • access_token_validity: (Optional number)

      Time limit, between 5 minutes and 1 day, after which the access token is no longer valid and cannot be used. This value will be overridden if you have entered a value in token_validity_units.

    • allowed_oauth_flows_user_pool_client: (Optional bool)

      Whether the client is allowed to follow the OAuth protocol when interacting with Cognito user pools.

    • allowed_oauth_flows: (Optional set(string))

      List of allowed OAuth flows (code, implicit, client_credentials).

    • allowed_oauth_scopes: (Optional set(string))

      List of allowed OAuth scopes (phone, email, openid, profile, and aws.cognito.signin.user.admin).

    • analytics_configuration: (Optional object(analytics_configuration))

      Configuration block for Amazon Pinpoint analytics for collecting metrics for this user pool.

      The analytics_configuration object accepts the following attributes:

      • application_arn: (Optional string)

        Application ARN for an Amazon Pinpoint application. Conflicts with external_id and role_arn.

      • application_id: (Optional string)

        Application ID for an Amazon Pinpoint application.

      • external_id: (Optional string)

        ID for the Analytics Configuration. Conflicts with application_arn. Application ID for an Amazon Pinpoint application.

      • role_arn: (Optional string)

        ARN of an IAM role that authorizes Amazon Cognito to publish events to Amazon Pinpoint analytics. Conflicts with application_arn.

      • user_data_shared: (Optional bool)

        If set to true, Amazon Cognito will include user data in the events it publishes to Amazon Pinpoint analytics.

    • callback_urls: (Optional set(string))

      List of allowed callback URLs for the identity providers.

    • default_redirect_uri: (Optional string)

      Default redirect URI. Must be in the list of callback URLs.

    • enable_token_revocation: (Optional bool)

      Enables or disables token revocation.

    • explicit_auth_flows: (Optional set(string))

      List of authentication flows (ADMIN_NO_SRP_AUTH, CUSTOM_AUTH_FLOW_ONLY, USER_PASSWORD_AUTH, ALLOW_ADMIN_USER_PASSWORD_AUTH, ALLOW_CUSTOM_AUTH, ALLOW_USER_PASSWORD_AUTH, ALLOW_USER_SRP_AUTH, ALLOW_REFRESH_TOKEN_AUTH).

    • generate_secret: (Optional bool)

      Should an application secret be generated.

    • id_token_validity: (Optional number)

      Time limit, between 5 minutes and 1 day, after which the ID token is no longer valid and cannot be used. This value will be overridden if you have entered a value in token_validity_units.

    • logout_urls: (Optional set(string))

      List of allowed logout URLs for the identity providers.

    • prevent_user_existence_errors: (Optional string)

      Choose which errors and responses are returned by Cognito APIs during authentication, account confirmation, and password recovery when the user does not exist in the user pool. When set to ENABLED and the user does not exist, authentication returns an error indicating either the username or password was incorrect, and account confirmation and password recovery return a response indicating a code was sent to a simulated destination. When set to LEGACY, those APIs will return a UserNotFoundException exception if the user does not exist in the user pool.

    • read_attributes: (Optional set(string))

      List of user pool attributes the application client can read from.

    • refresh_token_validity: (Optional number)

      Time limit in days refresh tokens are valid for.

    • supported_identity_providers: (Optional set(string))

      List of provider names for the identity providers that are supported on this client. Uses the provider_name attribute of aws_cognito_identity_provider resource(s), or the equivalent string(s).

    • token_validity_units: (Optional object(token_validity_units))

      Configuration block for units in which the validity times are represented in.

      The token_validity_units object accepts the following attributes:

      • access_token: (Optional string)

        Time unit in for the value in access_token_validity, defaults to hours.

        Default is "hours".

      • id_token: (Optional string)

        Time unit in for the value in id_token_validity, defaults to hours.

        Default is "hours".

      • refresh_token: (Optional string)

        Time unit in for the value in refresh_token_validity, defaults to days.

        Default is "days".

    • write_attributes: (Optional set(string))

      List of user pool attributes the application client can write to.

Cognito User Pool Clients Default Values

The following variables can be used for setting default settings among various clients defined through the clients variable. This helps you to quickly issue several clients that implement the same settings, e.g. like so:

clients = [
  { name = "ios" },
  { name = "android" },
  { name = "web" },
]

default_client_read_attributes        = ["email", "email_verified", "preferred_username"]
default_client_allowed_oauth_scopes   = ["email", "openid"]
default_client_allowed_oauth_flows    = ["implicit"]
default_client_callback_urls          = ["https://mineiros.io/callback", "https://mineiros.io/anothercallback"]
default_client_default_redirect_uri   = "https://mineiros.io/callback"
default_client_generate_secret        = true
default_client_refresh_token_validity = 45

default_client_supported_identity_providers         = null
default_client_logout_urls                          = null
default_client_allowed_oauth_flows_user_pool_client = null
default_client_write_attributes                     = null
default_client_explicit_auth_flows                  = null
default_client_prevent_user_existence_errors        = null
default_client_access_token_validity                = null
default_client_id_token_validity                    = null
default_client_token_validity_units                 = null
default_client_enable_token_revocation              = null
  • default_client_callback_urls: (Optional list(string))

    List of allowed callback URLs for the identity providers.

  • default_client_default_redirect_uri: (Optional string)

    The default redirect URI. Must be in the list of callback URLs.

  • default_client_read_attributes: (Optional list(string))

    List of Cognito User Pool attributes the application client can read from.

  • default_client_refresh_token_validity: (Optional number)

    The time limit in days refresh tokens are valid for.

    Default is 30.

  • default_client_supported_identity_providers: (Optional list(string))

    List of provider names for the identity providers that are supported on this client.

  • default_client_allowed_oauth_scopes: (Optional list(string))

    List of allowed OAuth scopes. Possible values are phone, email, openid, profile, and aws.cognito.signin.user.admin.

  • default_client_logout_urls: (Optional list(string))

    List of allowed logout URLs for the identity providers.

  • default_client_allowed_oauth_flows_user_pool_client: (Optional bool)

    Whether the client is allowed to follow the OAuth protocol when interacting with Cognito User Pools.

  • default_client_generate_secret: (Optional bool)

    Boolean flag for generating an application secret.

  • default_client_allowed_oauth_flows: (Optional list(string))

    List of allowed OAuth flows. Possible flows are code, implicit, and client_credentials.

  • default_client_write_attributes: (Optional list(string))

    List of Cognito User Pool attributes the application client can write to.

  • default_client_explicit_auth_flows: (Optional list(string))

    List of authentication flows. Possible values are ADMIN_NO_SRP_AUTH, CUSTOM_AUTH_FLOW_ONLY, USER_PASSWORD_AUTH, ALLOW_ADMIN_USER_PASSWORD_AUTH, ALLOW_CUSTOM_AUTH, ALLOW_USER_PASSWORD_AUTH, ALLOW_USER_SRP_AUTH, and ALLOW_REFRESH_TOKEN_AUTH.

  • default_client_prevent_user_existence_errors: (Optional string)

    Choose which errors and responses are returned by Cognito APIs during authentication, account confirmation, and password recovery when the user does not exist in the Cognito User Pool. When set to ENABLED and the user does not exist, authentication returns an error indicating either the username or password was incorrect, and account confirmation and password recovery return a response indicating a code was sent to a simulated destination. When set to LEGACY, those APIs will return a UserNotFoundException exception if the user does not exist in the Cognito User Pool.

  • default_client_access_token_validity: (Optional number)

    Time limit, between 5 minutes and 1 day, after which the access token is no longer valid and cannot be used. This value will be overridden if you have entered a value in 'default_client_token_validity_units'.

  • default_client_id_token_validity: (Optional number)

    Time limit, between 5 minutes and 1 day, after which the ID token is no longer valid and cannot be used. This value will be overridden if you have entered a value in 'default_client_token_validity_units'.

  • default_client_token_validity_units: (Optional number)

    Configuration block for units in which the validity times are represented in.

  • default_client_enable_token_revocation: (Optional bool)

    Enables or disables token revocation.

Module Outputs

The following attributes are exported by the module:

  • user_pool: (object(user_pool))

    The cognito_user_pool object.

  • domain: (object(domain))

    The full aws_cognito_user_pool object.

  • clients: (map(client))

    A map of cognito_user_pool_client objects. The map is keyed by the name of the created clients. Client secrets are filtered out of this map and are available through the client_secrets output variable and flagged as sensitive.

  • client_secrets: (map(client_secret))

    A sensitive map of client secrets for all created cognito_user_pool_client resources. The map is keyed by the name of the created clients.

  • module_enabled: (bool)

    Whether this module is enabled.

External Documentation

AWS Documentation

Terraform AWS Provider Documentation

Module Versioning

This Module follows the principles of Semantic Versioning (SemVer).

Given a version number MAJOR.MINOR.PATCH, we increment the:

  1. MAJOR version when we make incompatible changes,
  2. MINOR version when we add functionality in a backwards compatible manner, and
  3. PATCH version when we make backwards compatible bug fixes.

Backwards compatibility in 0.0.z and 0.y.z version

  • Backwards compatibility in versions 0.0.z is not guaranteed when z is increased. (Initial development)
  • Backwards compatibility in versions 0.y.z is not guaranteed when y is increased. (Pre-release)

About Mineiros

Mineiros is a remote-first company headquartered in Berlin, Germany that solves development, automation and security challenges in cloud infrastructure.

Our vision is to massively reduce time and overhead for teams to manage and deploy production-grade and secure cloud infrastructure.

We offer commercial support for all of our modules and encourage you to reach out if you have any questions or need help. Feel free to email us at [email protected] or join our Community Slack channel.

Reporting Issues

We use GitHub Issues to track community reported issues and missing features.

Contributing

Contributions are always encouraged and welcome! For the process of accepting changes, we use Pull Requests. If you'd like more information, please see our Contribution Guidelines.

Makefile Targets

This repository comes with a handy Makefile. Run make help to see details on each available target.

License

license

This module is licensed under the Apache License Version 2.0, January 2004. Please see LICENSE for full details.

Copyright © 2020-2022 Mineiros GmbH