diff --git a/builtin/providers/aws/provider.go b/builtin/providers/aws/provider.go index 3b4771813aae..f7869a9cf604 100644 --- a/builtin/providers/aws/provider.go +++ b/builtin/providers/aws/provider.go @@ -115,6 +115,7 @@ func Provider() terraform.ResourceProvider { "aws_ami_copy": resourceAwsAmiCopy(), "aws_ami_from_instance": resourceAwsAmiFromInstance(), "aws_api_gateway_api_key": resourceAwsApiGatewayApiKey(), + "aws_api_gateway_authorizer": resourceAwsApiGatewayAuthorizer(), "aws_api_gateway_deployment": resourceAwsApiGatewayDeployment(), "aws_api_gateway_integration": resourceAwsApiGatewayIntegration(), "aws_api_gateway_integration_response": resourceAwsApiGatewayIntegrationResponse(), diff --git a/builtin/providers/aws/resource_aws_api_gateway_authorizer.go b/builtin/providers/aws/resource_aws_api_gateway_authorizer.go new file mode 100644 index 000000000000..6b005181381b --- /dev/null +++ b/builtin/providers/aws/resource_aws_api_gateway_authorizer.go @@ -0,0 +1,207 @@ +package aws + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/apigateway" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceAwsApiGatewayAuthorizer() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsApiGatewayAuthorizerCreate, + Read: resourceAwsApiGatewayAuthorizerRead, + Update: resourceAwsApiGatewayAuthorizerUpdate, + Delete: resourceAwsApiGatewayAuthorizerDelete, + + Schema: map[string]*schema.Schema{ + "authorizer_uri": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + "identity_source": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Default: "method.request.header.Authorization", + }, + "name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + "rest_api_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Default: "TOKEN", + }, + "authorizer_credentials": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "authorizer_result_ttl_in_seconds": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validateIntegerInRange(0, 3600), + }, + "identity_validation_expression": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + }, + } +} + +func resourceAwsApiGatewayAuthorizerCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).apigateway + + input := apigateway.CreateAuthorizerInput{ + AuthorizerUri: aws.String(d.Get("authorizer_uri").(string)), + IdentitySource: aws.String(d.Get("identity_source").(string)), + Name: aws.String(d.Get("name").(string)), + RestApiId: aws.String(d.Get("rest_api_id").(string)), + Type: aws.String(d.Get("type").(string)), + } + + if v, ok := d.GetOk("authorizer_credentials"); ok { + input.AuthorizerCredentials = aws.String(v.(string)) + } + if v, ok := d.GetOk("authorizer_result_ttl_in_seconds"); ok { + input.AuthorizerResultTtlInSeconds = aws.Int64(int64(v.(int))) + } + if v, ok := d.GetOk("identity_validation_expression"); ok { + input.IdentityValidationExpression = aws.String(v.(string)) + } + + log.Printf("[INFO] Creating API Gateway Authorizer: %s", input) + out, err := conn.CreateAuthorizer(&input) + if err != nil { + return fmt.Errorf("Error creating API Gateway Authorizer: %s", err) + } + + d.SetId(*out.Id) + + return resourceAwsApiGatewayAuthorizerRead(d, meta) +} + +func resourceAwsApiGatewayAuthorizerRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).apigateway + + log.Printf("[INFO] Reading API Gateway Authorizer %s", d.Id()) + input := apigateway.GetAuthorizerInput{ + AuthorizerId: aws.String(d.Id()), + RestApiId: aws.String(d.Get("rest_api_id").(string)), + } + + authorizer, err := conn.GetAuthorizer(&input) + if err != nil { + if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NotFoundException" { + log.Printf("[WARN] No API Gateway Authorizer found: %s", input) + d.SetId("") + return nil + } + return err + } + log.Printf("[DEBUG] Received API Gateway Authorizer: %s", authorizer) + + d.Set("authorizer_credentials", authorizer.AuthorizerCredentials) + d.Set("authorizer_result_ttl_in_seconds", authorizer.AuthorizerResultTtlInSeconds) + d.Set("authorizer_uri", authorizer.AuthorizerUri) + d.Set("identity_source", authorizer.IdentitySource) + d.Set("identity_validation_expression", authorizer.IdentityValidationExpression) + d.Set("name", authorizer.Name) + d.Set("type", authorizer.Type) + + return nil +} + +func resourceAwsApiGatewayAuthorizerUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).apigateway + + input := apigateway.UpdateAuthorizerInput{ + AuthorizerId: aws.String(d.Id()), + RestApiId: aws.String(d.Get("rest_api_id").(string)), + } + + operations := make([]*apigateway.PatchOperation, 0) + + if d.HasChange("authorizer_uri") { + operations = append(operations, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String("/authorizerUri"), + Value: aws.String(d.Get("authorizer_uri").(string)), + }) + } + if d.HasChange("identity_source") { + operations = append(operations, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String("/identitySource"), + Value: aws.String(d.Get("identity_source").(string)), + }) + } + if d.HasChange("name") { + operations = append(operations, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String("/name"), + Value: aws.String(d.Get("name").(string)), + }) + } + if d.HasChange("type") { + operations = append(operations, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String("/type"), + Value: aws.String(d.Get("type").(string)), + }) + } + if d.HasChange("authorizer_credentials") { + operations = append(operations, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String("/authorizerCredentials"), + Value: aws.String(d.Get("authorizer_credentials").(string)), + }) + } + if d.HasChange("authorizer_result_ttl_in_seconds") { + operations = append(operations, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String("/authorizerResultTtlInSeconds"), + Value: aws.String(fmt.Sprintf("%d", d.Get("authorizer_result_ttl_in_seconds").(int))), + }) + } + if d.HasChange("identity_validation_expression") { + operations = append(operations, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String("/identityValidationExpression"), + Value: aws.String(d.Get("identity_validation_expression").(string)), + }) + } + input.PatchOperations = operations + + log.Printf("[INFO] Updating API Gateway Authorizer: %s", input) + _, err := conn.UpdateAuthorizer(&input) + if err != nil { + return fmt.Errorf("Updating API Gateway Authorizer failed: %s", err) + } + + return resourceAwsApiGatewayAuthorizerRead(d, meta) +} + +func resourceAwsApiGatewayAuthorizerDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).apigateway + input := apigateway.DeleteAuthorizerInput{ + AuthorizerId: aws.String(d.Id()), + RestApiId: aws.String(d.Get("rest_api_id").(string)), + } + log.Printf("[INFO] Deleting API Gateway Authorizer: %s", input) + _, err := conn.DeleteAuthorizer(&input) + if err != nil { + return fmt.Errorf("Deleting API Gateway Authorizer failed: %s", err) + } + + return nil +} diff --git a/builtin/providers/aws/resource_aws_api_gateway_authorizer_test.go b/builtin/providers/aws/resource_aws_api_gateway_authorizer_test.go new file mode 100644 index 000000000000..3eb89e636fce --- /dev/null +++ b/builtin/providers/aws/resource_aws_api_gateway_authorizer_test.go @@ -0,0 +1,319 @@ +package aws + +import ( + "fmt" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/apigateway" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAWSAPIGatewayAuthorizer_basic(t *testing.T) { + var conf apigateway.Authorizer + + expectedAuthUri := regexp.MustCompile("arn:aws:apigateway:region:lambda:path/2015-03-31/functions/" + + "arn:aws:lambda:[a-z0-9-]+:[0-9]{12}:function:tf_acc_api_gateway_authorizer/invocations") + expectedCreds := regexp.MustCompile("arn:aws:iam::[0-9]{12}:role/tf_acc_api_gateway_auth_invocation_role") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayAuthorizerDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccAWSAPIGatewayAuthorizerConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayAuthorizerExists("aws_api_gateway_authorizer.test", &conf), + testAccCheckAWSAPIGatewayAuthorizerAuthorizerUri(&conf, expectedAuthUri), + resource.TestMatchResourceAttr("aws_api_gateway_authorizer.test", "authorizer_uri", expectedAuthUri), + testAccCheckAWSAPIGatewayAuthorizerIdentitySource(&conf, "method.request.header.Authorization"), + resource.TestCheckResourceAttr("aws_api_gateway_authorizer.test", "identity_source", "method.request.header.Authorization"), + testAccCheckAWSAPIGatewayAuthorizerName(&conf, "tf-acc-test-authorizer"), + resource.TestCheckResourceAttr("aws_api_gateway_authorizer.test", "name", "tf-acc-test-authorizer"), + testAccCheckAWSAPIGatewayAuthorizerType(&conf, "TOKEN"), + resource.TestCheckResourceAttr("aws_api_gateway_authorizer.test", "type", "TOKEN"), + testAccCheckAWSAPIGatewayAuthorizerAuthorizerCredentials(&conf, expectedCreds), + resource.TestMatchResourceAttr("aws_api_gateway_authorizer.test", "authorizer_credentials", expectedCreds), + testAccCheckAWSAPIGatewayAuthorizerAuthorizerResultTtlInSeconds(&conf, nil), + resource.TestCheckResourceAttr("aws_api_gateway_authorizer.test", "authorizer_result_ttl_in_seconds", "0"), + testAccCheckAWSAPIGatewayAuthorizerIdentityValidationExpression(&conf, nil), + resource.TestCheckResourceAttr("aws_api_gateway_authorizer.test", "identity_validation_expression", ""), + ), + }, + resource.TestStep{ + Config: testAccAWSAPIGatewayAuthorizerUpdatedConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayAuthorizerExists("aws_api_gateway_authorizer.test", &conf), + testAccCheckAWSAPIGatewayAuthorizerAuthorizerUri(&conf, expectedAuthUri), + resource.TestMatchResourceAttr("aws_api_gateway_authorizer.test", "authorizer_uri", expectedAuthUri), + testAccCheckAWSAPIGatewayAuthorizerIdentitySource(&conf, "method.request.header.Authorization"), + resource.TestCheckResourceAttr("aws_api_gateway_authorizer.test", "identity_source", "method.request.header.Authorization"), + testAccCheckAWSAPIGatewayAuthorizerName(&conf, "tf-acc-test-authorizer_modified"), + resource.TestCheckResourceAttr("aws_api_gateway_authorizer.test", "name", "tf-acc-test-authorizer_modified"), + testAccCheckAWSAPIGatewayAuthorizerType(&conf, "TOKEN"), + resource.TestCheckResourceAttr("aws_api_gateway_authorizer.test", "type", "TOKEN"), + testAccCheckAWSAPIGatewayAuthorizerAuthorizerCredentials(&conf, expectedCreds), + resource.TestMatchResourceAttr("aws_api_gateway_authorizer.test", "authorizer_credentials", expectedCreds), + testAccCheckAWSAPIGatewayAuthorizerAuthorizerResultTtlInSeconds(&conf, aws.Int64(360)), + resource.TestCheckResourceAttr("aws_api_gateway_authorizer.test", "authorizer_result_ttl_in_seconds", "360"), + testAccCheckAWSAPIGatewayAuthorizerIdentityValidationExpression(&conf, aws.String(".*")), + resource.TestCheckResourceAttr("aws_api_gateway_authorizer.test", "identity_validation_expression", ".*"), + ), + }, + }, + }) +} + +func testAccCheckAWSAPIGatewayAuthorizerAuthorizerUri(conf *apigateway.Authorizer, expectedUri *regexp.Regexp) resource.TestCheckFunc { + return func(s *terraform.State) error { + if conf.AuthorizerUri == nil { + return fmt.Errorf("Empty AuthorizerUri, expected: %q", expectedUri) + } + + if !expectedUri.MatchString(*conf.AuthorizerUri) { + return fmt.Errorf("AuthorizerUri didn't match. Expected: %q, Given: %q", expectedUri, *conf.AuthorizerUri) + } + return nil + } +} + +func testAccCheckAWSAPIGatewayAuthorizerIdentitySource(conf *apigateway.Authorizer, expectedSource string) resource.TestCheckFunc { + return func(s *terraform.State) error { + if conf.IdentitySource == nil { + return fmt.Errorf("Empty IdentitySource, expected: %q", expectedSource) + } + if *conf.IdentitySource != expectedSource { + return fmt.Errorf("IdentitySource didn't match. Expected: %q, Given: %q", expectedSource, *conf.IdentitySource) + } + return nil + } +} + +func testAccCheckAWSAPIGatewayAuthorizerName(conf *apigateway.Authorizer, expectedName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + if conf.Name == nil { + return fmt.Errorf("Empty Name, expected: %q", expectedName) + } + if *conf.Name != expectedName { + return fmt.Errorf("Name didn't match. Expected: %q, Given: %q", expectedName, *conf.Name) + } + return nil + } +} + +func testAccCheckAWSAPIGatewayAuthorizerType(conf *apigateway.Authorizer, expectedType string) resource.TestCheckFunc { + return func(s *terraform.State) error { + if conf.Type == nil { + return fmt.Errorf("Empty Type, expected: %q", expectedType) + } + if *conf.Type != expectedType { + return fmt.Errorf("Type didn't match. Expected: %q, Given: %q", expectedType, *conf.Type) + } + return nil + } +} + +func testAccCheckAWSAPIGatewayAuthorizerAuthorizerCredentials(conf *apigateway.Authorizer, expectedCreds *regexp.Regexp) resource.TestCheckFunc { + return func(s *terraform.State) error { + if conf.AuthorizerCredentials == nil { + return fmt.Errorf("Empty AuthorizerCredentials, expected: %q", expectedCreds) + } + if !expectedCreds.MatchString(*conf.AuthorizerCredentials) { + return fmt.Errorf("AuthorizerCredentials didn't match. Expected: %q, Given: %q", + expectedCreds, *conf.AuthorizerCredentials) + } + return nil + } +} + +func testAccCheckAWSAPIGatewayAuthorizerAuthorizerResultTtlInSeconds(conf *apigateway.Authorizer, expectedTtl *int64) resource.TestCheckFunc { + return func(s *terraform.State) error { + if expectedTtl == conf.AuthorizerResultTtlInSeconds { + return nil + } + if expectedTtl == nil && conf.AuthorizerResultTtlInSeconds != nil { + return fmt.Errorf("Expected empty AuthorizerResultTtlInSeconds, given: %d", *conf.AuthorizerResultTtlInSeconds) + } + if conf.AuthorizerResultTtlInSeconds == nil { + return fmt.Errorf("Empty AuthorizerResultTtlInSeconds, expected: %d", expectedTtl) + } + if *conf.AuthorizerResultTtlInSeconds != *expectedTtl { + return fmt.Errorf("AuthorizerResultTtlInSeconds didn't match. Expected: %d, Given: %d", + *expectedTtl, *conf.AuthorizerResultTtlInSeconds) + } + return nil + } +} + +func testAccCheckAWSAPIGatewayAuthorizerIdentityValidationExpression(conf *apigateway.Authorizer, expectedExpression *string) resource.TestCheckFunc { + return func(s *terraform.State) error { + if expectedExpression == conf.IdentityValidationExpression { + return nil + } + if expectedExpression == nil && conf.IdentityValidationExpression != nil { + return fmt.Errorf("Expected empty IdentityValidationExpression, given: %q", *conf.IdentityValidationExpression) + } + if conf.IdentityValidationExpression == nil { + return fmt.Errorf("Empty IdentityValidationExpression, expected: %q", *expectedExpression) + } + if *conf.IdentityValidationExpression != *expectedExpression { + return fmt.Errorf("IdentityValidationExpression didn't match. Expected: %q, Given: %q", + *expectedExpression, *conf.IdentityValidationExpression) + } + return nil + } +} + +func testAccCheckAWSAPIGatewayAuthorizerExists(n string, res *apigateway.Authorizer) 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 fmt.Errorf("No API Gateway Authorizer ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).apigateway + + req := &apigateway.GetAuthorizerInput{ + AuthorizerId: aws.String(rs.Primary.ID), + RestApiId: aws.String(rs.Primary.Attributes["rest_api_id"]), + } + describe, err := conn.GetAuthorizer(req) + if err != nil { + return err + } + + *res = *describe + + return nil + } +} + +func testAccCheckAWSAPIGatewayAuthorizerDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).apigateway + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_api_gateway_authorizer" { + continue + } + + req := &apigateway.GetAuthorizerInput{ + AuthorizerId: aws.String(rs.Primary.ID), + RestApiId: aws.String(rs.Primary.Attributes["rest_api_id"]), + } + _, err := conn.GetAuthorizer(req) + + if err == nil { + return fmt.Errorf("API Gateway Authorizer still exists") + } + + aws2err, ok := err.(awserr.Error) + if !ok { + return err + } + if aws2err.Code() != "NotFoundException" { + return err + } + + return nil + } + + return nil +} + +const testAccAWSAPIGatewayAuthorizerConfig_base = ` +resource "aws_api_gateway_rest_api" "test" { + name = "tf-auth-test" +} + +resource "aws_iam_role" "invocation_role" { + name = "tf_acc_api_gateway_auth_invocation_role" + path = "/" + assume_role_policy = < max { + errors = append(errors, fmt.Errorf( + "%q cannot be higher than %d: %d", k, max, value)) + } + return + } +} + func validateCloudWatchEventTargetId(v interface{}, k string) (ws []string, errors []error) { value := v.(string) if len(value) > 64 { diff --git a/builtin/providers/aws/validators_test.go b/builtin/providers/aws/validators_test.go index 9e8106f6ad81..afd92c41c1f2 100644 --- a/builtin/providers/aws/validators_test.go +++ b/builtin/providers/aws/validators_test.go @@ -460,3 +460,23 @@ func TestValidateS3BucketLifecycleRuleId(t *testing.T) { } } } + +func TestValidateIntegerInRange(t *testing.T) { + validIntegers := []int{-259, 0, 1, 5, 999} + min := -259 + max := 999 + for _, v := range validIntegers { + _, errors := validateIntegerInRange(min, max)(v, "name") + if len(errors) != 0 { + t.Fatalf("%q should be an integer in range (%d, %d): %q", v, min, max, errors) + } + } + + invalidIntegers := []int{-260, -99999, 1000, 25678} + for _, v := range invalidIntegers { + _, errors := validateIntegerInRange(min, max)(v, "name") + if len(errors) == 0 { + t.Fatalf("%q should be an integer outside range (%d, %d)", v, min, max) + } + } +} diff --git a/website/source/docs/providers/aws/r/api_gateway_authorizer.html.markdown b/website/source/docs/providers/aws/r/api_gateway_authorizer.html.markdown new file mode 100644 index 000000000000..a1bcc4194f89 --- /dev/null +++ b/website/source/docs/providers/aws/r/api_gateway_authorizer.html.markdown @@ -0,0 +1,112 @@ +--- +layout: "aws" +page_title: "AWS: aws_api_gateway_authorizer" +sidebar_current: "docs-aws-resource-api-gateway-authorizer" +description: |- + Provides an API Gateway Authorizer. +--- + +# aws\_api\_gateway\_authorizer + +Provides an API Gateway Authorizer. + +## Example Usage + +``` +resource "aws_api_gateway_authorizer" "demo" { + name = "demo" + rest_api_id = "${aws_api_gateway_rest_api.demo.id}" + authorizer_uri = "arn:aws:apigateway:region:lambda:path/2015-03-31/functions/${aws_lambda_function.authorizer.arn}/invocations" + authorizer_credentials = "${aws_iam_role.invocation_role.arn}" +} + +resource "aws_api_gateway_rest_api" "demo" { + name = "auth-demo" +} + +resource "aws_iam_role" "invocation_role" { + name = "api_gateway_auth_invocation" + path = "/" + assume_role_policy = <> aws_api_gateway_api_key + > + aws_api_gateway_authorizer + > aws_api_gateway_deployment