Skip to content

Commit

Permalink
resource/aws_cognito_resource_server: Address PR #4530 feedback
Browse files Browse the repository at this point in the history
  • Loading branch information
bflad committed May 31, 2018
1 parent 2f9470e commit 1ab680f
Show file tree
Hide file tree
Showing 6 changed files with 181 additions and 73 deletions.
89 changes: 61 additions & 28 deletions aws/resource_aws_cognito_resource_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ package aws
import (
"fmt"
"log"
"strings"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
)

func resourceAwsCognitoResourceServer() *schema.Resource {
Expand Down Expand Up @@ -42,17 +43,13 @@ func resourceAwsCognitoResourceServer() *schema.Resource {
"scope_description": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateCognitoResourceServerScopeDescription,
ValidateFunc: validation.StringLenBetween(1, 256),
},
"scope_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateCognitoResourceServerScopeName,
},
"scope_identifier": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
Expand All @@ -75,10 +72,13 @@ func resourceAwsCognitoResourceServer() *schema.Resource {
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(d.Get("identifier").(string)),
Identifier: aws.String(identifier),
Name: aws.String(d.Get("name").(string)),
UserPoolId: aws.String(d.Get("user_pool_id").(string)),
UserPoolId: aws.String(userPoolID),
}

if v, ok := d.GetOk("scope"); ok {
Expand All @@ -88,51 +88,62 @@ func resourceAwsCognitoResourceServerCreate(d *schema.ResourceData, meta interfa

log.Printf("[DEBUG] Creating Cognito Resource Server: %s", params)

resp, err := conn.CreateResourceServer(params)
_, err := conn.CreateResourceServer(params)

if err != nil {
return errwrap.Wrapf("Error creating Cognito Resource Server: {{err}}", err)
return fmt.Errorf("Error creating Cognito Resource Server: %s", err)
}

d.SetId(*resp.ResourceServer.Identifier)
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(d.Id()),
UserPoolId: aws.String(d.Get("user_pool_id").(string)),
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, "ResourceNotFoundException", "") {
log.Printf("[WARN] Cognito Resource Server %s is already gone", d.Id())
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
}

d.SetId(*resp.ResourceServer.Identifier)
d.Set("name", *resp.ResourceServer.Name)
d.Set("user_pool_id", *resp.ResourceServer.UserPoolId)
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.Identifier, resp.ResourceServer.Scopes)
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 := elem["scope_identifier"].(string)
scopeIdentifier := fmt.Sprintf("%s/%s", aws.StringValue(resp.ResourceServer.Identifier), elem["scope_name"].(string))
scopeIdentifiers = append(scopeIdentifiers, scopeIdentifier)
}
d.Set("scope_identifiers", scopeIdentifiers)
Expand All @@ -142,17 +153,23 @@ func resourceAwsCognitoResourceServerRead(d *schema.ResourceData, meta interface
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(d.Id()),
Identifier: aws.String(identifier),
Name: aws.String(d.Get("name").(string)),
UserPoolId: aws.String(d.Get("user_pool_id").(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)
_, err = conn.UpdateResourceServer(params)
if err != nil {
return errwrap.Wrapf("Error updating Cognito Resource Server: {{err}}", err)
return fmt.Errorf("Error updating Cognito Resource Server: %s", err)
}

return resourceAwsCognitoResourceServerRead(d, meta)
Expand All @@ -161,18 +178,34 @@ func resourceAwsCognitoResourceServerUpdate(d *schema.ResourceData, meta interfa
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(d.Id()),
UserPoolId: aws.String(d.Get("user_pool_id").(string)),
Identifier: aws.String(identifier),
UserPoolId: aws.String(userPoolID),
}

log.Printf("[DEBUG] Deleting Resource Server: %s", params)

_, err := conn.DeleteResourceServer(params)
_, err = conn.DeleteResourceServer(params)

if err != nil {
return errwrap.Wrapf("Error deleting Resource Server: {{err}}", err)
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
}
125 changes: 101 additions & 24 deletions aws/resource_aws_cognito_resource_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,53 +13,94 @@ import (
)

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))
name := fmt.Sprintf("tf-acc-test-resource-server-name-%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, name, poolName),
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("aws_cognito_resource_server.main"),
resource.TestCheckResourceAttr("aws_cognito_resource_server.main", "identifier", identifier),
resource.TestCheckResourceAttr("aws_cognito_resource_server.main", "name", name),
resource.TestCheckResourceAttr("aws_cognito_user_pool.main", "name", poolName),
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_full(t *testing.T) {
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_full(identifier, name, poolName),
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("aws_cognito_resource_server.main"),
resource.TestCheckResourceAttr("aws_cognito_resource_server.main", "identifier", identifier),
resource.TestCheckResourceAttr("aws_cognito_resource_server.main", "name", name),
resource.TestCheckResourceAttrSet("aws_cognito_resource_server.main", "scope_identifiers"),
resource.TestCheckResourceAttr("aws_cognito_user_pool.main", "name", poolName),
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) resource.TestCheckFunc {
func testAccCheckAWSCognitoResourceServerExists(n string, resourceServer *cognitoidentityprovider.ResourceServerType) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
Expand All @@ -72,15 +113,26 @@ func testAccCheckAWSCognitoResourceServerExists(n string) resource.TestCheckFunc

conn := testAccProvider.Meta().(*AWSClient).cognitoidpconn

_, err := conn.DescribeResourceServer(&cognitoidentityprovider.DescribeResourceServerInput{
Identifier: aws.String(rs.Primary.ID),
UserPoolId: aws.String(rs.Primary.Attributes["user_pool_id"]),
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
}
}
Expand All @@ -93,13 +145,18 @@ func testAccCheckAWSCognitoResourceServerDestroy(s *terraform.State) error {
continue
}

_, err := conn.DescribeResourceServer(&cognitoidentityprovider.DescribeResourceServerInput{
Identifier: aws.String(rs.Primary.ID),
UserPoolId: aws.String(rs.Primary.Attributes["user_pool_id"]),
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, "ResourceNotFoundException", "") {
if isAWSErr(err, cognitoidentityprovider.ErrCodeResourceNotFoundException, "") {
return nil
}
return err
Expand All @@ -123,19 +180,19 @@ resource "aws_cognito_user_pool" "main" {
`, identifier, name, poolName)
}

func testAccAWSCognitoResourceServerConfig_full(identifier string, name string, poolName string) string {
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_name = "scope_1_name"
scope_description = "scope_1_description"
}
scope = {
scope_name = "scope_2_name"
scope_name = "scope_2_name"
scope_description = "scope_2_description"
}
Expand All @@ -147,3 +204,23 @@ resource "aws_cognito_user_pool" "main" {
}
`, 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)
}
Loading

0 comments on commit 1ab680f

Please sign in to comment.