github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/aws/resource_aws_lambda_permission_test.go (about)

     1  package aws
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"regexp"
     7  	"strings"
     8  	"testing"
     9  	"time"
    10  
    11  	"github.com/aws/aws-sdk-go/aws"
    12  	"github.com/aws/aws-sdk-go/aws/awserr"
    13  	"github.com/aws/aws-sdk-go/service/lambda"
    14  	"github.com/hashicorp/terraform/helper/acctest"
    15  	"github.com/hashicorp/terraform/helper/resource"
    16  	"github.com/hashicorp/terraform/terraform"
    17  )
    18  
    19  func TestLambdaPermissionUnmarshalling(t *testing.T) {
    20  	v := LambdaPolicy{}
    21  	err := json.Unmarshal(testLambdaPolicy, &v)
    22  	if err != nil {
    23  		t.Fatalf("Expected no error when unmarshalling: %s", err)
    24  	}
    25  
    26  	expectedSid := "36fe77d9-a4ae-13fb-8beb-5dc6821d5291"
    27  	if v.Statement[0].Sid != expectedSid {
    28  		t.Fatalf("Expected Sid to match (%q != %q)", v.Statement[0].Sid, expectedSid)
    29  	}
    30  
    31  	expectedFunctionName := "arn:aws:lambda:eu-west-1:319201112229:function:myCustomFunction"
    32  	if v.Statement[0].Resource != expectedFunctionName {
    33  		t.Fatalf("Expected function name to match (%q != %q)", v.Statement[0].Resource, expectedFunctionName)
    34  	}
    35  
    36  	expectedAction := "lambda:InvokeFunction"
    37  	if v.Statement[0].Action != expectedAction {
    38  		t.Fatalf("Expected Action to match (%q != %q)", v.Statement[0].Action, expectedAction)
    39  	}
    40  
    41  	expectedPrincipal := "events.amazonaws.com"
    42  	if v.Statement[0].Principal["Service"] != expectedPrincipal {
    43  		t.Fatalf("Expected Principal to match (%q != %q)", v.Statement[0].Principal["Service"], expectedPrincipal)
    44  	}
    45  
    46  	expectedSourceAccount := "319201112229"
    47  	if v.Statement[0].Condition["StringEquals"]["AWS:SourceAccount"] != expectedSourceAccount {
    48  		t.Fatalf("Expected Source Account to match (%q != %q)",
    49  			v.Statement[0].Condition["StringEquals"]["AWS:SourceAccount"],
    50  			expectedSourceAccount)
    51  	}
    52  }
    53  
    54  func TestLambdaPermissionGetQualifierFromLambdaAliasOrVersionArn_alias(t *testing.T) {
    55  	arnWithAlias := "arn:aws:lambda:us-west-2:187636751137:function:lambda_function_name:testalias"
    56  	expectedQualifier := "testalias"
    57  	qualifier, err := getQualifierFromLambdaAliasOrVersionArn(arnWithAlias)
    58  	if err != nil {
    59  		t.Fatalf("Expected no error when getting qualifier: %s", err)
    60  	}
    61  	if qualifier != expectedQualifier {
    62  		t.Fatalf("Expected qualifier to match (%q != %q)", qualifier, expectedQualifier)
    63  	}
    64  }
    65  
    66  func TestLambdaPermissionGetQualifierFromLambdaAliasOrVersionArn_govcloud(t *testing.T) {
    67  	arnWithAlias := "arn:aws-us-gov:lambda:us-west-2:187636751137:function:lambda_function_name:testalias"
    68  	expectedQualifier := "testalias"
    69  	qualifier, err := getQualifierFromLambdaAliasOrVersionArn(arnWithAlias)
    70  	if err != nil {
    71  		t.Fatalf("Expected no error when getting qualifier: %s", err)
    72  	}
    73  	if qualifier != expectedQualifier {
    74  		t.Fatalf("Expected qualifier to match (%q != %q)", qualifier, expectedQualifier)
    75  	}
    76  }
    77  
    78  func TestLambdaPermissionGetQualifierFromLambdaAliasOrVersionArn_version(t *testing.T) {
    79  	arnWithVersion := "arn:aws:lambda:us-west-2:187636751137:function:lambda_function_name:223"
    80  	expectedQualifier := "223"
    81  	qualifier, err := getQualifierFromLambdaAliasOrVersionArn(arnWithVersion)
    82  	if err != nil {
    83  		t.Fatalf("Expected no error when getting qualifier: %s", err)
    84  	}
    85  	if qualifier != expectedQualifier {
    86  		t.Fatalf("Expected qualifier to match (%q != %q)", qualifier, expectedQualifier)
    87  	}
    88  }
    89  
    90  func TestLambdaPermissionGetQualifierFromLambdaAliasOrVersionArn_invalid(t *testing.T) {
    91  	invalidArn := "arn:aws:lambda:us-west-2:187636751137:function:lambda_function_name"
    92  	qualifier, err := getQualifierFromLambdaAliasOrVersionArn(invalidArn)
    93  	if err == nil {
    94  		t.Fatalf("Expected error when getting qualifier")
    95  	}
    96  	if qualifier != "" {
    97  		t.Fatalf("Expected qualifier to be empty (%q)", qualifier)
    98  	}
    99  
   100  	// with trailing colon
   101  	invalidArn = "arn:aws:lambda:us-west-2:187636751137:function:lambda_function_name:"
   102  	qualifier, err = getQualifierFromLambdaAliasOrVersionArn(invalidArn)
   103  	if err == nil {
   104  		t.Fatalf("Expected error when getting qualifier")
   105  	}
   106  	if qualifier != "" {
   107  		t.Fatalf("Expected qualifier to be empty (%q)", qualifier)
   108  	}
   109  }
   110  
   111  func TestLambdaPermissionGetFunctionNameFromLambdaArn_invalid(t *testing.T) {
   112  	invalidArn := "arn:aws:lambda:us-west-2:187636751137:function:"
   113  	fn, err := getFunctionNameFromLambdaArn(invalidArn)
   114  	if err == nil {
   115  		t.Fatalf("Expected error when parsing invalid ARN (%q)", invalidArn)
   116  	}
   117  	if fn != "" {
   118  		t.Fatalf("Expected empty string when parsing invalid ARN (%q)", invalidArn)
   119  	}
   120  }
   121  
   122  func TestLambdaPermissionGetFunctionNameFromLambdaArn_valid(t *testing.T) {
   123  	validArn := "arn:aws:lambda:us-west-2:187636751137:function:lambda_function_name"
   124  	fn, err := getFunctionNameFromLambdaArn(validArn)
   125  	if err != nil {
   126  		t.Fatalf("Expected no error (%q): %q", validArn, err)
   127  	}
   128  	expectedFunctionname := "lambda_function_name"
   129  	if fn != expectedFunctionname {
   130  		t.Fatalf("Expected Lambda function name to match (%q != %q)",
   131  			validArn, expectedFunctionname)
   132  	}
   133  
   134  	// With qualifier
   135  	validArn = "arn:aws:lambda:us-west-2:187636751137:function:lambda_function_name:12"
   136  	fn, err = getFunctionNameFromLambdaArn(validArn)
   137  	if err != nil {
   138  		t.Fatalf("Expected no error (%q): %q", validArn, err)
   139  	}
   140  	expectedFunctionname = "lambda_function_name"
   141  	if fn != expectedFunctionname {
   142  		t.Fatalf("Expected Lambda function name to match (%q != %q)",
   143  			validArn, expectedFunctionname)
   144  	}
   145  }
   146  
   147  func TestAccAWSLambdaPermission_basic(t *testing.T) {
   148  	var statement LambdaPolicyStatement
   149  	endsWithFuncName := regexp.MustCompile(":function:lambda_function_name_perm$")
   150  
   151  	rName := fmt.Sprintf("tf_iam_%d", acctest.RandInt())
   152  
   153  	resource.Test(t, resource.TestCase{
   154  		PreCheck:     func() { testAccPreCheck(t) },
   155  		Providers:    testAccProviders,
   156  		CheckDestroy: testAccCheckAWSLambdaPermissionDestroy,
   157  		Steps: []resource.TestStep{
   158  			{
   159  				Config: testAccAWSLambdaPermissionConfig(rName),
   160  				Check: resource.ComposeTestCheckFunc(
   161  					testAccCheckLambdaPermissionExists("aws_lambda_permission.allow_cloudwatch", &statement),
   162  					resource.TestCheckResourceAttr("aws_lambda_permission.allow_cloudwatch", "action", "lambda:InvokeFunction"),
   163  					resource.TestCheckResourceAttr("aws_lambda_permission.allow_cloudwatch", "principal", "events.amazonaws.com"),
   164  					resource.TestCheckResourceAttr("aws_lambda_permission.allow_cloudwatch", "statement_id", "AllowExecutionFromCloudWatch"),
   165  					resource.TestCheckResourceAttr("aws_lambda_permission.allow_cloudwatch", "qualifier", ""),
   166  					resource.TestMatchResourceAttr("aws_lambda_permission.allow_cloudwatch", "function_name", endsWithFuncName),
   167  				),
   168  			},
   169  		},
   170  	})
   171  }
   172  
   173  func TestAccAWSLambdaPermission_withRawFunctionName(t *testing.T) {
   174  	var statement LambdaPolicyStatement
   175  	endsWithFuncName := regexp.MustCompile(":function:lambda_function_name_perm_raw_func_name$")
   176  
   177  	resource.Test(t, resource.TestCase{
   178  		PreCheck:     func() { testAccPreCheck(t) },
   179  		Providers:    testAccProviders,
   180  		CheckDestroy: testAccCheckAWSLambdaPermissionDestroy,
   181  		Steps: []resource.TestStep{
   182  			{
   183  				Config: testAccAWSLambdaPermissionConfig_withRawFunctionName,
   184  				Check: resource.ComposeTestCheckFunc(
   185  					testAccCheckLambdaPermissionExists("aws_lambda_permission.with_raw_func_name", &statement),
   186  					resource.TestCheckResourceAttr("aws_lambda_permission.with_raw_func_name", "action", "lambda:InvokeFunction"),
   187  					resource.TestCheckResourceAttr("aws_lambda_permission.with_raw_func_name", "principal", "events.amazonaws.com"),
   188  					resource.TestCheckResourceAttr("aws_lambda_permission.with_raw_func_name", "statement_id", "AllowExecutionWithRawFuncName"),
   189  					resource.TestMatchResourceAttr("aws_lambda_permission.with_raw_func_name", "function_name", endsWithFuncName),
   190  				),
   191  			},
   192  		},
   193  	})
   194  }
   195  
   196  func TestAccAWSLambdaPermission_withQualifier(t *testing.T) {
   197  	var statement LambdaPolicyStatement
   198  	endsWithFuncName := regexp.MustCompile(":function:lambda_function_name_perm_qualifier$")
   199  
   200  	resource.Test(t, resource.TestCase{
   201  		PreCheck:     func() { testAccPreCheck(t) },
   202  		Providers:    testAccProviders,
   203  		CheckDestroy: testAccCheckAWSLambdaPermissionDestroy,
   204  		Steps: []resource.TestStep{
   205  			{
   206  				Config: testAccAWSLambdaPermissionConfig_withQualifier,
   207  				Check: resource.ComposeTestCheckFunc(
   208  					testAccCheckLambdaPermissionExists("aws_lambda_permission.with_qualifier", &statement),
   209  					resource.TestCheckResourceAttr("aws_lambda_permission.with_qualifier", "action", "lambda:InvokeFunction"),
   210  					resource.TestCheckResourceAttr("aws_lambda_permission.with_qualifier", "principal", "events.amazonaws.com"),
   211  					resource.TestCheckResourceAttr("aws_lambda_permission.with_qualifier", "statement_id", "AllowExecutionWithQualifier"),
   212  					resource.TestMatchResourceAttr("aws_lambda_permission.with_qualifier", "function_name", endsWithFuncName),
   213  					resource.TestCheckResourceAttr("aws_lambda_permission.with_qualifier", "qualifier", "testalias_perm_qualifier"),
   214  				),
   215  			},
   216  		},
   217  	})
   218  }
   219  
   220  func TestAccAWSLambdaPermission_multiplePerms(t *testing.T) {
   221  	var firstStatement LambdaPolicyStatement
   222  	var firstStatementModified LambdaPolicyStatement
   223  
   224  	var secondStatement LambdaPolicyStatement
   225  	var secondStatementModified LambdaPolicyStatement
   226  
   227  	var thirdStatement LambdaPolicyStatement
   228  
   229  	resource.Test(t, resource.TestCase{
   230  		PreCheck:     func() { testAccPreCheck(t) },
   231  		Providers:    testAccProviders,
   232  		CheckDestroy: testAccCheckAWSLambdaPermissionDestroy,
   233  		Steps: []resource.TestStep{
   234  			{
   235  				Config: testAccAWSLambdaPermissionConfig_multiplePerms,
   236  				Check: resource.ComposeTestCheckFunc(
   237  					// 1st
   238  					testAccCheckLambdaPermissionExists("aws_lambda_permission.first", &firstStatement),
   239  					resource.TestCheckResourceAttr("aws_lambda_permission.first", "action", "lambda:InvokeFunction"),
   240  					resource.TestCheckResourceAttr("aws_lambda_permission.first", "principal", "events.amazonaws.com"),
   241  					resource.TestCheckResourceAttr("aws_lambda_permission.first", "statement_id", "AllowExecutionFirst"),
   242  					resource.TestMatchResourceAttr("aws_lambda_permission.first", "function_name",
   243  						regexp.MustCompile(":function:lambda_function_name_perm_multiperms$")),
   244  					// 2nd
   245  					testAccCheckLambdaPermissionExists("aws_lambda_permission.second", &firstStatementModified),
   246  					resource.TestCheckResourceAttr("aws_lambda_permission.second", "action", "lambda:*"),
   247  					resource.TestCheckResourceAttr("aws_lambda_permission.second", "principal", "events.amazonaws.com"),
   248  					resource.TestCheckResourceAttr("aws_lambda_permission.second", "statement_id", "AllowExecutionSecond"),
   249  					resource.TestMatchResourceAttr("aws_lambda_permission.second", "function_name",
   250  						regexp.MustCompile(":function:lambda_function_name_perm_multiperms$")),
   251  				),
   252  			},
   253  			{
   254  				Config: testAccAWSLambdaPermissionConfig_multiplePermsModified,
   255  				Check: resource.ComposeTestCheckFunc(
   256  					// 1st
   257  					testAccCheckLambdaPermissionExists("aws_lambda_permission.first", &secondStatement),
   258  					resource.TestCheckResourceAttr("aws_lambda_permission.first", "action", "lambda:InvokeFunction"),
   259  					resource.TestCheckResourceAttr("aws_lambda_permission.first", "principal", "events.amazonaws.com"),
   260  					resource.TestCheckResourceAttr("aws_lambda_permission.first", "statement_id", "AllowExecutionFirst"),
   261  					resource.TestMatchResourceAttr("aws_lambda_permission.first", "function_name",
   262  						regexp.MustCompile(":function:lambda_function_name_perm_multiperms$")),
   263  					// 2nd
   264  					testAccCheckLambdaPermissionExists("aws_lambda_permission.sec0nd", &secondStatementModified),
   265  					resource.TestCheckResourceAttr("aws_lambda_permission.sec0nd", "action", "lambda:*"),
   266  					resource.TestCheckResourceAttr("aws_lambda_permission.sec0nd", "principal", "events.amazonaws.com"),
   267  					resource.TestCheckResourceAttr("aws_lambda_permission.sec0nd", "statement_id", "AllowExecutionSec0nd"),
   268  					resource.TestMatchResourceAttr("aws_lambda_permission.sec0nd", "function_name",
   269  						regexp.MustCompile(":function:lambda_function_name_perm_multiperms$")),
   270  					// 3rd
   271  					testAccCheckLambdaPermissionExists("aws_lambda_permission.third", &thirdStatement),
   272  					resource.TestCheckResourceAttr("aws_lambda_permission.third", "action", "lambda:*"),
   273  					resource.TestCheckResourceAttr("aws_lambda_permission.third", "principal", "events.amazonaws.com"),
   274  					resource.TestCheckResourceAttr("aws_lambda_permission.third", "statement_id", "AllowExecutionThird"),
   275  					resource.TestMatchResourceAttr("aws_lambda_permission.third", "function_name",
   276  						regexp.MustCompile(":function:lambda_function_name_perm_multiperms$")),
   277  				),
   278  			},
   279  		},
   280  	})
   281  }
   282  
   283  func TestAccAWSLambdaPermission_withS3(t *testing.T) {
   284  	rInt := acctest.RandInt()
   285  
   286  	var statement LambdaPolicyStatement
   287  	endsWithFuncName := regexp.MustCompile(":function:lambda_function_name_perm_s3$")
   288  
   289  	resource.Test(t, resource.TestCase{
   290  		PreCheck:     func() { testAccPreCheck(t) },
   291  		Providers:    testAccProviders,
   292  		CheckDestroy: testAccCheckAWSLambdaPermissionDestroy,
   293  		Steps: []resource.TestStep{
   294  			{
   295  				Config: fmt.Sprintf(testAccAWSLambdaPermissionConfig_withS3_tpl, rInt),
   296  				Check: resource.ComposeTestCheckFunc(
   297  					testAccCheckLambdaPermissionExists("aws_lambda_permission.with_s3", &statement),
   298  					resource.TestCheckResourceAttr("aws_lambda_permission.with_s3", "action", "lambda:InvokeFunction"),
   299  					resource.TestCheckResourceAttr("aws_lambda_permission.with_s3", "principal", "s3.amazonaws.com"),
   300  					resource.TestCheckResourceAttr("aws_lambda_permission.with_s3", "statement_id", "AllowExecutionFromS3"),
   301  					resource.TestMatchResourceAttr("aws_lambda_permission.with_s3", "function_name", endsWithFuncName),
   302  					resource.TestCheckResourceAttr("aws_lambda_permission.with_s3", "source_arn",
   303  						fmt.Sprintf("arn:aws:s3:::tf-acc-towards-lambda-%d", rInt)),
   304  				),
   305  			},
   306  		},
   307  	})
   308  }
   309  
   310  func TestAccAWSLambdaPermission_withSNS(t *testing.T) {
   311  	var statement LambdaPolicyStatement
   312  	endsWithFuncName := regexp.MustCompile(":function:lambda_function_name_perm_sns$")
   313  	endsWithTopicName := regexp.MustCompile(":tf-acc-user-updates-topic$")
   314  
   315  	resource.Test(t, resource.TestCase{
   316  		PreCheck:     func() { testAccPreCheck(t) },
   317  		Providers:    testAccProviders,
   318  		CheckDestroy: testAccCheckAWSLambdaPermissionDestroy,
   319  		Steps: []resource.TestStep{
   320  			{
   321  				Config: testAccAWSLambdaPermissionConfig_withSNS,
   322  				Check: resource.ComposeTestCheckFunc(
   323  					testAccCheckLambdaPermissionExists("aws_lambda_permission.with_sns", &statement),
   324  					resource.TestCheckResourceAttr("aws_lambda_permission.with_sns", "action", "lambda:InvokeFunction"),
   325  					resource.TestCheckResourceAttr("aws_lambda_permission.with_sns", "principal", "sns.amazonaws.com"),
   326  					resource.TestCheckResourceAttr("aws_lambda_permission.with_sns", "statement_id", "AllowExecutionFromSNS"),
   327  					resource.TestMatchResourceAttr("aws_lambda_permission.with_sns", "function_name", endsWithFuncName),
   328  					resource.TestMatchResourceAttr("aws_lambda_permission.with_sns", "source_arn", endsWithTopicName),
   329  				),
   330  			},
   331  		},
   332  	})
   333  }
   334  
   335  func testAccCheckLambdaPermissionExists(n string, statement *LambdaPolicyStatement) resource.TestCheckFunc {
   336  	return func(s *terraform.State) error {
   337  		rs, ok := s.RootModule().Resources[n]
   338  		if !ok {
   339  			return fmt.Errorf("Not found: %s", n)
   340  		}
   341  
   342  		conn := testAccProvider.Meta().(*AWSClient).lambdaconn
   343  
   344  		// IAM is eventually consistent
   345  		var foundStatement *LambdaPolicyStatement
   346  		err := resource.Retry(5*time.Minute, func() *resource.RetryError {
   347  			var err error
   348  			foundStatement, err = lambdaPermissionExists(rs, conn)
   349  			if err != nil {
   350  				if strings.HasPrefix(err.Error(), "ResourceNotFoundException") {
   351  					return resource.RetryableError(err)
   352  				}
   353  				if strings.HasPrefix(err.Error(), "Lambda policy not found") {
   354  					return resource.RetryableError(err)
   355  				}
   356  				if strings.HasPrefix(err.Error(), "Failed to find statement") {
   357  					return resource.RetryableError(err)
   358  				}
   359  				return resource.NonRetryableError(err)
   360  			}
   361  			return nil
   362  		})
   363  		if err != nil {
   364  			return err
   365  		}
   366  
   367  		*statement = *foundStatement
   368  
   369  		return nil
   370  	}
   371  }
   372  
   373  func testAccCheckAWSLambdaPermissionDestroy(s *terraform.State) error {
   374  	conn := testAccProvider.Meta().(*AWSClient).lambdaconn
   375  
   376  	for _, rs := range s.RootModule().Resources {
   377  		if rs.Type != "aws_lambda_permission" {
   378  			continue
   379  		}
   380  
   381  		// IAM is eventually consistent
   382  		err := resource.Retry(5*time.Minute, func() *resource.RetryError {
   383  			err := isLambdaPermissionGone(rs, conn)
   384  			if err != nil {
   385  				if !strings.HasPrefix(err.Error(), "Error unmarshalling Lambda policy") {
   386  					return resource.RetryableError(err)
   387  				}
   388  				return resource.NonRetryableError(err)
   389  			}
   390  			return nil
   391  		})
   392  		if err != nil {
   393  			return err
   394  		}
   395  	}
   396  
   397  	return nil
   398  }
   399  
   400  func isLambdaPermissionGone(rs *terraform.ResourceState, conn *lambda.Lambda) error {
   401  	params := &lambda.GetPolicyInput{
   402  		FunctionName: aws.String(rs.Primary.Attributes["function_name"]),
   403  	}
   404  	if v, ok := rs.Primary.Attributes["qualifier"]; ok && v != "" {
   405  		params.Qualifier = aws.String(v)
   406  	}
   407  
   408  	resp, err := conn.GetPolicy(params)
   409  	if awsErr, ok := err.(awserr.Error); ok {
   410  		if awsErr.Code() == "ResourceNotFoundException" {
   411  			// no policy found => all statements deleted
   412  			return nil
   413  		}
   414  	}
   415  	if err != nil {
   416  		return fmt.Errorf("Unexpected error when checking existence of Lambda permission: %s\n%s",
   417  			rs.Primary.ID, err)
   418  	}
   419  
   420  	policyInBytes := []byte(*resp.Policy)
   421  	policy := LambdaPolicy{}
   422  	err = json.Unmarshal(policyInBytes, &policy)
   423  	if err != nil {
   424  		return fmt.Errorf("Error unmarshalling Lambda policy (%s): %s", *resp.Policy, err)
   425  	}
   426  
   427  	state, err := findLambdaPolicyStatementById(&policy, rs.Primary.ID)
   428  	if err != nil {
   429  		// statement not found => deleted
   430  		return nil
   431  	}
   432  
   433  	return fmt.Errorf("Policy statement expected to be gone (%s):\n%s",
   434  		rs.Primary.ID, *state)
   435  }
   436  
   437  func lambdaPermissionExists(rs *terraform.ResourceState, conn *lambda.Lambda) (*LambdaPolicyStatement, error) {
   438  	params := &lambda.GetPolicyInput{
   439  		FunctionName: aws.String(rs.Primary.Attributes["function_name"]),
   440  	}
   441  	if v, ok := rs.Primary.Attributes["qualifier"]; ok && v != "" {
   442  		params.Qualifier = aws.String(v)
   443  	}
   444  
   445  	resp, err := conn.GetPolicy(params)
   446  	if err != nil {
   447  		return nil, fmt.Errorf("Lambda policy not found: %q", err)
   448  	}
   449  
   450  	if resp.Policy == nil {
   451  		return nil, fmt.Errorf("Received Lambda policy is empty")
   452  	}
   453  
   454  	policyInBytes := []byte(*resp.Policy)
   455  	policy := LambdaPolicy{}
   456  	err = json.Unmarshal(policyInBytes, &policy)
   457  	if err != nil {
   458  		return nil, fmt.Errorf("Error unmarshalling Lambda policy: %s", err)
   459  	}
   460  
   461  	return findLambdaPolicyStatementById(&policy, rs.Primary.ID)
   462  }
   463  
   464  func testAccAWSLambdaPermissionConfig(rName string) string {
   465  	return fmt.Sprintf(`
   466  resource "aws_lambda_permission" "allow_cloudwatch" {
   467      statement_id = "AllowExecutionFromCloudWatch"
   468      action = "lambda:InvokeFunction"
   469      function_name = "${aws_lambda_function.test_lambda.arn}"
   470      principal = "events.amazonaws.com"
   471  }
   472  
   473  resource "aws_lambda_function" "test_lambda" {
   474      filename = "test-fixtures/lambdatest.zip"
   475      function_name = "lambda_function_name_perm"
   476      role = "${aws_iam_role.iam_for_lambda.arn}"
   477      handler = "exports.handler"
   478      runtime = "nodejs4.3"
   479  }
   480  
   481  resource "aws_iam_role" "iam_for_lambda" {
   482      name = "%s"
   483      assume_role_policy = <<EOF
   484  {
   485    "Version": "2012-10-17",
   486    "Statement": [
   487      {
   488        "Action": "sts:AssumeRole",
   489        "Principal": {
   490          "Service": "lambda.amazonaws.com"
   491        },
   492        "Effect": "Allow",
   493        "Sid": ""
   494      }
   495    ]
   496  }
   497  EOF
   498  }`, rName)
   499  }
   500  
   501  var testAccAWSLambdaPermissionConfig_withRawFunctionName = `
   502  resource "aws_lambda_permission" "with_raw_func_name" {
   503      statement_id = "AllowExecutionWithRawFuncName"
   504      action = "lambda:InvokeFunction"
   505      function_name = "${aws_lambda_function.test_lambda.arn}"
   506      principal = "events.amazonaws.com"
   507  }
   508  
   509  resource "aws_lambda_function" "test_lambda" {
   510      filename = "test-fixtures/lambdatest.zip"
   511      function_name = "lambda_function_name_perm_raw_func_name"
   512      role = "${aws_iam_role.iam_for_lambda.arn}"
   513      handler = "exports.handler"
   514      runtime = "nodejs4.3"
   515  }
   516  
   517  resource "aws_iam_role" "iam_for_lambda" {
   518      name = "iam_for_lambda_perm_raw_func_name"
   519      assume_role_policy = <<EOF
   520  {
   521    "Version": "2012-10-17",
   522    "Statement": [
   523      {
   524        "Action": "sts:AssumeRole",
   525        "Principal": {
   526          "Service": "lambda.amazonaws.com"
   527        },
   528        "Effect": "Allow",
   529        "Sid": ""
   530      }
   531    ]
   532  }
   533  EOF
   534  }
   535  `
   536  
   537  var testAccAWSLambdaPermissionConfig_withQualifier = `
   538  resource "aws_lambda_permission" "with_qualifier" {
   539      statement_id = "AllowExecutionWithQualifier"
   540      action = "lambda:InvokeFunction"
   541      function_name = "${aws_lambda_function.test_lambda.arn}"
   542      principal = "events.amazonaws.com"
   543      source_account = "111122223333"
   544      source_arn = "arn:aws:events:eu-west-1:111122223333:rule/RunDaily"
   545      qualifier = "${aws_lambda_alias.test_alias.name}"
   546  }
   547  
   548  resource "aws_lambda_alias" "test_alias" {
   549      name = "testalias_perm_qualifier"
   550      description = "a sample description"
   551      function_name = "${aws_lambda_function.test_lambda.arn}"
   552      function_version = "$LATEST"
   553  }
   554  
   555  resource "aws_lambda_function" "test_lambda" {
   556      filename = "test-fixtures/lambdatest.zip"
   557      function_name = "lambda_function_name_perm_qualifier"
   558      role = "${aws_iam_role.iam_for_lambda.arn}"
   559      handler = "exports.handler"
   560      runtime = "nodejs4.3"
   561  }
   562  
   563  resource "aws_iam_role" "iam_for_lambda" {
   564      name = "iam_for_lambda_perm_qualifier"
   565      assume_role_policy = <<EOF
   566  {
   567    "Version": "2012-10-17",
   568    "Statement": [
   569      {
   570        "Action": "sts:AssumeRole",
   571        "Principal": {
   572          "Service": "lambda.amazonaws.com"
   573        },
   574        "Effect": "Allow",
   575        "Sid": ""
   576      }
   577    ]
   578  }
   579  EOF
   580  }
   581  `
   582  
   583  var testAccAWSLambdaPermissionConfig_multiplePerms_tpl = `
   584  resource "aws_lambda_permission" "first" {
   585      statement_id = "AllowExecutionFirst"
   586      action = "lambda:InvokeFunction"
   587      function_name = "${aws_lambda_function.test_lambda.arn}"
   588      principal = "events.amazonaws.com"
   589  }
   590  
   591  resource "aws_lambda_permission" "%s" {
   592      statement_id = "%s"
   593      action = "lambda:*"
   594      function_name = "${aws_lambda_function.test_lambda.arn}"
   595      principal = "events.amazonaws.com"
   596  }
   597  %s
   598  
   599  resource "aws_lambda_function" "test_lambda" {
   600      filename = "test-fixtures/lambdatest.zip"
   601      function_name = "lambda_function_name_perm_multiperms"
   602      role = "${aws_iam_role.iam_for_lambda.arn}"
   603      handler = "exports.handler"
   604      runtime = "nodejs4.3"
   605  }
   606  
   607  resource "aws_iam_role" "iam_for_lambda" {
   608      name = "iam_for_lambda_perm_multi_perms"
   609      assume_role_policy = <<EOF
   610  {
   611    "Version": "2012-10-17",
   612    "Statement": [
   613      {
   614        "Action": "sts:AssumeRole",
   615        "Principal": {
   616          "Service": "lambda.amazonaws.com"
   617        },
   618        "Effect": "Allow",
   619        "Sid": ""
   620      }
   621    ]
   622  }
   623  EOF
   624  }
   625  `
   626  
   627  var testAccAWSLambdaPermissionConfig_multiplePerms = fmt.Sprintf(
   628  	testAccAWSLambdaPermissionConfig_multiplePerms_tpl, "second", "AllowExecutionSecond", "")
   629  var testAccAWSLambdaPermissionConfig_multiplePermsModified = fmt.Sprintf(
   630  	testAccAWSLambdaPermissionConfig_multiplePerms_tpl, "sec0nd", "AllowExecutionSec0nd", `
   631  resource "aws_lambda_permission" "third" {
   632      statement_id = "AllowExecutionThird"
   633      action = "lambda:*"
   634      function_name = "${aws_lambda_function.test_lambda.arn}"
   635      principal = "events.amazonaws.com"
   636  }`)
   637  
   638  var testAccAWSLambdaPermissionConfig_withS3_tpl = `
   639  resource "aws_lambda_permission" "with_s3" {
   640      statement_id = "AllowExecutionFromS3"
   641      action = "lambda:InvokeFunction"
   642      function_name = "${aws_lambda_function.my-func.arn}"
   643      principal = "s3.amazonaws.com"
   644      source_arn = "${aws_s3_bucket.default.arn}"
   645  }
   646  
   647  resource "aws_s3_bucket" "default" {
   648  	bucket = "tf-acc-towards-lambda-%d"
   649      acl = "private"
   650  }
   651  
   652  resource "aws_lambda_function" "my-func" {
   653      filename = "test-fixtures/lambdatest.zip"
   654      function_name = "lambda_function_name_perm_s3"
   655      role = "${aws_iam_role.police.arn}"
   656      handler = "exports.handler"
   657      runtime = "nodejs4.3"
   658  }
   659  
   660  resource "aws_iam_role" "police" {
   661      name = "iam_for_lambda_perm_with_s3"
   662      assume_role_policy = <<EOF
   663  {
   664    "Version": "2012-10-17",
   665    "Statement": [
   666      {
   667        "Action": "sts:AssumeRole",
   668        "Principal": {
   669          "Service": "lambda.amazonaws.com"
   670        },
   671        "Effect": "Allow",
   672        "Sid": ""
   673      }
   674    ]
   675  }
   676  EOF
   677  }
   678  `
   679  
   680  var testAccAWSLambdaPermissionConfig_withSNS = `
   681  resource "aws_lambda_permission" "with_sns" {
   682      statement_id = "AllowExecutionFromSNS"
   683      action = "lambda:InvokeFunction"
   684      function_name = "${aws_lambda_function.my-func.arn}"
   685      principal = "sns.amazonaws.com"
   686      source_arn = "${aws_sns_topic.default.arn}"
   687  }
   688  
   689  resource "aws_sns_topic" "default" {
   690  	name = "tf-acc-user-updates-topic"
   691  }
   692  
   693  resource "aws_sns_topic_subscription" "lambda" {
   694      topic_arn = "${aws_sns_topic.default.arn}"
   695      protocol  = "lambda"
   696      endpoint  = "${aws_lambda_function.my-func.arn}"
   697  }
   698  
   699  resource "aws_lambda_function" "my-func" {
   700      filename = "test-fixtures/lambdatest.zip"
   701      function_name = "lambda_function_name_perm_sns"
   702      role = "${aws_iam_role.police.arn}"
   703      handler = "exports.handler"
   704      runtime = "nodejs4.3"
   705  }
   706  
   707  resource "aws_iam_role" "police" {
   708      name = "iam_for_lambda_perm_with_sns"
   709      assume_role_policy = <<EOF
   710  {
   711    "Version": "2012-10-17",
   712    "Statement": [
   713      {
   714        "Action": "sts:AssumeRole",
   715        "Principal": {
   716          "Service": "lambda.amazonaws.com"
   717        },
   718        "Effect": "Allow",
   719        "Sid": ""
   720      }
   721    ]
   722  }
   723  EOF
   724  }
   725  `
   726  
   727  var testLambdaPolicy = []byte(`{
   728  	"Version": "2012-10-17",
   729  	"Statement": [
   730  		{
   731  			"Condition": {
   732  				"StringEquals": {"AWS:SourceAccount": "319201112229"},
   733  				"ArnLike":{"AWS:SourceArn":"arn:aws:events:eu-west-1:319201112229:rule/RunDaily"}
   734  			},
   735  			"Action": "lambda:InvokeFunction",
   736  			"Resource": "arn:aws:lambda:eu-west-1:319201112229:function:myCustomFunction",
   737  			"Effect": "Allow",
   738  			"Principal": {"Service":"events.amazonaws.com"},
   739  			"Sid": "36fe77d9-a4ae-13fb-8beb-5dc6821d5291"
   740  		}
   741  	],
   742  	"Id":"default"
   743  }`)