diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index 2ca4532b88..3d0ebc0378 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -573,10 +573,12 @@ in that map, return `BadRequestException` rather than silently discarding or cha | `contentHandling` | `CONVERT_TO_TEXT` base64-encodes a binary request for mapping templates; `CONVERT_TO_BINARY` base64-decodes a text request before sending it | | `connectionType` / `connectionId` | `VPC_LINK` requires `connectionId` to name an existing, available VPC link; an unknown link yields `502` | | `cacheNamespace` / `cacheKeyParameters` | Form the response cache key (see below) | -| `credentials` | Persisted and returned. Floci does not enforce IAM, so the role is not actually assumed | +| `credentials` | Persisted and returned. The role is not assumed, and even with IAM enforcement on neither its trust policy nor its identity policies are checked | Integration responses additionally accept `contentHandling`, applied as an output conversion after response templates. +With IAM enforcement on, an `AWS_PROXY` or `AWS` Lambda integration with no `credentials` invokes the function only when its function policy allows `apigateway.amazonaws.com` to, for the request's execute-api ARN when the statement names a `SourceArn` (`arn:aws:execute-api:::///`). `` is the concrete request path such as `items/42`, not the resource path template `items/{id}`, so a grant for `.../GET/items/42` covers that call, and a greedy `{proxy+}` resource is checked against the full path it matched. `` is the function's Region, taken from the function ARN in the integration URI, and the API's Region when that ARN names none; it differs from the API's for a cross-Region integration, as [Lambda's guide for API Gateway](https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html) specifies. The Lambda authorizer `methodArn` keeps the API's Region. For an `ANY` method, `` is the request's verb, as in a Lambda authorizer's `methodArn`; this was not measured on AWS. A refused call is answered with `500` and `{"message": "Internal server error"}`, shaped by an `API_CONFIGURATION_ERROR` or `DEFAULT_5XX` gateway response when one is set, and the function is not invoked. A call to a function that does not exist is refused the same way; with enforcement off it is still answered with `404`. See [Function policies under IAM enforcement](lambda.md#function-policies-under-iam-enforcement). An integration with `credentials` skips the function-policy check, since AWS authorizes it through that role instead, but Floci does not check the role either: its trust policy for `apigateway.amazonaws.com` and its identity policies for `lambda:InvokeFunction` are not evaluated, so such an integration always invokes the function. REST Lambda authorizers and HTTP and WebSocket API integrations are not checked yet. + ### Binary Payloads Set `binaryMediaTypes` on the RestApi to mark content types as binary. Entries are matched exactly, ignoring any charset parameter; `*/*` is the one wildcard entry, and it covers every content type. A subtype wildcard such as `image/*` is not expanded, matching AWS, which documents only `*/*` and otherwise names one exact media type at a time. A binary request body reaches an `AWS_PROXY` (Lambda) integration base64-encoded with `isBase64Encoded: true`; previously it was read as a UTF-8 string, which corrupted it. For non-proxy integrations, pair `binaryMediaTypes` with `contentHandling` as above. diff --git a/docs/services/iam.md b/docs/services/iam.md index 452c7e7e59..f0dbf954b5 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3039,7 +3039,7 @@ When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` is active, Floci also queries regi - EventBridge event bus policies, the statements `PutPermission` adds, take part the same way for a call on the bus; see [EventBridge](eventbridge.md#event-bus-policies-under-iam-enforcement). - A role's trust policy takes part the same way for `sts:AssumeRole` on the role, with the role as its resource: a trust policy names no `Resource`. It is not consulted for IAM actions on the role, such as `iam:GetRole` or `iam:PassRole`. See [STS trust policy enforcement](sts.md#trust-policy-enforcement). - API Gateway REST API policies are stored but not evaluated. -- A call an AWS service makes to another service's resource on its own behalf, such as SES publishing an event or a notification to an SNS topic, has no IAM principal, so the target's resource policy decides it alone and has to allow the calling service, through `{"Service": ".amazonaws.com"}` or `{"AWS": "*"}`. A target with no policy refuses it. Its request context holds `aws:PrincipalIsAWSService` (`true`), `aws:PrincipalServiceName` and `aws:PrincipalServiceNamesList`, `aws:SourceArn` and `aws:SourceAccount` for the resource whose configuration triggered the call, `aws:ResourceAccount` and `aws:RequestedRegion`, and none of the keys that describe an IAM principal. A publish to an SNS topic from SES also carries `aws:SourceOwner`, the key the SNS Developer Guide lists SES among the services setting, which is what the default topic policy checks, so that policy admits SES acting for the topic owner's account and no other. SES and Lambda, when it reads the code of a Web Function revision from S3, are the services checked this way so far; see [SES IAM enforcement](ses.md#iam-enforcement) and [Lambda Web Functions](lambda-web-functions.md#emulation-behavior). +- A call an AWS service makes to another service's resource on its own behalf, such as SES publishing an event or a notification to an SNS topic, has no IAM principal, so the target's resource policy decides it alone and has to allow the calling service, through `{"Service": ".amazonaws.com"}` or `{"AWS": "*"}`. A target with no policy refuses it. Its request context holds `aws:PrincipalIsAWSService` (`true`), `aws:PrincipalServiceName` and `aws:PrincipalServiceNamesList`, `aws:SourceArn` and `aws:SourceAccount` for the resource whose configuration triggered the call, `aws:ResourceAccount` and `aws:RequestedRegion`, and none of the keys that describe an IAM principal. A publish to an SNS topic from SES also carries `aws:SourceOwner`, the key the SNS Developer Guide lists SES among the services setting, which is what the default topic policy checks, so that policy admits SES acting for the topic owner's account and no other. SES, Lambda when it reads the code of a Web Function revision from S3, and API Gateway REST API Lambda integrations when they invoke a function, are the services checked this way so far; see [SES IAM enforcement](ses.md#iam-enforcement), [Lambda Web Functions](lambda-web-functions.md#emulation-behavior) and [Function policies under IAM enforcement](lambda.md#function-policies-under-iam-enforcement). ### Service control policies (SCPs) diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 6266b2bc5c..e78cd1d98f 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -149,6 +149,25 @@ part in authorizing calls to the function: authorized against the function as its name gives it, as the Service Reference lists the function alone for those actions. - A statement conditioned on `InvokedViaFunctionUrl` does not admit a direct `Invoke`. +- An API Gateway REST API whose `AWS_PROXY` or `AWS` integration names the function invokes it on + its own behalf. The function policy has to allow `lambda:InvokeFunction` to + `apigateway.amazonaws.com`, as `AddPermission --principal apigateway.amazonaws.com` writes it, + and a function with no policy refuses the call. `aws:SourceArn` is the request's execute-api ARN, + `arn:aws:execute-api:::///`, where `` is the + concrete request path such as `items/42` rather than the resource path template `items/{id}`, so + a grant for `.../GET/items/*` covers it. `` is the function's Region, not the API's, when + the two differ, as Lambda's guide for API Gateway specifies; a function named without a Region is + taken to be in the API's. `aws:SourceAccount` is the API's account. + For an `ANY` method, `` is the request's verb, as in a Lambda authorizer's `methodArn`; + this was not measured on AWS. A refused call is answered with `500` and + `{"message": "Internal server error"}`; see [API Gateway](api-gateway.md#integration-settings). + A call to a function that does not exist is refused the same way, since Lambda authorizes a call + before it looks the function up (not measured through API Gateway); with enforcement off it is + still answered with `404` and `Function not found`. An integration that names `credentials` + invokes the function as that role, so the function policy does not decide it; Floci does not + check that role's trust policy or identity policies either, so the call always goes through. + Other services that invoke a function, such as EventBridge rules and Scheduler, event source + mappings and Pipes, are not checked against the function policy. - `aws:PrincipalOrgID` is in the request context for a caller whose account is in an organization, so a grant added with `PrincipalOrgID` admits the callers of that organization and no others. A caller in no organization carries no value for the key, and such a grant then admits none. diff --git a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayExecuteController.java index b09180eef4..ab2e2a8d66 100644 --- a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayExecuteController.java +++ b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayExecuteController.java @@ -27,6 +27,7 @@ import io.floci.aws.core.common.CookieHeaders; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.RequestContext; import io.floci.aws.core.common.ResteasyRequests; +import io.floci.aws.core.common.ServiceCallAuthorizer; import io.floci.aws.core.common.auth.SigV4AuthorizationHeader; import io.floci.aws.services.apigateway.model.ApiGatewayResource; import io.floci.aws.services.apigateway.model.ApiKey; @@ -56,6 +57,7 @@ import io.floci.aws.services.apigatewayv2.websocket.WebSocketConnectionManager; import io.floci.aws.services.elbv2.ElbV2Service; import io.floci.aws.services.elbv2.model.Listener; import io.floci.aws.services.elbv2.model.LoadBalancer; +import io.floci.aws.services.iam.IamPolicyEvaluator.Decision; import io.floci.aws.services.lambda.LambdaArnUtils; import io.floci.aws.services.lambda.LambdaService; import io.floci.aws.services.lambda.model.InvocationType; @@ -151,9 +153,31 @@ public class ApiGatewayExecuteController { private final CloudMapInstanceResolver cloudMapInstanceResolver; private final AwsServiceIntegrationMapper awsServiceIntegrationMapper; private final HttpProxyInvoker httpProxyInvoker; + private final ServiceCallAuthorizer serviceCallAuthorizer; private final ResponseParameterMapper responseParameterMapper = new ResponseParameterMapper(new ContextValueResolver()); + public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, CognitoUserPoolAuthorizer cognitoAuthorizer, + ApiGatewayV2Service apiGatewayV2Service, + LambdaService lambdaService, RegionResolver regionResolver, + ObjectMapper objectMapper, VtlTemplateEngine vtlEngine, + AwsServiceRouter serviceRouter, + WebSocketConnectionManager webSocketConnectionManager, + ElbV2Service elbV2Service, + SqsQueryHandler sqsQueryHandler, + ApiGatewayExecuteRouteContext routeContext, + JwtSignatureVerifier jwtSignatureVerifier, + RequestContext requestContext, + ExecuteApiSigV4Authorizer sigV4Authorizer, RestLambdaAuthorizer restLambdaAuthorizer, + AuthorizerPolicyEvaluator authorizerPolicyEvaluator, + CloudMapInstanceResolver cloudMapInstanceResolver, + HttpProxyInvoker httpProxyInvoker) { + this(apiGatewayService, cognitoAuthorizer, apiGatewayV2Service, lambdaService, regionResolver, objectMapper, + vtlEngine, serviceRouter, webSocketConnectionManager, elbV2Service, sqsQueryHandler, routeContext, + jwtSignatureVerifier, requestContext, sigV4Authorizer, restLambdaAuthorizer, + authorizerPolicyEvaluator, cloudMapInstanceResolver, httpProxyInvoker, null); + } + @Inject public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, CognitoUserPoolAuthorizer cognitoAuthorizer, ApiGatewayV2Service apiGatewayV2Service, @@ -169,7 +193,8 @@ public class ApiGatewayExecuteController { ExecuteApiSigV4Authorizer sigV4Authorizer, RestLambdaAuthorizer restLambdaAuthorizer, AuthorizerPolicyEvaluator authorizerPolicyEvaluator, CloudMapInstanceResolver cloudMapInstanceResolver, - HttpProxyInvoker httpProxyInvoker) { + HttpProxyInvoker httpProxyInvoker, + ServiceCallAuthorizer serviceCallAuthorizer) { this.apiGatewayService = apiGatewayService; this.cognitoAuthorizer = cognitoAuthorizer; this.apiGatewayV2Service = apiGatewayV2Service; @@ -194,6 +219,7 @@ public class ApiGatewayExecuteController { this.authorizerPolicyEvaluator = authorizerPolicyEvaluator; this.cloudMapInstanceResolver = cloudMapInstanceResolver; this.httpProxyInvoker = httpProxyInvoker; + this.serviceCallAuthorizer = serviceCallAuthorizer; } /** Matches an ELBv2 listener ARN (ALB {@code app/} or NLB {@code net/}); group 1 = region. */ @@ -612,6 +638,9 @@ public class ApiGatewayExecuteController { return gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500, "Cannot resolve function from URI: " + integration.getUri()); } + if (!apiGatewayMayInvoke(integration, functionName, region, apiId, stageName, httpMethod, path)) { + return gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500, "Internal server error"); + } String requestId = routeContext.requestId(headers); String eventJson = buildProxyEvent(region, apiId, httpMethod, path, resource.getPath(), @@ -1484,6 +1513,29 @@ public class ApiGatewayExecuteController { return AwsArnUtils.Arn.of("execute-api", arnRegion, regionResolver.getAccountId(), apiId + "/" + stageName + "/" + httpMethod + "/" + normalizedPath).toString(); } + /** + * Whether the function policy lets API Gateway invoke {@code functionName} for this request. The + * source ARN names the API's account, the stage, the request verb and the concrete request path, + * in the function's Region rather than the API's, as Lambda checks it for a cross-Region API; a + * function reference without a Region is taken to be in the API's. An integration with + * {@code credentials} invokes as that role instead, so the function policy is not consulted for it. + */ + private boolean apiGatewayMayInvoke(Integration integration, String functionName, String apiRegion, + String apiId, String stageName, String httpMethod, String requestPath) { + if (serviceCallAuthorizer == null + || (integration.getCredentials() != null && !integration.getCredentials().isBlank())) { + return true; + } + String functionRegion = LambdaArnUtils.resolve(functionName).region(); + String sourceArn = buildMethodArn(functionRegion != null ? functionRegion : apiRegion, apiId, stageName, + httpMethod, requestPath); + AwsArnUtils.Arn source = AwsArnUtils.parse(sourceArn); + String functionArn = LambdaArnUtils.functionArn(functionName, source.partition(), source.region(), + source.accountId()); + return serviceCallAuthorizer.authorize("apigateway", "lambda:InvokeFunction", functionArn, sourceArn, + source.accountId()) == Decision.ALLOW; + } + /** * Extracts function name from integration URI like * {@code arn:aws:apigateway:...:lambda:path/2015-03-31/functions/{fnArn}/invocations}. @@ -1980,6 +2032,11 @@ public class ApiGatewayExecuteController { throw new AwsException("InvalidParameterValueException", "Cannot resolve Lambda function name from URI: " + integration.getUri(), 400); } + if (!apiGatewayMayInvoke(integration, functionName, region, scope.apiId(), stageName, httpMethod, + path)) { + return gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500, + "Internal server error"); + } byte[] payload = transformedBody != null ? transformedBody.getBytes(StandardCharsets.UTF_8) : new byte[0]; InvokeResult invokeResult = lambdaService.invokeTarget(region, functionName, payload, InvocationType.RequestResponse); String lambdaResponseBody = invokeResult.getPayload() != null diff --git a/src/test/java/io/floci/aws/services/apigateway/ApiGatewayLambdaFixtures.java b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayLambdaFixtures.java new file mode 100644 index 0000000000..c1682b1114 --- /dev/null +++ b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayLambdaFixtures.java @@ -0,0 +1,72 @@ +package io.floci.aws.services.apigateway; + +import io.restassured.http.ContentType; +import io.restassured.specification.RequestSpecification; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; + +import static io.floci.aws.testing.EnforcementFixtures.auth; +import static io.restassured.RestAssured.given; + +/** + * A deployed REST API whose resource at a given path has one method integrated with a Lambda + * function, served on the {@code test} stage, and the signed requests that build it. + */ +final class ApiGatewayLambdaFixtures { + + static final String REGION = "us-east-1"; + static final String ACCOUNT = "000000000000"; + + private ApiGatewayLambdaFixtures() { + } + + static String createLambdaRestApi(String resourcePath, String httpMethod, String type, String functionArn, + String credentials) { + String apiId = apiGateway() + .body("{\"name\":\"lambda-integration-" + UUID.randomUUID().toString().substring(0, 8) + "\"}") + .post("/restapis").then().statusCode(201).extract().path("id"); + String resourceId = apiGateway().get("/restapis/" + apiId + "/resources") + .then().statusCode(200).extract().path("item[0].id"); + for (String pathPart : resourcePath.substring(1).split("/")) { + resourceId = apiGateway().body(Map.of("pathPart", pathPart)) + .post("/restapis/" + apiId + "/resources/" + resourceId) + .then().statusCode(201).extract().path("id"); + } + String methodPath = "/restapis/" + apiId + "/resources/" + resourceId + "/methods/" + httpMethod; + apiGateway().body("{\"authorizationType\":\"NONE\"}").put(methodPath).then().statusCode(201); + + Map integration = new LinkedHashMap<>(); + integration.put("type", type); + integration.put("httpMethod", "POST"); + integration.put("uri", "arn:aws:apigateway:" + REGION + ":lambda:path/2015-03-31/functions/" + + functionArn + "/invocations"); + if (credentials != null) { + integration.put("credentials", credentials); + } + apiGateway().body(integration).put(methodPath + "/integration").then().statusCode(201); + if ("AWS".equals(type)) { + apiGateway().body("{\"selectionPattern\":\"\"}") + .put(methodPath + "/integration/responses/200").then().statusCode(201); + } + + String deploymentId = apiGateway().body("{}").post("/restapis/" + apiId + "/deployments") + .then().statusCode(201).extract().path("id"); + apiGateway().body("{\"stageName\":\"test\",\"deploymentId\":\"" + deploymentId + "\"}") + .post("/restapis/" + apiId + "/stages").then().statusCode(201); + return apiId; + } + + static RequestSpecification apiGateway() { + return signed("apigateway").contentType(ContentType.JSON); + } + + static RequestSpecification signed(String service) { + return signed(service, REGION); + } + + static RequestSpecification signed(String service, String region) { + return given().header("Authorization", auth(ACCOUNT, region, service)); + } +} diff --git a/src/test/java/io/floci/aws/services/apigateway/ApiGatewayLambdaMissingFunctionIntegrationTest.java b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayLambdaMissingFunctionIntegrationTest.java new file mode 100644 index 0000000000..a3a459bcd8 --- /dev/null +++ b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayLambdaMissingFunctionIntegrationTest.java @@ -0,0 +1,51 @@ +package io.floci.aws.services.apigateway; + +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.UUID; + +import static io.floci.aws.services.apigateway.ApiGatewayLambdaFixtures.ACCOUNT; +import static io.floci.aws.services.apigateway.ApiGatewayLambdaFixtures.REGION; +import static io.floci.aws.services.apigateway.ApiGatewayLambdaFixtures.apiGateway; +import static io.floci.aws.services.apigateway.ApiGatewayLambdaFixtures.createLambdaRestApi; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +/** + * With IAM enforcement off, the function policy is not consulted, so a REST API Lambda proxy + * integration naming a function that does not exist is answered with 404 and + * {@code Function not found}. + */ +@QuarkusTest +class ApiGatewayLambdaMissingFunctionIntegrationTest { + + private String apiId; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @AfterEach + void deleteApi() { + if (apiId != null) { + apiGateway().delete("/restapis/" + apiId).then().statusCode(202); + } + } + + @Test + void proxyIntegrationToAMissingFunctionAnswersFunctionNotFound() { + String functionArn = "arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:missing-" + + UUID.randomUUID().toString().substring(0, 8); + apiId = createLambdaRestApi("/items", "GET", "AWS_PROXY", functionArn, null); + + given().when().get("/execute-api/" + apiId + "/test/items") + .then() + .statusCode(404) + .body("message", equalTo("Function not found: " + functionArn)); + } +} diff --git a/src/test/java/io/floci/aws/services/apigateway/ApiGatewayLambdaPermissionIntegrationTest.java b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayLambdaPermissionIntegrationTest.java new file mode 100644 index 0000000000..badec874af --- /dev/null +++ b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayLambdaPermissionIntegrationTest.java @@ -0,0 +1,267 @@ +package io.floci.aws.services.apigateway; + +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.services.lambda.LambdaService; +import io.floci.aws.services.lambda.model.InvocationType; +import io.floci.aws.services.lambda.model.InvokeResult; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.quarkus.test.junit.mockito.InjectSpy; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; + +import static io.floci.aws.services.apigateway.ApiGatewayLambdaFixtures.ACCOUNT; +import static io.floci.aws.services.apigateway.ApiGatewayLambdaFixtures.REGION; +import static io.floci.aws.services.apigateway.ApiGatewayLambdaFixtures.apiGateway; +import static io.floci.aws.services.apigateway.ApiGatewayLambdaFixtures.createLambdaRestApi; +import static io.floci.aws.services.apigateway.ApiGatewayLambdaFixtures.signed; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +/** + * With IAM enforcement on, a REST API Lambda integration invokes the function only when the + * function policy allows apigateway.amazonaws.com to, for the request's execute-api ARN when the + * grant names one. That ARN carries the concrete request path and the function's Region. A refused + * call is answered with the gateway's 500 "Internal server error" and never reaches the function. + * An integration that names {@code credentials} invokes as that role, so the function policy does + * not decide it. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class ApiGatewayLambdaPermissionIntegrationTest { + + private static final String OTHER_REGION = "us-west-2"; + private static final String PROXY_RESPONSE = "{\"statusCode\":200,\"body\":\"invoked\"}"; + + @InjectSpy + LambdaService lambdaService; + + private final Deque cleanup = new ArrayDeque<>(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void stubInvocation() { + clearInvocations(lambdaService); + doReturn(new InvokeResult(200, null, PROXY_RESPONSE.getBytes(StandardCharsets.UTF_8), null, "req")) + .when(lambdaService).invokeTarget(any(), any(), any(), eq(InvocationType.RequestResponse)); + } + + @AfterEach + void deleteWhatTheTestCreated() { + while (!cleanup.isEmpty()) { + cleanup.pop().run(); + } + } + + @Test + void proxyIntegrationToAFunctionWithoutAPolicyAnswersInternalServerError() { + String functionArn = createFunction("no-policy-" + suffix()); + String apiId = createApi("AWS_PROXY", functionArn, null); + + execute(apiId) + .statusCode(500) + .body("message", equalTo("Internal server error")); + + verify(lambdaService, never()).invokeTarget(any(), any(), any(), any()); + } + + @Test + void proxyIntegrationGrantedForTheMethodInvokesTheFunction() { + String functionArn = createFunction("granted-" + suffix()); + String apiId = createApi("AWS_PROXY", functionArn, null); + addPermission(functionArn, "arn:aws:execute-api:" + REGION + ":" + ACCOUNT + ":" + apiId + "/*/GET/items"); + + execute(apiId).statusCode(200).body(equalTo("invoked")); + + verify(lambdaService).invokeTarget(any(), eq(functionArn), any(), eq(InvocationType.RequestResponse)); + } + + @Test + void grantForAnotherApiDoesNotCoverThisOne() { + String functionArn = createFunction("other-api-" + suffix()); + String apiId = createApi("AWS_PROXY", functionArn, null); + addPermission(functionArn, "arn:aws:execute-api:" + REGION + ":" + ACCOUNT + ":otherapi/*/GET/items"); + + execute(apiId).statusCode(500); + + verify(lambdaService, never()).invokeTarget(any(), any(), any(), any()); + } + + @Test + void nonProxyIntegrationToAFunctionWithoutAPolicyAnswersInternalServerError() { + String functionArn = createFunction("non-proxy-" + suffix()); + String apiId = createApi("AWS", functionArn, null); + + execute(apiId) + .statusCode(500) + .body("message", equalTo("Internal server error")); + + verify(lambdaService, never()).invokeTarget(any(), any(), any(), any()); + } + + @Test + void anyMethodIsAuthorizedForTheRequestVerb() { + String functionArn = createFunction("any-method-" + suffix()); + String apiId = createApi("/items", "ANY", "AWS_PROXY", functionArn, null); + addPermission(functionArn, "arn:aws:execute-api:" + REGION + ":" + ACCOUNT + ":" + apiId + "/*/GET/items"); + + execute(apiId).statusCode(200).body(equalTo("invoked")); + given().when().delete("/execute-api/" + apiId + "/test/items").then().statusCode(500); + + verify(lambdaService).invokeTarget(any(), eq(functionArn), any(), eq(InvocationType.RequestResponse)); + } + + @Test + void proxyIntegrationToAMissingFunctionAnswersInternalServerError() { + String functionArn = "arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:missing-" + suffix(); + String apiId = createApi("AWS_PROXY", functionArn, null); + + execute(apiId) + .statusCode(500) + .body("message", equalTo("Internal server error")); + + verify(lambdaService, never()).invokeTarget(any(), any(), any(), any()); + } + + @Test + void integrationWithCredentialsIsNotDecidedByTheFunctionPolicy() { + String functionArn = createFunction("role-invoked-" + suffix()); + String apiId = createApi("AWS_PROXY", functionArn, "arn:aws:iam::" + ACCOUNT + ":role/apigateway-invoke"); + + execute(apiId).statusCode(200); + + verify(lambdaService).invokeTarget(any(), eq(functionArn), any(), eq(InvocationType.RequestResponse)); + } + + @Test + void grantForTheConcreteRequestPathCoversAPathParameterResource() { + String functionArn = createFunction("path-param-" + suffix()); + String apiId = createApi("/items/{id}", "GET", "AWS_PROXY", functionArn, null); + addPermission(functionArn, "arn:aws:execute-api:" + REGION + ":" + ACCOUNT + ":" + apiId + "/*/GET/items/42"); + + execute(apiId, "/items/42").statusCode(200).body(equalTo("invoked")); + + verify(lambdaService).invokeTarget(any(), eq(functionArn), any(), eq(InvocationType.RequestResponse)); + } + + @Test + void grantForAnotherPathParameterValueDoesNotCoverThisOne() { + String functionArn = createFunction("other-item-" + suffix()); + String apiId = createApi("/items/{id}", "GET", "AWS_PROXY", functionArn, null); + addPermission(functionArn, "arn:aws:execute-api:" + REGION + ":" + ACCOUNT + ":" + apiId + "/*/GET/items/7"); + + execute(apiId, "/items/42").statusCode(500); + + verify(lambdaService, never()).invokeTarget(any(), any(), any(), any()); + } + + @Test + void grantForTheConcreteRequestPathCoversAGreedyResource() { + String functionArn = createFunction("greedy-" + suffix()); + String apiId = createApi("/items/{proxy+}", "GET", "AWS_PROXY", functionArn, null); + addPermission(functionArn, "arn:aws:execute-api:" + REGION + ":" + ACCOUNT + ":" + apiId + "/*/GET/items/a/b"); + + execute(apiId, "/items/a/b").statusCode(200).body(equalTo("invoked")); + + verify(lambdaService).invokeTarget(any(), eq(functionArn), any(), eq(InvocationType.RequestResponse)); + } + + @Test + void crossRegionFunctionIsAuthorizedInTheFunctionsRegion() { + String functionArn = createFunction(OTHER_REGION, "cross-region-" + suffix()); + String apiId = createApi("AWS_PROXY", functionArn, null); + addPermission(functionArn, "arn:aws:execute-api:" + OTHER_REGION + ":" + ACCOUNT + ":" + apiId + "/*/GET/items"); + + execute(apiId).statusCode(200).body(equalTo("invoked")); + + verify(lambdaService).invokeTarget(any(), eq(functionArn), any(), eq(InvocationType.RequestResponse)); + } + + @Test + void crossRegionGrantInTheApisRegionDoesNotCoverTheCall() { + String functionArn = createFunction(OTHER_REGION, "api-region-" + suffix()); + String apiId = createApi("AWS_PROXY", functionArn, null); + addPermission(functionArn, "arn:aws:execute-api:" + REGION + ":" + ACCOUNT + ":" + apiId + "/*/GET/items"); + + execute(apiId).statusCode(500); + + verify(lambdaService, never()).invokeTarget(any(), any(), any(), any()); + } + + private static String suffix() { + return UUID.randomUUID().toString().substring(0, 8); + } + + private static ValidatableResponse execute(String apiId) { + return execute(apiId, "/items"); + } + + private static ValidatableResponse execute(String apiId, String path) { + return given().when().get("/execute-api/" + apiId + "/test" + path).then(); + } + + private String createApi(String type, String functionArn, String credentials) { + return createApi("/items", "GET", type, functionArn, credentials); + } + + private String createApi(String resourcePath, String httpMethod, String type, String functionArn, + String credentials) { + String apiId = createLambdaRestApi(resourcePath, httpMethod, type, functionArn, credentials); + cleanup.push(() -> apiGateway().delete("/restapis/" + apiId).then().statusCode(202)); + return apiId; + } + + private String createFunction(String name) { + return createFunction(REGION, name); + } + + private String createFunction(String region, String name) { + lambda(region) + .body(""" + {"FunctionName":"%s","Runtime":"nodejs20.x","Handler":"index.handler", + "Role":"arn:aws:iam::%s:role/lambda-role"}""".formatted(name, ACCOUNT)) + .when() + .post("/2015-03-31/functions") + .then() + .statusCode(201); + cleanup.push(() -> lambda(region).delete("/2015-03-31/functions/{name}", name).then().statusCode(204)); + return "arn:aws:lambda:" + region + ":" + ACCOUNT + ":function:" + name; + } + + private static void addPermission(String functionArn, String sourceArn) { + Map request = new LinkedHashMap<>(); + request.put("StatementId", "s-" + suffix()); + request.put("Action", "lambda:InvokeFunction"); + request.put("Principal", "apigateway.amazonaws.com"); + request.put("SourceArn", sourceArn); + lambda(AwsArnUtils.parse(functionArn).region()).body(request) + .post("/2015-03-31/functions/{name}/policy", functionArn).then().statusCode(201); + } + + private static RequestSpecification lambda(String region) { + return signed("lambda", region).contentType("application/json"); + } +}