fix(apigateway): merge OpenAPI imports in PutRestApi (#4570)

* fix(apigateway): merge OpenAPI imports in PutRestApi

Signed-off-by: zhanglangning <zln1905391059@163.com>

* fix(apigateway): preserve authorization across API merges

Signed-off-by: zhanglangning <zln1905391059@163.com>

* fix(apigateway): preserve authorization across API merges

Signed-off-by: zhanglangning <zln1905391059@163.com>

* fix(apigateway): reject invalid PutRestApi modes

Signed-off-by: boulea7 <zln1905391059@163.com>

---------

Signed-off-by: zhanglangning <zln1905391059@163.com>
Signed-off-by: boulea7 <zln1905391059@163.com>
This commit is contained in:
Langning Zhang authored and GitHub committed 2026-09-29 07:37:44 -04:00
1 parent 2ec5300029
commit cfc9a440c1
8 files changed
+1355 -31

No files matched your search

@@ -9,6 +9,8 @@ import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.Map;
@@ -100,6 +102,112 @@ class ApiGatewayCognitoAuthorizerIntegrationTest {
}
}
@ParameterizedTest
@ValueSource(strings = {"", ", \"providerARNs\": null"})
void mergingPartialCognitoAuthorizerKeepsRetainedMethodAuthorized(String providerArnsField)
throws Exception {
UserPool pool = cognitoService.createUserPool(Map.of("PoolName", "merge-pool"), "us-east-1");
String accessToken = (String) issueTokens(pool).get("AccessToken");
String apiId = given().contentType(ContentType.JSON)
.body(Map.of("name", "cognito-merge-test"))
.post("/restapis").then().statusCode(201).extract().path("id");
try {
String rootId = given().get("/restapis/" + apiId + "/resources")
.then().statusCode(200).extract().path("item[0].id");
String securedId = createResource(apiId, rootId, "secured");
String authorizerId = createAuthorizer(apiId, "Guard", pool.getArn());
configureMethod(apiId, securedId, authorizerId, "COGNITO_USER_POOLS", List.of());
given().contentType(ContentType.JSON).body(Map.of("stageName", "before"))
.post("/restapis/" + apiId + "/deployments").then().statusCode(201);
String beforePath = "/execute-api/" + apiId + "/before/secured";
given().header("X-Id-Token", "Bearer " + accessToken)
.get(beforePath).then().statusCode(200);
given().contentType(ContentType.JSON).queryParam("mode", "merge")
.body(partialCognitoSpec(providerArnsField))
.put("/restapis/" + apiId).then().statusCode(200);
given().contentType(ContentType.JSON).body(Map.of("stageName", "after"))
.post("/restapis/" + apiId + "/deployments").then().statusCode(201);
String actualAuthorizerId = given().get("/restapis/" + apiId + "/authorizers/" + authorizerId)
.then().statusCode(200).extract().path("id");
assertEquals(authorizerId, actualAuthorizerId);
given().header("X-Id-Token", "Bearer " + accessToken)
.get("/execute-api/" + apiId + "/after/secured").then().statusCode(200);
List<String> retainedArns = given().get("/restapis/" + apiId + "/authorizers/" + authorizerId)
.then().statusCode(200).extract().path("providerARNs");
assertEquals(List.of(pool.getArn()), retainedArns);
} finally {
given().delete("/restapis/" + apiId).then().statusCode(202);
}
}
@Test
void explicitCognitoPoolListsReplacePriorPools() throws Exception {
UserPool oldPool = cognitoService.createUserPool(Map.of("PoolName", "old-merge-pool"), "us-east-1");
UserPool newPool = cognitoService.createUserPool(Map.of("PoolName", "new-merge-pool"), "us-east-1");
String oldToken = (String) issueTokens(oldPool).get("AccessToken");
String newToken = (String) issueTokens(newPool).get("AccessToken");
String apiId = given().contentType(ContentType.JSON)
.body(Map.of("name", "cognito-pool-replacement-test"))
.post("/restapis").then().statusCode(201).extract().path("id");
try {
String rootId = given().get("/restapis/" + apiId + "/resources")
.then().statusCode(200).extract().path("item[0].id");
String securedId = createResource(apiId, rootId, "secured");
String authorizerId = createAuthorizer(apiId, "Guard", oldPool.getArn());
configureMethod(apiId, securedId, authorizerId, "COGNITO_USER_POOLS", List.of());
given().contentType(ContentType.JSON).body(Map.of("stageName", "before"))
.post("/restapis/" + apiId + "/deployments").then().statusCode(201);
given().header("X-Id-Token", "Bearer " + oldToken)
.get("/execute-api/" + apiId + "/before/secured").then().statusCode(200);
String newArns = MAPPER.writeValueAsString(List.of(newPool.getArn()));
given().contentType(ContentType.JSON).queryParam("mode", "merge")
.body(partialCognitoSpec(", \"providerARNs\": " + newArns))
.put("/restapis/" + apiId).then().statusCode(200);
given().contentType(ContentType.JSON).body(Map.of("stageName", "new-pool"))
.post("/restapis/" + apiId + "/deployments").then().statusCode(201);
given().header("X-Id-Token", "Bearer " + oldToken)
.get("/execute-api/" + apiId + "/new-pool/secured").then().statusCode(401);
given().header("X-Id-Token", "Bearer " + newToken)
.get("/execute-api/" + apiId + "/new-pool/secured").then().statusCode(200);
List<String> replacementArns = given().get("/restapis/" + apiId + "/authorizers/" + authorizerId)
.then().statusCode(200).extract().path("providerARNs");
assertEquals(List.of(newPool.getArn()), replacementArns);
given().contentType(ContentType.JSON).queryParam("mode", "merge")
.body(partialCognitoSpec(", \"providerARNs\": []"))
.put("/restapis/" + apiId).then().statusCode(200);
given().contentType(ContentType.JSON).body(Map.of("stageName", "empty-pools"))
.post("/restapis/" + apiId + "/deployments").then().statusCode(201);
given().header("X-Id-Token", "Bearer " + newToken)
.get("/execute-api/" + apiId + "/empty-pools/secured").then().statusCode(401);
} finally {
given().delete("/restapis/" + apiId).then().statusCode(202);
}
}
private static String partialCognitoSpec(String providerArnsField) {
return """
{
"openapi": "3.0.1",
"info": {"title": "Partial Cognito", "version": "2"},
"components": {"securitySchemes": {
"Guard": {
"type": "apiKey", "name": "X-Id-Token", "in": "header",
"x-amazon-apigateway-authorizer": {
"type": "cognito_user_pools"%s
}
}
}},
"paths": {"/added": {"get": {
"x-amazon-apigateway-integration": {"type": "MOCK"}
}}}
}
""".formatted(providerArnsField);
}
private Map<String, Object> issueTokens(UserPool pool) {
String username = "user-" + UUID.randomUUID();
cognitoService.adminCreateUser(pool.getId(), username,
@@ -477,7 +477,6 @@ class ApiGatewayOpenApiImportTest {
@Test
@Order(52)
void putRestApi_modeMergeAccepted() throws Exception {
// mode=merge is accepted (treated as overwrite — merge semantics not yet implemented)
String apiBody = given()
.contentType(ContentType.JSON)
.body("{\"name\": \"MergeTest\"}")
@@ -0,0 +1,653 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@QuarkusTest
class ApiGatewayPutRestApiMergeAuthorizationTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String AUTHORIZER_FUNCTION = "deniedAuth";
private static final String AUTHORIZER_URI = "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/"
+ "arn:aws:lambda:us-east-1:000000000000:function:" + AUTHORIZER_FUNCTION + "/invocations";
private static final String REPLACEMENT_FUNCTION = "replacementAuth";
private static final String REPLACEMENT_URI = "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/"
+ "arn:aws:lambda:us-east-1:000000000000:function:" + REPLACEMENT_FUNCTION + "/invocations";
private static final String ORIGINAL_SPEC = """
{
"openapi": "3.0.1",
"info": {"title": "Protected", "version": "1"},
"components": {"securitySchemes": {
"Guard": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authorizer": {
"type": "token", "authorizerUri": "%s"
}
}
}},
"paths": {"/protected": {"get": {
"security": [{"Guard": []}],
"x-amazon-apigateway-integration": {"type": "MOCK"}
}}}
}
""".formatted(AUTHORIZER_URI);
private static final String MISSING_URI_SPEC = """
{
"openapi": "3.0.1",
"info": {"title": "MissingUri", "version": "1"},
"components": {"securitySchemes": {
"Guard": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authorizer": {"type": "token"}
}
}},
"paths": {"/protected": {"get": {
"security": [{"Guard": []}],
"x-amazon-apigateway-integration": {"type": "MOCK"}
}}}
}
""";
private static final String PARTIAL_AUTHORIZER_SPEC = """
{
"openapi": "3.0.1",
"info": {"title": "PartialAuthorizer", "version": "2"},
"components": {"securitySchemes": {
"Guard": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authorizer": {"type": "token"%s}
}
}},
"paths": {"/added": {"get": {
"x-amazon-apigateway-integration": {"type": "MOCK"}
}}}
}
""";
private static final String REPLACEMENT_URI_SPEC = """
{
"openapi": "3.0.1",
"info": {"title": "ReplacementUri", "version": "2"},
"components": {"securitySchemes": {
"Guard": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authorizer": {"type": "token", "authorizerUri": "%s"}
}
}},
"paths": {"/added": {"get": {
"x-amazon-apigateway-integration": {"type": "MOCK"}
}}}
}
""".formatted(REPLACEMENT_URI);
private static final String RETAINED_SCHEME_SPEC = """
{
"openapi": "3.0.1",
"info": {"title": "RetainedScheme", "version": "2"},
"paths": {"/protected": {"get": {
"security": [{"Guard": []}],
"x-amazon-apigateway-integration": {"type": "MOCK"}
}}}
}
""";
private static final String ROOT_SECURITY_SPEC = """
{
"openapi": "3.0.1",
"info": {"title": "RootSecurity", "version": "2"},
"security": [{"Guard": []}],
"paths": {"/protected": {"get": {
"x-amazon-apigateway-integration": {"type": "MOCK"}
}}}
}
""";
private static final String NO_SECURITY_SPEC = """
{
"openapi": "3.0.1",
"info": {"title": "NoSecurity", "version": "2"},
"paths": {"/protected": {"get": {
"x-amazon-apigateway-integration": {"type": "MOCK"}
}}}
}
""";
private static final String EMPTY_SECURITY_SPEC = """
{
"openapi": "3.0.1",
"info": {"title": "EmptySecurity", "version": "3"},
"security": [{"Guard": []}],
"paths": {"/protected": {"get": {
"security": [],
"x-amazon-apigateway-integration": {"type": "MOCK"}
}}}
}
""";
private static final String COGNITO_SPEC = """
{
"openapi": "3.0.1",
"info": {"title": "CognitoProtected", "version": "1"},
"components": {"securitySchemes": {
"Guard": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authorizer": {
"type": "cognito_user_pools",
"providerARNs": ["arn:aws:cognito-idp:us-east-1:000000000000:userpool/us-east-1_ABC123"]
}
}
}},
"paths": {"/protected": {"get": {
"security": [{"Guard": []}],
"x-amazon-apigateway-integration": {"type": "MOCK"}
}}}
}
""";
private static final String COGNITO_TYPE_REPLACEMENT_SPEC = """
{
"openapi": "3.0.1",
"info": {"title": "CognitoReplacement", "version": "2"},
"components": {"securitySchemes": {
"Guard": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authorizer": {
"type": "cognito_user_pools",
"providerARNs": ["arn:aws:cognito-idp:us-east-1:000000000000:userpool/us-east-1_ABC123"]
}
}
}},
"paths": {"/added": {"get": {
"x-amazon-apigateway-integration": {"type": "MOCK"}
}}}
}
""";
private static final String LAMBDA_TYPE_REPLACEMENT_SPEC = """
{
"openapi": "3.0.1",
"info": {"title": "LambdaReplacement", "version": "2"},
"components": {"securitySchemes": {
"Guard": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authorizer": {
"type": "token", "authorizerUri": "%s"
}
}
}},
"paths": {"/added": {"get": {
"x-amazon-apigateway-integration": {"type": "MOCK"}
}}}
}
""".formatted(AUTHORIZER_URI);
private static final String EXPLICIT_SCHEME_SPEC = """
{
"openapi": "3.0.1",
"info": {"title": "ExplicitScheme", "version": "2"},
"components": {"securitySchemes": {
"Guard": {
"type": "apiKey", "name": "Authorization", "in": "header"%s
}
}},
"paths": {"/protected": {"get": {
"security": [{"Guard": []}],
"x-amazon-apigateway-integration": {"type": "MOCK"}
}}}
}
""";
private static final byte[] DENY_POLICY = """
{"principalId":"blocked","policyDocument":{"Statement":[{"Effect":"Deny"}]}}
""".getBytes(StandardCharsets.UTF_8);
private static final byte[] ALLOW_POLICY = """
{"principalId":"allowed","policyDocument":{"Statement":[{"Effect":"Allow"}]}}
""".getBytes(StandardCharsets.UTF_8);
@InjectMock
LambdaService lambdaService;
@ParameterizedTest
@ValueSource(strings = {"", ", \"authorizerUri\": null"})
void retainedMethodStaysDeniedWhenSameNameAuthorizerHasNoNewUri(String uriFragment) throws Exception {
String apiId = importApi();
try {
denyAuthorizerRequests();
String methodPath = methodPath(apiId);
String authorizerId = getJson(methodPath).path("authorizerId").asText();
deploy(apiId, "before");
assertEquals(403, invoke(apiId, "before"));
verifyDenyInvocations(1);
merge(apiId, PARTIAL_AUTHORIZER_SPEC.formatted(uriFragment));
deploy(apiId, "after");
int afterStatus = invoke(apiId, "after");
JsonNode method = getJson(methodPath(apiId));
JsonNode authorizer = getJson("/restapis/" + apiId + "/authorizers/" + authorizerId);
assertAll(
() -> assertEquals(403, afterStatus),
() -> assertEquals("CUSTOM", method.path("authorizationType").asText()),
() -> assertEquals(authorizerId, method.path("authorizerId").asText()),
() -> assertEquals(AUTHORIZER_URI, authorizer.path("authorizerUri").asText(null)),
() -> verifyDenyInvocations(2));
} finally {
given().delete("/restapis/" + apiId).then().statusCode(202);
}
}
@Test
void boundCustomAuthorizerWithoutUriDoesNotExecuteIntegration() throws Exception {
String apiId = importApi(MISSING_URI_SPEC);
try {
JsonNode method = getJson(methodPath(apiId));
JsonNode authorizer = getJson("/restapis/" + apiId + "/authorizers/"
+ method.path("authorizerId").asText());
assertAll(
() -> assertEquals("CUSTOM", method.path("authorizationType").asText()),
() -> assertTrue(!method.path("authorizerId").asText().isBlank()),
() -> assertTrue(authorizer.path("authorizerUri").isMissingNode()
|| authorizer.path("authorizerUri").isNull()));
deploy(apiId, "missing-uri");
assertEquals(500, invoke(apiId, "missing-uri"));
verifyNoInteractions(lambdaService);
} finally {
given().delete("/restapis/" + apiId).then().statusCode(202);
}
}
@Test
void boundCustomMethodDoesNotInvokeCognitoAuthorizerWithLambdaUri() throws Exception {
String apiId = importApi(COGNITO_SPEC);
try {
String methodPath = methodPath(apiId);
String authorizerId = getJson(methodPath).path("authorizerId").asText();
given().contentType(ContentType.JSON)
.body(Map.of("patchOperations", List.of(Map.of(
"op", "replace", "path", "/authorizerUri", "value", AUTHORIZER_URI))))
.patch("/restapis/" + apiId + "/authorizers/" + authorizerId)
.then().statusCode(200);
given().contentType(ContentType.JSON)
.body(Map.of("patchOperations", List.of(Map.of(
"op", "replace", "path", "/authorizationType", "value", "CUSTOM"))))
.patch(methodPath).then().statusCode(200);
JsonNode method = getJson(methodPath);
JsonNode authorizer = getJson("/restapis/" + apiId + "/authorizers/" + authorizerId);
assertAll(
() -> assertEquals("CUSTOM", method.path("authorizationType").asText()),
() -> assertEquals(authorizerId, method.path("authorizerId").asText()),
() -> assertEquals("COGNITO_USER_POOLS", authorizer.path("type").asText()),
() -> assertEquals(AUTHORIZER_URI, authorizer.path("authorizerUri").asText()));
when(lambdaService.invoke(eq("us-east-1"), eq(AUTHORIZER_FUNCTION), any(byte[].class),
eq(InvocationType.RequestResponse)))
.thenReturn(new InvokeResult(200, null, ALLOW_POLICY, null, "authorizer-request"));
deploy(apiId, "mismatched-type");
int status = invoke(apiId, "mismatched-type");
assertAll(
() -> assertEquals(500, status),
() -> verifyNoInteractions(lambdaService));
} finally {
given().delete("/restapis/" + apiId).then().statusCode(202);
}
}
@Test
void replacedMethodStaysDeniedWhenSecurityReferencesRetainedScheme() throws Exception {
String apiId = importApi();
try {
denyAuthorizerRequests();
String authorizerId = getJson(methodPath(apiId)).path("authorizerId").asText();
deploy(apiId, "before");
assertEquals(403, invoke(apiId, "before"));
verifyDenyInvocations(1);
merge(apiId, RETAINED_SCHEME_SPEC);
deploy(apiId, "after");
int afterStatus = invoke(apiId, "after");
JsonNode method = getJson(methodPath(apiId));
assertAll(
() -> assertEquals(403, afterStatus),
() -> assertEquals("CUSTOM", method.path("authorizationType").asText()),
() -> assertEquals(authorizerId, method.path("authorizerId").asText()),
() -> verifyDenyInvocations(2));
} finally {
given().delete("/restapis/" + apiId).then().statusCode(202);
}
}
@Test
void defaultMergeResolvesRetainedSchemeFromRootSecurity() throws Exception {
String apiId = importApi();
try {
denyAuthorizerRequests();
String authorizerId = getJson(methodPath(apiId)).path("authorizerId").asText();
putSpec(apiId, null, ROOT_SECURITY_SPEC);
deploy(apiId, "after");
int afterStatus = invoke(apiId, "after");
JsonNode method = getJson(methodPath(apiId));
assertAll(
() -> assertEquals(403, afterStatus),
() -> assertEquals("CUSTOM", method.path("authorizationType").asText()),
() -> assertEquals(authorizerId, method.path("authorizerId").asText()),
() -> verifyDenyInvocations(1));
} finally {
given().delete("/restapis/" + apiId).then().statusCode(202);
}
}
@Test
void incomingAuthorizerUriReplacesRetainedUri() throws Exception {
String apiId = importApi();
try {
denyAuthorizerRequests();
denyAuthorizerRequests(REPLACEMENT_FUNCTION);
String authorizerId = getJson(methodPath(apiId)).path("authorizerId").asText();
deploy(apiId, "before");
assertEquals(403, invoke(apiId, "before"));
verifyDenyInvocations(1);
merge(apiId, REPLACEMENT_URI_SPEC);
deploy(apiId, "after");
int afterStatus = invoke(apiId, "after");
JsonNode authorizer = getJson("/restapis/" + apiId + "/authorizers/" + authorizerId);
assertAll(
() -> assertEquals(403, afterStatus),
() -> assertEquals(REPLACEMENT_URI, authorizer.path("authorizerUri").asText(null)),
() -> verifyDenyInvocations(1),
() -> verifyDenyInvocations(REPLACEMENT_FUNCTION, 1));
} finally {
given().delete("/restapis/" + apiId).then().statusCode(202);
}
}
@Test
void replacementWithoutSecurityAndExplicitEmptySecurityRemainPublic() throws Exception {
String apiId = importApi();
try {
denyAuthorizerRequests();
merge(apiId, NO_SECURITY_SPEC);
JsonNode noSecurityMethod = getJson(methodPath(apiId));
deploy(apiId, "no-security");
assertAll(
() -> assertEquals("NONE", noSecurityMethod.path("authorizationType").asText()),
() -> assertEquals(200, invoke(apiId, "no-security")),
() -> verifyDenyInvocations(0));
merge(apiId, EMPTY_SECURITY_SPEC);
JsonNode emptySecurityMethod = getJson(methodPath(apiId));
deploy(apiId, "empty-security");
assertAll(
() -> assertEquals("NONE", emptySecurityMethod.path("authorizationType").asText()),
() -> assertEquals(200, invoke(apiId, "empty-security")),
() -> verifyDenyInvocations(0));
} finally {
given().delete("/restapis/" + apiId).then().statusCode(202);
}
}
@Test
void retainedCognitoSchemeKeepsItsAuthorizationType() throws Exception {
String apiId = importApi(COGNITO_SPEC);
try {
String authorizerId = getJson(methodPath(apiId)).path("authorizerId").asText();
merge(apiId, RETAINED_SCHEME_SPEC);
JsonNode method = getJson(methodPath(apiId));
assertAll(
() -> assertEquals("COGNITO_USER_POOLS", method.path("authorizationType").asText()),
() -> assertEquals(authorizerId, method.path("authorizerId").asText()));
} finally {
given().delete("/restapis/" + apiId).then().statusCode(202);
}
}
@Test
void retainedLambdaMethodUsesCognitoAuthorizationAfterSameNameTypeReplacement() throws Exception {
String apiId = importApi();
try {
denyAuthorizerRequests();
String authorizerId = getJson(methodPath(apiId)).path("authorizerId").asText();
deploy(apiId, "before");
assertEquals(403, invoke(apiId, "before"));
merge(apiId, COGNITO_TYPE_REPLACEMENT_SPEC);
deploy(apiId, "after");
JsonNode method = getJson(methodPath(apiId));
JsonNode authorizer = getJson("/restapis/" + apiId + "/authorizers/" + authorizerId);
int afterStatus = invokeWithoutToken(apiId, "after");
assertAll(
() -> assertEquals(401, afterStatus),
() -> assertEquals("COGNITO_USER_POOLS", authorizer.path("type").asText()),
() -> assertEquals("COGNITO_USER_POOLS", method.path("authorizationType").asText()),
() -> assertEquals(authorizerId, method.path("authorizerId").asText()),
() -> verifyDenyInvocations(1));
} finally {
given().delete("/restapis/" + apiId).then().statusCode(202);
}
}
@Test
void retainedCognitoMethodUsesLambdaAuthorizationAfterSameNameTypeReplacement() throws Exception {
String apiId = importApi(COGNITO_SPEC);
try {
String authorizerId = getJson(methodPath(apiId)).path("authorizerId").asText();
deploy(apiId, "before");
assertEquals(401, invokeWithoutToken(apiId, "before"));
denyAuthorizerRequests();
merge(apiId, LAMBDA_TYPE_REPLACEMENT_SPEC);
deploy(apiId, "after");
JsonNode method = getJson(methodPath(apiId));
JsonNode authorizer = getJson("/restapis/" + apiId + "/authorizers/" + authorizerId);
int afterStatus = invoke(apiId, "after");
assertAll(
() -> assertEquals(403, afterStatus),
() -> assertEquals("TOKEN", authorizer.path("type").asText()),
() -> assertEquals("CUSTOM", method.path("authorizationType").asText()),
() -> assertEquals(authorizerId, method.path("authorizerId").asText()),
() -> verifyDenyInvocations(1));
} finally {
given().delete("/restapis/" + apiId).then().statusCode(202);
}
}
@ParameterizedTest
@ValueSource(strings = {"", ", \"authorizerUri\": null", ", \"authorizerUri\": \"\""})
void cognitoToLambdaTypeChangeRequiresNewUri(String uriFragment) throws Exception {
String apiId = importApi(COGNITO_SPEC);
try {
String authorizerId = getJson(methodPath(apiId)).path("authorizerId").asText();
deploy(apiId, "before");
assertEquals(401, invokeWithoutToken(apiId, "before"));
int putStatus = given().contentType(ContentType.JSON).queryParam("mode", "merge")
.body(PARTIAL_AUTHORIZER_SPEC.formatted(uriFragment))
.put("/restapis/" + apiId).statusCode();
JsonNode method = getJson(methodPath(apiId));
JsonNode authorizer = getJson("/restapis/" + apiId + "/authorizers/" + authorizerId);
deploy(apiId, "after-attempt");
int afterStatus = invokeWithoutToken(apiId, "after-attempt");
assertAll(
() -> assertEquals(400, putStatus),
() -> assertEquals(401, afterStatus),
() -> assertEquals("COGNITO_USER_POOLS", method.path("authorizationType").asText()),
() -> assertEquals(authorizerId, method.path("authorizerId").asText()),
() -> assertEquals("COGNITO_USER_POOLS", authorizer.path("type").asText()));
} finally {
given().delete("/restapis/" + apiId).then().statusCode(202);
}
}
@Test
void failedCrossTypeMergeRestoresMethodAndAuthorizer() throws Exception {
String apiId = importApi();
try {
denyAuthorizerRequests();
String authorizerId = getJson(methodPath(apiId)).path("authorizerId").asText();
deploy(apiId, "before");
assertEquals(403, invoke(apiId, "before"));
String spec = """
{
"openapi": "3.0.1",
"info": {"title": "RejectedCrossType", "version": "2"},
"components": {"securitySchemes": {
"Guard": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authorizer": {
"type": "cognito_user_pools",
"providerARNs": ["arn:aws:cognito-idp:us-east-1:000000000000:userpool/us-east-1_ABC123"]
}
}
}},
"paths": {
"/attempted": {"get": {
"x-amazon-apigateway-integration": {"type": "MOCK"}
}},
"/broken": {"get": {
"parameters": [{"name": "filter[a]", "in": "query", "required": true,
"schema": {"type": "string"}}],
"responses": {"200": {"description": "ok"}}
}}
}
}
""";
String errorBody = given().contentType(ContentType.JSON).queryParam("mode", "merge")
.body(spec).put("/restapis/" + apiId).then().statusCode(400)
.extract().asString();
assertTrue(MAPPER.readTree(errorBody).path("message").asText()
.contains("Unable to put method 'GET' on resource at path '/broken'"));
JsonNode method = getJson(methodPath(apiId));
JsonNode authorizer = getJson("/restapis/" + apiId + "/authorizers/" + authorizerId);
deploy(apiId, "after-failed");
int afterStatus = invoke(apiId, "after-failed");
assertAll(
() -> assertEquals(403, afterStatus),
() -> assertEquals("CUSTOM", method.path("authorizationType").asText()),
() -> assertEquals(authorizerId, method.path("authorizerId").asText()),
() -> assertEquals("TOKEN", authorizer.path("type").asText()),
() -> assertEquals(AUTHORIZER_URI, authorizer.path("authorizerUri").asText(null)),
() -> verifyDenyInvocations(2));
} finally {
given().delete("/restapis/" + apiId).then().statusCode(202);
}
}
@Test
void overwriteDoesNotResolveSchemeFromRemovedAuthorizer() throws Exception {
String apiId = importApi();
try {
putSpec(apiId, "overwrite", RETAINED_SCHEME_SPEC);
JsonNode method = getJson(methodPath(apiId));
assertAll(
() -> assertEquals("NONE", method.path("authorizationType").asText()),
() -> assertEquals("", method.path("authorizerId").asText()),
() -> assertEquals(0, getJson("/restapis/" + apiId + "/authorizers")
.path("item").size()));
} finally {
given().delete("/restapis/" + apiId).then().statusCode(202);
}
}
@Test
void explicitNonAuthorizerSchemesDoNotInheritRetainedAuthorizerId() throws Exception {
for (String expectedType : List.of("NONE", "AWS_IAM")) {
String apiId = importApi();
try {
String extension = "AWS_IAM".equals(expectedType)
? ", \"x-amazon-apigateway-authtype\": \"awsSigv4\"" : "";
merge(apiId, EXPLICIT_SCHEME_SPEC.formatted(extension));
JsonNode method = getJson(methodPath(apiId));
assertAll(
() -> assertEquals(expectedType, method.path("authorizationType").asText()),
() -> assertEquals("", method.path("authorizerId").asText()));
} finally {
given().delete("/restapis/" + apiId).then().statusCode(202);
}
}
}
private String importApi() {
return importApi(ORIGINAL_SPEC);
}
private String importApi(String spec) {
return given().contentType(ContentType.JSON).queryParam("mode", "import")
.body(spec).post("/restapis").then().statusCode(201).extract().path("id");
}
private static void merge(String apiId, String spec) {
putSpec(apiId, "merge", spec);
}
private static void putSpec(String apiId, String mode, String spec) {
if (mode == null) {
given().contentType(ContentType.JSON).body(spec)
.put("/restapis/" + apiId).then().statusCode(200);
} else {
given().contentType(ContentType.JSON).queryParam("mode", mode).body(spec)
.put("/restapis/" + apiId).then().statusCode(200);
}
}
private static void deploy(String apiId, String stageName) {
given().contentType(ContentType.JSON).body(Map.of("stageName", stageName))
.post("/restapis/" + apiId + "/deployments").then().statusCode(201);
}
private static int invoke(String apiId, String stageName) {
return given().header("Authorization", "Bearer denied")
.get("/execute-api/" + apiId + "/" + stageName + "/protected").statusCode();
}
private static int invokeWithoutToken(String apiId, String stageName) {
return given().get("/execute-api/" + apiId + "/" + stageName + "/protected").statusCode();
}
private static JsonNode getJson(String path) throws Exception {
String body = given().get(path).then().statusCode(200).extract().asString();
return MAPPER.readTree(body);
}
private static String methodPath(String apiId) throws Exception {
for (JsonNode resource : getJson("/restapis/" + apiId + "/resources").path("item")) {
if ("/protected".equals(resource.path("path").asText())) {
return "/restapis/" + apiId + "/resources/" + resource.path("id").asText()
+ "/methods/GET";
}
}
throw new AssertionError("Missing /protected resource");
}
private void denyAuthorizerRequests() {
denyAuthorizerRequests(AUTHORIZER_FUNCTION);
}
private void denyAuthorizerRequests(String function) {
when(lambdaService.invoke(eq("us-east-1"), eq(function), any(byte[].class),
eq(InvocationType.RequestResponse)))
.thenReturn(new InvokeResult(200, null, DENY_POLICY, null, "authorizer-request"));
}
private void verifyDenyInvocations(int count) {
verifyDenyInvocations(AUTHORIZER_FUNCTION, count);
}
private void verifyDenyInvocations(String function, int count) {
verify(lambdaService, times(count)).invoke(eq("us-east-1"), eq(function),
any(byte[].class), eq(InvocationType.RequestResponse));
}
}
@@ -0,0 +1,366 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.HashSet;
import java.util.Set;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class ApiGatewayPutRestApiMergeTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String ORIGINAL_SPEC = """
{
"openapi": "3.0.1",
"info": {"title": "BeforeMerge", "version": "1"},
"x-amazon-apigateway-request-validators": {
"KeptValidator": {"validateRequestBody": true, "validateRequestParameters": false},
"ChangedValidator": {"validateRequestBody": false, "validateRequestParameters": true}
},
"x-amazon-apigateway-gateway-responses": {
"DEFAULT_4XX": {"statusCode": "430"},
"DEFAULT_5XX": {"statusCode": "530"}
},
"components": {
"schemas": {
"KeptModel": {"type": "object", "properties": {"keptField": {"type": "string"}}},
"ChangedModel": {"type": "object", "properties": {"oldField": {"type": "string"}}}
},
"securitySchemes": {
"KeptAuth": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authorizer": {
"type": "token",
"authorizerUri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:keptAuth/invocations"
}
},
"ChangedAuth": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authorizer": {
"type": "token",
"authorizerUri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:oldAuth/invocations"
}
}
}
},
"paths": {
"/kept": {
"post": {
"security": [{"KeptAuth": []}],
"x-amazon-apigateway-request-validator": "KeptValidator",
"requestBody": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/KeptModel"}}}},
"x-amazon-apigateway-integration": {"type": "MOCK"}
}
},
"/shared": {
"get": {
"security": [{"ChangedAuth": []}],
"x-amazon-apigateway-request-validator": "ChangedValidator",
"x-amazon-apigateway-integration": {
"type": "http_proxy", "httpMethod": "GET", "uri": "https://example.com/old",
"responses": {"default": {"statusCode": "200"}, "legacy": {"statusCode": "206"}}
}
},
"post": {
"security": [{"ChangedAuth": []}],
"x-amazon-apigateway-request-validator": "ChangedValidator",
"requestBody": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ChangedModel"}}}},
"x-amazon-apigateway-integration": {"type": "MOCK"}
}
}
}
}
""";
private static final String CHANGED_SPEC = """
{
"openapi": "3.0.1",
"info": {"title": "AfterMerge", "version": "2"},
"x-amazon-apigateway-request-validators": {
"ChangedValidator": {"validateRequestBody": true, "validateRequestParameters": true}
},
"x-amazon-apigateway-gateway-responses": {
"DEFAULT_4XX": {"statusCode": "431"}
},
"components": {
"schemas": {
"ChangedModel": {"type": "object", "properties": {"newField": {"type": "integer"}}}
},
"securitySchemes": {
"ChangedAuth": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authorizer": {
"type": "token",
"authorizerUri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:newAuth/invocations"
}
}
}
},
"paths": {
"/shared": {
"get": {
"security": [{"ChangedAuth": []}],
"x-amazon-apigateway-request-validator": "ChangedValidator",
"x-amazon-apigateway-integration": {
"type": "http_proxy", "httpMethod": "GET", "uri": "https://example.com/new",
"responses": {"default": {"statusCode": "200"}, "new": {"statusCode": "400"}}
}
}
},
"/new": {"get": {"x-amazon-apigateway-integration": {"type": "MOCK"}}}
}
}
""";
private static final String MERGE_SPEC = CHANGED_SPEC.replace(
"\"/new\": {\"get\": {\"x-amazon-apigateway-integration\": {\"type\": \"MOCK\"}}}",
"\"/new\": {\"get\": {\"x-amazon-apigateway-request-validator\": \"KeptValidator\", "
+ "\"x-amazon-apigateway-integration\": {\"type\": \"MOCK\"}}}");
@Test
void explicitMergePreservesUnmentionedDefinitionsAndReplacesConflicts() throws Exception {
String apiId = importApi(ORIGINAL_SPEC);
try {
JsonNode keptMethodBefore = getJson(methodPath(apiId, "/kept", "POST"));
assertFalse(keptMethodBefore.path("authorizerId").asText().isBlank());
assertFalse(keptMethodBefore.path("requestValidatorId").asText().isBlank());
JsonNode sharedPostBefore = getJson(methodPath(apiId, "/shared", "POST"));
assertEquals(getJson(methodPath(apiId, "/shared", "GET")).path("authorizerId").asText(),
sharedPostBefore.path("authorizerId").asText());
putSpec(apiId, "merge", MERGE_SPEC);
assertEquals(Set.of("/", "/kept", "/shared", "/new"), paths(apiId));
assertEquals("AfterMerge", getJson("/restapis/" + apiId).path("name").asText());
String keptAfter = methodPath(apiId, "/kept", "POST");
JsonNode keptMethodAfter = getJson(keptAfter);
String keptAuthorizerId = keptMethodAfter.path("authorizerId").asText();
String keptValidatorId = keptMethodAfter.path("requestValidatorId").asText();
assertFalse(keptAuthorizerId.isBlank());
assertFalse(keptValidatorId.isBlank());
assertEquals("KeptModel", keptMethodAfter.path("requestModels").path("application/json").asText());
assertEquals("KeptAuth", getJson("/restapis/" + apiId + "/authorizers/" + keptAuthorizerId)
.path("name").asText());
assertEquals("KeptValidator", getJson("/restapis/" + apiId + "/requestvalidators/" + keptValidatorId)
.path("name").asText());
assertTrue(getJson("/restapis/" + apiId + "/models/KeptModel").path("schema").asText()
.contains("keptField"));
assertEquals("530", getJson("/restapis/" + apiId + "/gatewayresponses/DEFAULT_5XX")
.path("statusCode").asText());
String sharedGet = methodPath(apiId, "/shared", "GET");
JsonNode changedMethodAfter = getJson(sharedGet);
JsonNode sharedPostAfter = getJson(methodPath(apiId, "/shared", "POST"));
String changedAuthorizerId = changedMethodAfter.path("authorizerId").asText();
String changedValidatorId = changedMethodAfter.path("requestValidatorId").asText();
assertEquals(changedAuthorizerId, sharedPostAfter.path("authorizerId").asText());
assertEquals(changedValidatorId, sharedPostAfter.path("requestValidatorId").asText());
assertEquals("ChangedModel", sharedPostAfter.path("requestModels").path("application/json").asText());
assertEquals("https://example.com/new", getJson(sharedGet + "/integration").path("uri").asText());
assertEquals(200, status(sharedGet + "/responses/200"));
assertEquals(200, status(sharedGet + "/responses/400"));
assertEquals(404, status(sharedGet + "/responses/206"));
assertEquals(200, status(sharedGet + "/integration/responses/400"));
assertEquals(404, status(sharedGet + "/integration/responses/206"));
assertEquals(200, status(methodPath(apiId, "/shared", "POST")));
assertEquals(200, status(methodPath(apiId, "/new", "GET")));
String reusedValidatorId = getJson(methodPath(apiId, "/new", "GET"))
.path("requestValidatorId").asText();
assertEquals("KeptValidator", getJson("/restapis/" + apiId + "/requestvalidators/" + reusedValidatorId)
.path("name").asText());
assertEquals(2, getJson("/restapis/" + apiId + "/authorizers").path("item").size());
assertEquals(2, getJson("/restapis/" + apiId + "/requestvalidators").path("item").size());
assertTrue(getJson("/restapis/" + apiId + "/models/ChangedModel").path("schema").asText()
.contains("newField"));
assertFalse(getJson("/restapis/" + apiId + "/models/ChangedModel").path("schema").asText()
.contains("oldField"));
assertEquals("431", getJson("/restapis/" + apiId + "/gatewayresponses/DEFAULT_4XX")
.path("statusCode").asText());
assertTrue(getJson("/restapis/" + apiId + "/authorizers/" + changedAuthorizerId)
.path("authorizerUri").asText().contains("newAuth"));
assertTrue(getJson("/restapis/" + apiId + "/requestvalidators/" + changedValidatorId)
.path("validateRequestBody").asBoolean());
putSpec(apiId, "merge", MERGE_SPEC);
assertEquals(Set.of("/", "/kept", "/shared", "/new"), paths(apiId));
assertEquals(2, getJson("/restapis/" + apiId + "/authorizers").path("item").size());
assertEquals(2, getJson("/restapis/" + apiId + "/requestvalidators").path("item").size());
String keptAuthorizerAfterRepeat = getJson(methodPath(apiId, "/kept", "POST"))
.path("authorizerId").asText();
assertEquals("KeptAuth", getJson("/restapis/" + apiId + "/authorizers/" + keptAuthorizerAfterRepeat)
.path("name").asText());
} finally {
given().delete("/restapis/" + apiId);
}
}
@Test
void omittedModeMergesByDefault() throws Exception {
String apiId = importApi(ORIGINAL_SPEC);
try {
putSpec(apiId, null, MERGE_SPEC);
assertEquals(Set.of("/", "/kept", "/shared", "/new"), paths(apiId));
assertEquals(200, status(methodPath(apiId, "/shared", "POST")));
assertEquals("530", getJson("/restapis/" + apiId + "/gatewayresponses/DEFAULT_5XX")
.path("statusCode").asText());
} finally {
given().delete("/restapis/" + apiId);
}
}
@ParameterizedTest
@ValueSource(strings = {"merg", "Merge", "MERGE", " merge"})
void invalidModeIsRejectedBeforeAnyMutation(String mode) throws Exception {
String apiId = importApi(ORIGINAL_SPEC);
try {
given().contentType(ContentType.JSON).queryParam("mode", mode).body(MERGE_SPEC)
.when().put("/restapis/" + apiId).then().statusCode(400);
assertOriginalApi(apiId);
} finally {
given().delete("/restapis/" + apiId);
}
}
@Test
void overwriteStillRemovesUnmentionedDefinitions() throws Exception {
String apiId = importApi(ORIGINAL_SPEC);
try {
putSpec(apiId, "overwrite", CHANGED_SPEC);
assertEquals(Set.of("/", "/shared", "/new"), paths(apiId));
assertEquals(404, status(methodPath(apiId, "/shared", "POST")));
assertEquals(404, status("/restapis/" + apiId + "/models/KeptModel"));
assertEquals(1, getJson("/restapis/" + apiId + "/authorizers").path("item").size());
assertEquals(1, getJson("/restapis/" + apiId + "/requestvalidators").path("item").size());
assertTrue(getJson("/restapis/" + apiId + "/gatewayresponses/DEFAULT_5XX")
.path("defaultResponse").asBoolean());
} finally {
given().delete("/restapis/" + apiId);
}
}
@Test
void failedMergeLeavesOriginalApiAndDefinitionsIntact() throws Exception {
String apiId = importApi(ORIGINAL_SPEC);
try {
String warningSpec = """
{"openapi":"3.0.1","info":{"title":"RejectedByWarnings","version":"2"},
"paths":{"/attempted":{"get":{"security":"not-an-array",
"responses":{"200":{"description":"ok"}}}}}}
""";
given().contentType(ContentType.JSON).queryParam("mode", "merge")
.queryParam("failonwarnings", true).body(warningSpec)
.when().put("/restapis/" + apiId).then().statusCode(400);
assertOriginalApi(apiId);
String lateFailureSpec = """
{
"openapi": "3.0.1",
"info": {"title": "RejectedLate", "version": "2"},
"x-amazon-apigateway-request-validators": {
"ChangedValidator": {"validateRequestBody": true, "validateRequestParameters": true}
},
"paths": {
"/attempted": {"get": {"x-amazon-apigateway-integration": {"type": "MOCK"}}},
"/broken": {"get": {
"parameters": [
{"name": "filter[a]", "in": "query", "required": true,
"schema": {"type": "string"}}
],
"responses": {"200": {"description": "ok"}}
}}
}
}
""";
String failureBody = given().contentType(ContentType.JSON)
.queryParam("mode", "merge").body(lateFailureSpec)
.when().put("/restapis/" + apiId).then().statusCode(400)
.extract().body().asString();
assertTrue(MAPPER.readTree(failureBody).path("message").asText()
.contains("Unable to put method 'GET' on resource at path '/broken'"));
assertOriginalApi(apiId);
} finally {
given().delete("/restapis/" + apiId);
}
}
private static void assertOriginalApi(String apiId) throws Exception {
assertEquals("BeforeMerge", getJson("/restapis/" + apiId).path("name").asText());
assertEquals(Set.of("/", "/kept", "/shared"), paths(apiId));
assertEquals("https://example.com/old",
getJson(methodPath(apiId, "/shared", "GET") + "/integration").path("uri").asText());
assertEquals(2, getJson("/restapis/" + apiId + "/authorizers").path("item").size());
assertEquals(2, getJson("/restapis/" + apiId + "/requestvalidators").path("item").size());
assertEquals("430", getJson("/restapis/" + apiId + "/gatewayresponses/DEFAULT_4XX")
.path("statusCode").asText());
JsonNode keptMethod = getJson(methodPath(apiId, "/kept", "POST"));
assertEquals("KeptAuth", getJson("/restapis/" + apiId + "/authorizers/"
+ keptMethod.path("authorizerId").asText()).path("name").asText());
String changedValidatorId = getJson(methodPath(apiId, "/shared", "GET"))
.path("requestValidatorId").asText();
JsonNode changedValidator = getJson("/restapis/" + apiId + "/requestvalidators/"
+ changedValidatorId);
assertEquals("ChangedValidator", changedValidator.path("name").asText());
assertFalse(changedValidator.path("validateRequestBody").asBoolean());
assertTrue(changedValidator.path("validateRequestParameters").asBoolean());
}
private static String importApi(String spec) throws Exception {
String body = given().contentType(ContentType.JSON).queryParam("mode", "import").body(spec)
.when().post("/restapis").then().statusCode(201).extract().body().asString();
return MAPPER.readTree(body).path("id").asText();
}
private static void putSpec(String apiId, String mode, String spec) {
if (mode == null) {
given().contentType(ContentType.JSON).body(spec)
.when().put("/restapis/" + apiId).then().statusCode(200);
} else {
given().contentType(ContentType.JSON).queryParam("mode", mode).body(spec)
.when().put("/restapis/" + apiId).then().statusCode(200);
}
}
private static JsonNode getJson(String path) throws Exception {
String body = given().when().get(path).then().statusCode(200).extract().body().asString();
return MAPPER.readTree(body);
}
private static int status(String path) {
return given().when().get(path).getStatusCode();
}
private static Set<String> paths(String apiId) throws Exception {
Set<String> paths = new HashSet<>();
for (JsonNode resource : getJson("/restapis/" + apiId + "/resources").path("item")) {
paths.add(resource.path("path").asText());
}
return paths;
}
private static String methodPath(String apiId, String path, String method) throws Exception {
JsonNode resource = null;
for (JsonNode candidate : getJson("/restapis/" + apiId + "/resources").path("item")) {
if (path.equals(candidate.path("path").asText())) {
resource = candidate;
break;
}
}
assertNotNull(resource, "Missing resource " + path);
return "/restapis/" + apiId + "/resources/" + resource.path("id").asText()
+ "/methods/" + method;
}
}