Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] AWS APIGateway Custom Authorizer #6731

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion builtin/providers/aws/resource_aws_api_gateway_authorizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package aws
import (
"fmt"
"log"
"strings"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
Expand Down Expand Up @@ -200,7 +201,11 @@ func resourceAwsApiGatewayAuthorizerDelete(d *schema.ResourceData, meta interfac
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)
// XXX: Figure out a way to delete the method that depends on the authorizer first
// otherwise the authorizer will be dangling until the API is deleted
if !strings.Contains(err.Error(), "ConflictException") {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As long as the authorizer is managed in the same terraform scope and is referenced properly (i.e. not hardcoded authorizer IDs in methods) Terraform will schedule the deletion correctly by default - i.e. for complete destruction 1st method => 2nd authorizer. Have a look at the dependency graph via terraform graph. 😉

The only issue that may theoretically arise is eventual consistency of the AWS API (or the implementation of it) - i.e. the authorizer_id change may take time to propagate. We usually just retry the deletion in such cases with a reasonable timeout.

Did you experience this problem yourself @johnjelinek ?

return fmt.Errorf("Deleting API Gateway Authorizer failed: %s", err)
}
}

return nil
Expand Down
6 changes: 6 additions & 0 deletions builtin/providers/aws/resource_aws_api_gateway_method.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ func resourceAwsApiGatewayMethod() *schema.Resource {
Required: true,
},

"authorizer_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},

"api_key_required": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Expand Down Expand Up @@ -89,6 +94,7 @@ func resourceAwsApiGatewayMethodCreate(d *schema.ResourceData, meta interface{})
// TODO reimplement once [GH-2143](https://github.com/hashicorp/terraform/issues/2143) has been implemented
RequestParameters: aws.BoolMap(parameters),
ApiKeyRequired: aws.Bool(d.Get("api_key_required").(bool)),
AuthorizerId: aws.String(d.Get("authorizer_id").(string)),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we'll need to update the other functions too so that user can change the authorizer_id and Terraform can read it back if it's changed outside of Terraform.

i.e.

resourceAwsApiGatewayMethodRead will need d.Set("authorizer_id", out.AuthorizerId) - I noticed we're missing some other fields there - if you want to fix that too, that's great, but we can fix that in a separate PR.

and resourceAwsApiGatewayMethodUpdate will need if d.HasChange("authorizer_id") { block.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this all works for you, let's :shipit:

On Monday, July 25, 2016, Radek Simko notifications@github.com wrote:

In builtin/providers/aws/resource_aws_api_gateway_method.go
#6731 (comment):

@@ -89,6 +94,7 @@ func resourceAwsApiGatewayMethodCreate(d *schema.ResourceData, meta interface{})
// TODO reimplement once GH-2143 has been implemented
RequestParameters: aws.BoolMap(parameters),
ApiKeyRequired: aws.Bool(d.Get("api_key_required").(bool)),

  •   AuthorizerId:      aws.String(d.Get("authorizer_id").(string)),
    

I think we'll need to update the other functions too so that user can
change the authorizer_id and Terraform can read it back if it's changed
outside of Terraform.

i.e.

resourceAwsApiGatewayMethodRead will need d.Set("authorizer_id",
out.AuthorizerId) - I noticed we're missing some other fields there - if
you want to fix that too, that's great, but we can fix that in a separate
PR.

and resourceAwsApiGatewayMethodUpdate will need if
d.HasChange("authorizer_id") { block.


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/hashicorp/terraform/pull/6731/files/b47122f8b45f0439f214429e16701a23235e88ea#r72059118,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AA1Uikkw-TbB4vxBNSo9qBJ2sRW3VfE6ks5qZLRLgaJpZM4Ig0Qt
.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It works for common workflow - i.e. create/destroy, doesn't work for update and won't work for import either when we add it.

})
if err != nil {
return fmt.Errorf("Error creating API Gateway Method: %s", err)
Expand Down
137 changes: 136 additions & 1 deletion builtin/providers/aws/resource_aws_api_gateway_method_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,45 @@ func TestAccAWSAPIGatewayMethod_basic(t *testing.T) {
})
}

func TestAccAWSAPIGatewayMethod_customauthorizer(t *testing.T) {
var conf apigateway.Method

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAPIGatewayMethodDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAWSAPIGatewayMethodConfigWithCustomAuthorizer,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAPIGatewayMethodExists("aws_api_gateway_method.test", &conf),
testAccCheckAWSAPIGatewayMethodAttributes(&conf),
resource.TestCheckResourceAttr(
"aws_api_gateway_method.test", "http_method", "GET"),
resource.TestCheckResourceAttr(
"aws_api_gateway_method.test", "authorization", "CUSTOM"),
resource.TestCheckResourceAttr(
"aws_api_gateway_method.test", "request_models.application/json", "Error"),
),
},

resource.TestStep{
Config: testAccAWSAPIGatewayMethodConfigUpdate,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAPIGatewayMethodExists("aws_api_gateway_method.test", &conf),
testAccCheckAWSAPIGatewayMethodAttributesUpdate(&conf),
),
},
},
})
}

func testAccCheckAWSAPIGatewayMethodAttributes(conf *apigateway.Method) resource.TestCheckFunc {
return func(s *terraform.State) error {
if *conf.HttpMethod != "GET" {
return fmt.Errorf("Wrong HttpMethod: %q", *conf.HttpMethod)
}
if *conf.AuthorizationType != "NONE" {
if *conf.AuthorizationType != "NONE" && *conf.AuthorizationType != "CUSTOM" {
return fmt.Errorf("Wrong Authorization: %q", *conf.AuthorizationType)
}

Expand Down Expand Up @@ -154,6 +187,108 @@ func testAccCheckAWSAPIGatewayMethodDestroy(s *terraform.State) error {
return nil
}

const testAccAWSAPIGatewayMethodConfigWithCustomAuthorizer = `
resource "aws_api_gateway_rest_api" "test" {
name = "test"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably a nitpick, but it may be better to give the API unique name, e.g. tf-acc-test-authorizer. Should these tests leak (i.e. leave undeleted resources behind) we will be able to track the test more easily.

}

resource "aws_iam_role" "invocation_role" {
name = "tf_acc_api_gateway_auth_invocation_role"
path = "/"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "apigateway.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}

resource "aws_iam_role_policy" "invocation_policy" {
name = "default"
role = "${aws_iam_role.invocation_role.id}"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "lambda:InvokeFunction",
"Effect": "Allow",
"Resource": "${aws_lambda_function.authorizer.arn}"
}
]
}
EOF
}

resource "aws_iam_role" "iam_for_lambda" {
name = "tf_acc_iam_for_lambda_api_gateway_authorizer"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}

resource "aws_lambda_function" "authorizer" {
filename = "test-fixtures/lambdatest.zip"
source_code_hash = "${base64sha256(file("test-fixtures/lambdatest.zip"))}"
function_name = "tf_acc_api_gateway_authorizer"
role = "${aws_iam_role.iam_for_lambda.arn}"
handler = "exports.example"
}

resource "aws_api_gateway_authorizer" "test" {
name = "tf-acc-test-authorizer"
rest_api_id = "${aws_api_gateway_rest_api.test.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_resource" "test" {
rest_api_id = "${aws_api_gateway_rest_api.test.id}"
parent_id = "${aws_api_gateway_rest_api.test.root_resource_id}"
path_part = "test"
}

resource "aws_api_gateway_method" "test" {
rest_api_id = "${aws_api_gateway_rest_api.test.id}"
resource_id = "${aws_api_gateway_resource.test.id}"
http_method = "GET"
authorization = "CUSTOM"
authorizer_id = "${aws_api_gateway_authorizer.test.id}"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is the tricky part. Because I have a reference to the authorizer_id here, terraform wants to delete the authorizer before deleting the method, but the AWS SDK API expects all methods to be deleted first. Maybe instead, the authorizer should have a collection of methods it should attach to, instead. What do you think?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

terraform wants to delete the authorizer before deleting the method

in what situation exactly? on complete terraform destroy? I believe the opposite is reality:
https://gist.github.com/radeksimko/3d9b0637ad821b34de7be4e7e2c993fe - snippet below:

aws_api_gateway_method.MyDemoMethod: Destruction complete
...
aws_api_gateway_authorizer.demo: Destroying...
aws_api_gateway_authorizer.demo: Destruction complete


request_models = {
"application/json" = "Error"
}

request_parameters_in_json = <<PARAMS
{
"method.request.header.Content-Type": false,
"method.request.querystring.page": true
}
PARAMS
}
`

const testAccAWSAPIGatewayMethodConfig = `
resource "aws_api_gateway_rest_api" "test" {
name = "test"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ The following arguments are supported:
* `rest_api_id` - (Required) The ID of the associated REST API
* `resource_id` - (Required) The API resource ID
* `http_method` - (Required) The HTTP Method (`GET`, `POST`, `PUT`, `DELETE`, `HEAD`, `OPTION`)
* `authorization` - (Required) The type of authorization used for the method
* `authorization` - (Required) The type of authorization used for the method (`NONE`, `CUSTOM`)
* `authorizer_id` - (Optional) The authorizer id to be used when the authorization is `CUSTOM`
* `api_key_required` - (Optional) Specify if the method requires an API key
* `request_models` - (Optional) A map of the API models used for the request's content type
where key is the content type (e.g. `application/json`)
Expand Down