diff --git a/aws/provider.go b/aws/provider.go index 4ebd3e3d6ed..55cd29e842d 100644 --- a/aws/provider.go +++ b/aws/provider.go @@ -329,6 +329,7 @@ func Provider() terraform.ResourceProvider { "aws_cognito_user_pool": resourceAwsCognitoUserPool(), "aws_cognito_user_pool_client": resourceAwsCognitoUserPoolClient(), "aws_cognito_user_pool_domain": resourceAwsCognitoUserPoolDomain(), + "aws_cognito_resource_server": resourceAwsCognitoResourceServer(), "aws_cloudwatch_metric_alarm": resourceAwsCloudWatchMetricAlarm(), "aws_cloudwatch_dashboard": resourceAwsCloudWatchDashboard(), "aws_codedeploy_app": resourceAwsCodeDeployApp(), diff --git a/aws/resource_aws_cognito_resource_server.go b/aws/resource_aws_cognito_resource_server.go new file mode 100644 index 00000000000..5870d99847b --- /dev/null +++ b/aws/resource_aws_cognito_resource_server.go @@ -0,0 +1,211 @@ +package aws + +import ( + "fmt" + "log" + "strings" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" +) + +func resourceAwsCognitoResourceServer() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsCognitoResourceServerCreate, + Read: resourceAwsCognitoResourceServerRead, + Update: resourceAwsCognitoResourceServerUpdate, + Delete: resourceAwsCognitoResourceServerDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + // https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateResourceServer.html + Schema: map[string]*schema.Schema{ + "identifier": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "scope": { + Type: schema.TypeSet, + Optional: true, + MaxItems: 25, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "scope_description": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 256), + }, + "scope_name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateCognitoResourceServerScopeName, + }, + }, + }, + }, + "user_pool_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "scope_identifiers": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + } +} + +func resourceAwsCognitoResourceServerCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).cognitoidpconn + + identifier := d.Get("identifier").(string) + userPoolID := d.Get("user_pool_id").(string) + + params := &cognitoidentityprovider.CreateResourceServerInput{ + Identifier: aws.String(identifier), + Name: aws.String(d.Get("name").(string)), + UserPoolId: aws.String(userPoolID), + } + + if v, ok := d.GetOk("scope"); ok { + configs := v.(*schema.Set).List() + params.Scopes = expandCognitoResourceServerScope(configs) + } + + log.Printf("[DEBUG] Creating Cognito Resource Server: %s", params) + + _, err := conn.CreateResourceServer(params) + + if err != nil { + return fmt.Errorf("Error creating Cognito Resource Server: %s", err) + } + + d.SetId(fmt.Sprintf("%s|%s", userPoolID, identifier)) + + return resourceAwsCognitoResourceServerRead(d, meta) +} + +func resourceAwsCognitoResourceServerRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).cognitoidpconn + + userPoolID, identifier, err := decodeCognitoResourceServerID(d.Id()) + if err != nil { + return err + } + + params := &cognitoidentityprovider.DescribeResourceServerInput{ + Identifier: aws.String(identifier), + UserPoolId: aws.String(userPoolID), + } + + log.Printf("[DEBUG] Reading Cognito Resource Server: %s", params) + + resp, err := conn.DescribeResourceServer(params) + + if err != nil { + if isAWSErr(err, cognitoidentityprovider.ErrCodeResourceNotFoundException, "") { + log.Printf("[WARN] Cognito Resource Server %q not found, removing from state", d.Id()) + d.SetId("") + return nil + } + return err + } + + if resp == nil || resp.ResourceServer == nil { + log.Printf("[WARN] Cognito Resource Server %q not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + d.Set("identifier", resp.ResourceServer.Identifier) + d.Set("name", resp.ResourceServer.Name) + d.Set("user_pool_id", resp.ResourceServer.UserPoolId) + + scopes := flattenCognitoResourceServerScope(resp.ResourceServer.Scopes) + if err := d.Set("scope", scopes); err != nil { + return fmt.Errorf("Failed setting schema: %s", err) + } + + var scopeIdentifiers []string + for _, elem := range scopes { + + scopeIdentifier := fmt.Sprintf("%s/%s", aws.StringValue(resp.ResourceServer.Identifier), elem["scope_name"].(string)) + scopeIdentifiers = append(scopeIdentifiers, scopeIdentifier) + } + d.Set("scope_identifiers", scopeIdentifiers) + return nil +} + +func resourceAwsCognitoResourceServerUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).cognitoidpconn + + userPoolID, identifier, err := decodeCognitoResourceServerID(d.Id()) + if err != nil { + return err + } + + params := &cognitoidentityprovider.UpdateResourceServerInput{ + Identifier: aws.String(identifier), + Name: aws.String(d.Get("name").(string)), + Scopes: expandCognitoResourceServerScope(d.Get("scope").(*schema.Set).List()), + UserPoolId: aws.String(userPoolID), + } + + log.Printf("[DEBUG] Updating Cognito Resource Server: %s", params) + + _, err = conn.UpdateResourceServer(params) + if err != nil { + return fmt.Errorf("Error updating Cognito Resource Server: %s", err) + } + + return resourceAwsCognitoResourceServerRead(d, meta) +} + +func resourceAwsCognitoResourceServerDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).cognitoidpconn + + userPoolID, identifier, err := decodeCognitoResourceServerID(d.Id()) + if err != nil { + return err + } + + params := &cognitoidentityprovider.DeleteResourceServerInput{ + Identifier: aws.String(identifier), + UserPoolId: aws.String(userPoolID), + } + + log.Printf("[DEBUG] Deleting Resource Server: %s", params) + + _, err = conn.DeleteResourceServer(params) + + if err != nil { + if isAWSErr(err, cognitoidentityprovider.ErrCodeResourceNotFoundException, "") { + return nil + } + return fmt.Errorf("Error deleting Resource Server: %s", err) + } + + return nil +} + +func decodeCognitoResourceServerID(id string) (string, string, error) { + idParts := strings.Split(id, "|") + if len(idParts) != 2 { + return "", "", fmt.Errorf("expected ID in format UserPoolID|Identifier, received: %s", id) + } + return idParts[0], idParts[1], nil +} diff --git a/aws/resource_aws_cognito_resource_server_test.go b/aws/resource_aws_cognito_resource_server_test.go new file mode 100644 index 00000000000..fc70501bb97 --- /dev/null +++ b/aws/resource_aws_cognito_resource_server_test.go @@ -0,0 +1,226 @@ +package aws + +import ( + "errors" + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAWSCognitoResourceServer_basic(t *testing.T) { + var resourceServer cognitoidentityprovider.ResourceServerType + identifier := fmt.Sprintf("tf-acc-test-resource-server-id-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + name1 := fmt.Sprintf("tf-acc-test-resource-server-name-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + name2 := fmt.Sprintf("tf-acc-test-resource-server-name-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + poolName := fmt.Sprintf("tf-acc-test-pool-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + resourceName := "aws_cognito_resource_server.main" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCognitoResourceServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSCognitoResourceServerConfig_basic(identifier, name1, poolName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSCognitoResourceServerExists(resourceName, &resourceServer), + resource.TestCheckResourceAttr(resourceName, "identifier", identifier), + resource.TestCheckResourceAttr(resourceName, "name", name1), + resource.TestCheckResourceAttr(resourceName, "scope.#", "0"), + resource.TestCheckResourceAttr(resourceName, "scope_identifiers.#", "0"), + ), + }, + { + Config: testAccAWSCognitoResourceServerConfig_basic(identifier, name2, poolName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSCognitoResourceServerExists(resourceName, &resourceServer), + resource.TestCheckResourceAttr(resourceName, "identifier", identifier), + resource.TestCheckResourceAttr(resourceName, "name", name2), + resource.TestCheckResourceAttr(resourceName, "scope.#", "0"), + resource.TestCheckResourceAttr(resourceName, "scope_identifiers.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSCognitoResourceServer_scope(t *testing.T) { + var resourceServer cognitoidentityprovider.ResourceServerType + identifier := fmt.Sprintf("tf-acc-test-resource-server-id-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + name := fmt.Sprintf("tf-acc-test-resource-server-name-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + poolName := fmt.Sprintf("tf-acc-test-pool-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + resourceName := "aws_cognito_resource_server.main" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCognitoResourceServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSCognitoResourceServerConfig_scope(identifier, name, poolName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSCognitoResourceServerExists(resourceName, &resourceServer), + resource.TestCheckResourceAttr(resourceName, "scope.#", "2"), + resource.TestCheckResourceAttr(resourceName, "scope_identifiers.#", "2"), + ), + }, + { + Config: testAccAWSCognitoResourceServerConfig_scope_update(identifier, name, poolName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSCognitoResourceServerExists(resourceName, &resourceServer), + resource.TestCheckResourceAttr(resourceName, "scope.#", "1"), + resource.TestCheckResourceAttr(resourceName, "scope_identifiers.#", "1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + // Ensure we can remove scope completely + { + Config: testAccAWSCognitoResourceServerConfig_basic(identifier, name, poolName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSCognitoResourceServerExists(resourceName, &resourceServer), + resource.TestCheckResourceAttr(resourceName, "scope.#", "0"), + resource.TestCheckResourceAttr(resourceName, "scope_identifiers.#", "0"), + ), + }, + }, + }) +} + +func testAccCheckAWSCognitoResourceServerExists(n string, resourceServer *cognitoidentityprovider.ResourceServerType) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return errors.New("No Cognito Resource Server ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).cognitoidpconn + + userPoolID, identifier, err := decodeCognitoResourceServerID(rs.Primary.ID) + if err != nil { + return err + } + + output, err := conn.DescribeResourceServer(&cognitoidentityprovider.DescribeResourceServerInput{ + Identifier: aws.String(identifier), + UserPoolId: aws.String(userPoolID), + }) + + if err != nil { + return err + } + + if output == nil || output.ResourceServer == nil { + return fmt.Errorf("Cognito Resource Server %q information not found", rs.Primary.ID) + } + + *resourceServer = *output.ResourceServer + + return nil + } +} + +func testAccCheckAWSCognitoResourceServerDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).cognitoidpconn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_cognito_resource_server" { + continue + } + + userPoolID, identifier, err := decodeCognitoResourceServerID(rs.Primary.ID) + if err != nil { + return err + } + + _, err = conn.DescribeResourceServer(&cognitoidentityprovider.DescribeResourceServerInput{ + Identifier: aws.String(identifier), + UserPoolId: aws.String(userPoolID), + }) + + if err != nil { + if isAWSErr(err, cognitoidentityprovider.ErrCodeResourceNotFoundException, "") { + return nil + } + return err + } + } + + return nil +} + +func testAccAWSCognitoResourceServerConfig_basic(identifier string, name string, poolName string) string { + return fmt.Sprintf(` +resource "aws_cognito_resource_server" "main" { + identifier = "%s" + name = "%s" + user_pool_id = "${aws_cognito_user_pool.main.id}" +} + +resource "aws_cognito_user_pool" "main" { + name = "%s" +} +`, identifier, name, poolName) +} + +func testAccAWSCognitoResourceServerConfig_scope(identifier string, name string, poolName string) string { + return fmt.Sprintf(` +resource "aws_cognito_resource_server" "main" { + identifier = "%s" + name = "%s" + + scope = { + scope_name = "scope_1_name" + scope_description = "scope_1_description" + } + + scope = { + scope_name = "scope_2_name" + scope_description = "scope_2_description" + } + + user_pool_id = "${aws_cognito_user_pool.main.id}" +} + +resource "aws_cognito_user_pool" "main" { + name = "%s" +} +`, identifier, name, poolName) +} + +func testAccAWSCognitoResourceServerConfig_scope_update(identifier string, name string, poolName string) string { + return fmt.Sprintf(` +resource "aws_cognito_resource_server" "main" { + identifier = "%s" + name = "%s" + + scope = { + scope_name = "scope_1_name_updated" + scope_description = "scope_1_description" + } + + user_pool_id = "${aws_cognito_user_pool.main.id}" +} + +resource "aws_cognito_user_pool" "main" { + name = "%s" +} +`, identifier, name, poolName) +} diff --git a/aws/structure.go b/aws/structure.go index 80fc1e111aa..e9146613df8 100644 --- a/aws/structure.go +++ b/aws/structure.go @@ -2699,6 +2699,42 @@ func flattenCognitoUserPoolPasswordPolicy(s *cognitoidentityprovider.PasswordPol return []map[string]interface{}{} } +func expandCognitoResourceServerScope(inputs []interface{}) []*cognitoidentityprovider.ResourceServerScopeType { + configs := make([]*cognitoidentityprovider.ResourceServerScopeType, len(inputs), len(inputs)) + for i, input := range inputs { + param := input.(map[string]interface{}) + config := &cognitoidentityprovider.ResourceServerScopeType{} + + if v, ok := param["scope_description"]; ok { + config.ScopeDescription = aws.String(v.(string)) + } + + if v, ok := param["scope_name"]; ok { + config.ScopeName = aws.String(v.(string)) + } + + configs[i] = config + } + + return configs +} + +func flattenCognitoResourceServerScope(inputs []*cognitoidentityprovider.ResourceServerScopeType) []map[string]interface{} { + values := make([]map[string]interface{}, 0) + + for _, input := range inputs { + if input == nil { + continue + } + var value = map[string]interface{}{ + "scope_name": aws.StringValue(input.ScopeName), + "scope_description": aws.StringValue(input.ScopeDescription), + } + values = append(values, value) + } + return values +} + func expandCognitoUserPoolSchema(inputs []interface{}) []*cognitoidentityprovider.SchemaAttributeType { configs := make([]*cognitoidentityprovider.SchemaAttributeType, len(inputs), len(inputs)) diff --git a/aws/validators.go b/aws/validators.go index 3b41a98d1f8..2696fa2bc52 100644 --- a/aws/validators.go +++ b/aws/validators.go @@ -1386,6 +1386,21 @@ func validateCognitoUserPoolClientURL(v interface{}, k string) (ws []string, es return } +func validateCognitoResourceServerScopeName(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + + if len(value) < 1 { + errors = append(errors, fmt.Errorf("%q cannot be less than 1 character", k)) + } + if len(value) > 256 { + errors = append(errors, fmt.Errorf("%q cannot be longer than 256 character", k)) + } + if !regexp.MustCompile(`[\x21\x23-\x2E\x30-\x5B\x5D-\x7E]+`).MatchString(value) { + errors = append(errors, fmt.Errorf("%q must satisfy regular expression pattern: [\\x21\\x23-\\x2E\\x30-\\x5B\\x5D-\\x7E]+", k)) + } + return +} + func validateWafMetricName(v interface{}, k string) (ws []string, errors []error) { value := v.(string) if !regexp.MustCompile(`^[0-9A-Za-z]+$`).MatchString(value) { diff --git a/website/aws.erb b/website/aws.erb index e07a770c946..28da1a1b09e 100644 --- a/website/aws.erb +++ b/website/aws.erb @@ -629,6 +629,9 @@ > aws_cognito_identity_provider + > + aws_cognito_resource_server + > aws_cognito_user_group diff --git a/website/docs/r/cognito_resource_server.markdown b/website/docs/r/cognito_resource_server.markdown new file mode 100644 index 00000000000..57fb4ee52ad --- /dev/null +++ b/website/docs/r/cognito_resource_server.markdown @@ -0,0 +1,75 @@ +--- +layout: "aws" +page_title: "AWS: aws_cognito_resource_server" +side_bar_current: "docs-aws-resource-cognito-resource-server" +description: |- + Provides a Cognito Resource Server. +--- + +# aws_cognito_resource_server + +Provides a Cognito Resource Server. + +## Example Usage + +### Create a basic resource server + +```hcl +resource "aws_cognito_user_pool" "pool" { + name = "pool" +} + +resource "aws_cognito_resource_server" "resource" { + identifier = "https://example.com" + name = "example" + + user_pool_id = "${aws_cognito_user_pool.pool.id}" +} +``` + +### Create a resource server with sample-scope + +```hcl +resource "aws_cognito_user_pool" "pool" { + name = "pool" +} + +resource "aws_cognito_resource_server" "resource" { + identifier = "https://example.com" + name = "example" + + scope = [{ + scope_name = "sample-scope" + scope_description = "a Sample Scope Description" + }] + + user_pool_id = "${aws_cognito_user_pool.pool.id}" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `identifier` - (Required) An identifier for the resource server. +* `name` - (Required) A name for the resource server. +* `scope` - (Optional) A list of [Authorization Scope](#authorization_scope). + +### Authorization Scope + +* `scope_name` - (Required) The scope name. +* `scope_description` - (Required) The scope description. + +## Attribute Reference + +In addition to the arguments, which are exported, the following attributes are exported: + +* `scope_identifiers` - A list of all scopes configured for this resource server in the format identifier/scope_name. + +## Import + +`aws_cognito_resource_server` can be imported using their User Pool ID and Identifier, e.g. + +``` +$ terraform import aws_cognito_resource_server.example xxx_yyyyy|https://example.com +```