mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
1 parent
2ec5300029
commit
cfc9a440c1
8 files changed
+1355
-31
No files matched your search
+82
-2
@@ -8,6 +8,7 @@ import software.amazon.awssdk.services.apigateway.model.BadRequestException;
|
||||
import software.amazon.awssdk.services.apigateway.model.GetIntegrationResponse;
|
||||
import software.amazon.awssdk.services.apigateway.model.GetMethodResponse;
|
||||
import software.amazon.awssdk.services.apigateway.model.ImportRestApiResponse;
|
||||
import software.amazon.awssdk.services.apigateway.model.NotFoundException;
|
||||
import software.amazon.awssdk.services.apigateway.model.PutMode;
|
||||
import software.amazon.awssdk.services.apigateway.model.Resource;
|
||||
import software.amazon.awssdk.services.apigateway.model.RestApi;
|
||||
@@ -18,8 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
/**
|
||||
* OpenAPI import of the {@code x-amazon-apigateway-any-method} pseudo-operation. The JVM test suite
|
||||
* cannot see a native-image reflection gap, so this runs the import against the native build.
|
||||
* API Gateway OpenAPI import through the AWS SDK management API.
|
||||
*/
|
||||
@DisplayName("API Gateway OpenAPI import")
|
||||
class ApiGatewayOpenApiImportCompatibilityTest {
|
||||
@@ -169,6 +169,86 @@ class ApiGatewayOpenApiImportCompatibilityTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("PutRestApi with mode=merge retains unrelated methods and replaces a conflicting method")
|
||||
void explicitMergeKeepsUnrelatedMethods() {
|
||||
assertMergeKeepsUnrelatedMethods(PutMode.MERGE);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("PutRestApi defaults to merge when mode is omitted")
|
||||
void omittedModeMerges() {
|
||||
assertMergeKeepsUnrelatedMethods(null);
|
||||
}
|
||||
|
||||
private static void assertMergeKeepsUnrelatedMethods(PutMode mode) {
|
||||
String title = TestFixtures.uniqueName("apigw-merge");
|
||||
String original = """
|
||||
{
|
||||
"openapi": "3.0.1", "info": {"title": "%s", "version": "1"},
|
||||
"paths": {
|
||||
"/kept": {"get": {"x-amazon-apigateway-integration": {"type": "MOCK"}}},
|
||||
"/shared": {
|
||||
"get": {"x-amazon-apigateway-integration": {
|
||||
"type": "http_proxy", "httpMethod": "GET", "uri": "https://example.com/old",
|
||||
"responses": {"default": {"statusCode": "200"}, "legacy": {"statusCode": "206"}}
|
||||
}},
|
||||
"post": {"x-amazon-apigateway-integration": {"type": "MOCK"}}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(title);
|
||||
String incoming = """
|
||||
{
|
||||
"openapi": "3.0.1", "info": {"title": "%s", "version": "2"},
|
||||
"paths": {
|
||||
"/shared": {"get": {"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"}}}
|
||||
}
|
||||
}
|
||||
""".formatted(title);
|
||||
|
||||
try (ApiGatewayClient apiGateway = TestFixtures.apiGatewayClient()) {
|
||||
ImportRestApiResponse imported = apiGateway.importRestApi(request -> request
|
||||
.body(SdkBytes.fromUtf8String(original)));
|
||||
try {
|
||||
apiGateway.putRestApi(request -> {
|
||||
request.restApiId(imported.id()).body(SdkBytes.fromUtf8String(incoming));
|
||||
if (mode != null) {
|
||||
request.mode(mode);
|
||||
}
|
||||
});
|
||||
|
||||
List<String> paths = apiGateway.getResources(request -> request.restApiId(imported.id()))
|
||||
.items().stream().map(Resource::path).toList();
|
||||
assertThat(paths).containsExactlyInAnyOrder("/", "/kept", "/shared", "/new");
|
||||
|
||||
apiGateway.getMethod(request -> request.restApiId(imported.id())
|
||||
.resourceId(resourceId(apiGateway, imported.id(), "/kept")).httpMethod("GET"));
|
||||
String sharedId = resourceId(apiGateway, imported.id(), "/shared");
|
||||
apiGateway.getMethod(request -> request.restApiId(imported.id())
|
||||
.resourceId(sharedId).httpMethod("POST"));
|
||||
apiGateway.getMethodResponse(request -> request.restApiId(imported.id())
|
||||
.resourceId(sharedId).httpMethod("GET").statusCode("200"));
|
||||
apiGateway.getMethodResponse(request -> request.restApiId(imported.id())
|
||||
.resourceId(sharedId).httpMethod("GET").statusCode("400"));
|
||||
assertThatThrownBy(() -> apiGateway.getMethodResponse(request -> request
|
||||
.restApiId(imported.id()).resourceId(sharedId).httpMethod("GET")
|
||||
.statusCode("206"))).isInstanceOf(NotFoundException.class);
|
||||
GetIntegrationResponse integration = apiGateway.getIntegration(request -> request
|
||||
.restApiId(imported.id()).resourceId(sharedId).httpMethod("GET"));
|
||||
assertThat(integration.uri()).isEqualTo("https://example.com/new");
|
||||
assertThat(integration.integrationResponses())
|
||||
.containsKeys("200", "400").doesNotContainKey("206");
|
||||
} finally {
|
||||
apiGateway.deleteRestApi(request -> request.restApiId(imported.id()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String resourceId(ApiGatewayClient apiGateway, String restApiId, String path) {
|
||||
return apiGateway.getResources(request -> request.restApiId(restApiId)).items().stream()
|
||||
.filter(resource -> path.equals(resource.path()))
|
||||
|
||||
@@ -54,10 +54,22 @@ duplicate override IDs.
|
||||
|
||||
`ImportRestApi` and `PutRestApi` return parser warnings in the REST API's `warnings` array.
|
||||
Set the lowercase query parameter `failonwarnings=true` (SDK: `failOnWarnings`) to reject
|
||||
a warning-bearing definition with `BadRequestException` before creating or overwriting
|
||||
a warning-bearing definition with `BadRequestException` before creating or changing
|
||||
the API. The default is `false`. A successful import with no warnings clears any prior
|
||||
warnings; malformed definitions and fatal import errors remain errors in either mode.
|
||||
|
||||
`PutRestApi` defaults to `mode=merge`. Merge keeps paths, methods, models, authorizers,
|
||||
request validators, and gateway responses omitted from the incoming definition. An incoming
|
||||
method replaces the complete existing method at the same path and HTTP verb, including its
|
||||
integration and responses. Use `mode=overwrite` to clear those API definitions before import.
|
||||
During merge, a method can reference a retained Lambda or Cognito authorizer even when the
|
||||
incoming security schemes omit it. A same-name Lambda authorizer keeps its existing URI when
|
||||
the incoming definition provides no new URI. If a same-name authorizer changes between Lambda
|
||||
and Cognito, retained methods that reference it use the new authorization type. An explicit
|
||||
operation-level `security: []` leaves that method without authorization.
|
||||
For a same-name Cognito authorizer, merge also keeps its existing pool ARNs when the incoming
|
||||
definition provides no new `providerARNs`; an explicit list replaces them, including `[]`.
|
||||
|
||||
### Supported Operations
|
||||
|
||||
| Category | Operations |
|
||||
|
||||
+8
-4
@@ -969,7 +969,8 @@ public class ApiGatewayExecuteController {
|
||||
Stage stage,
|
||||
MethodConfig method,
|
||||
HttpHeaders headers, UriInfo uriInfo, ResolvedApiKey resolvedApiKey) {
|
||||
if ("COGNITO_USER_POOLS".equalsIgnoreCase(method.getAuthorizationType())) {
|
||||
String authorizationType = method.getAuthorizationType();
|
||||
if ("COGNITO_USER_POOLS".equalsIgnoreCase(authorizationType)) {
|
||||
CognitoUserPoolAuthorizer.Result result = cognitoAuthorizer.authorize(region, apiId, method, headers);
|
||||
if (result.failure() == CognitoUserPoolAuthorizer.Failure.UNAUTHORIZED) {
|
||||
return new AuthorizerResult(gatewayResponse(scope, GatewayResponseType.UNAUTHORIZED, 401,
|
||||
@@ -981,16 +982,19 @@ public class ApiGatewayExecuteController {
|
||||
}
|
||||
return new AuthorizerResult(null, result.principalId(), result.context());
|
||||
}
|
||||
if ("CUSTOM".equals(method.getAuthorizationType())) {
|
||||
if ("CUSTOM".equals(authorizationType)) {
|
||||
String authorizerId = method.getAuthorizerId();
|
||||
if (authorizerId == null) {
|
||||
return new AuthorizerResult(null, null, null);
|
||||
}
|
||||
|
||||
io.github.hectorvent.floci.services.apigateway.model.Authorizer auth = apiGatewayService.getAuthorizer(region, apiId, authorizerId);
|
||||
String authorizerType = auth.getType();
|
||||
String lambdaName = functionNameFromUri(auth.getAuthorizerUri());
|
||||
if (lambdaName == null) {
|
||||
return new AuthorizerResult(null, null, null);
|
||||
if ((!"TOKEN".equals(authorizerType) && !"REQUEST".equals(authorizerType))
|
||||
|| lambdaName == null || lambdaName.isBlank()) {
|
||||
return new AuthorizerResult(gatewayResponseOr(Response.status(500).build(), scope,
|
||||
GatewayResponseType.AUTHORIZER_CONFIGURATION_ERROR, null), null, null);
|
||||
}
|
||||
|
||||
String event = toAuthorizerEvent(auth, headers, region, apiId, stageName, httpMethod, requestPath, resourcePath, resourceId, stage, uriInfo, resolvedApiKey);
|
||||
|
||||
+125
-23
@@ -951,8 +951,15 @@ public class ApiGatewayService {
|
||||
|
||||
public Authorizer createAuthorizer(String region, String apiId, Map<String, Object> request) {
|
||||
getRestApi(region, apiId);
|
||||
Authorizer authorizer = saveAuthorizer(region, apiId, shortId(6), request);
|
||||
LOG.infov("Created authorizer {0} for API {1}", authorizer.getId(), apiId);
|
||||
return authorizer;
|
||||
}
|
||||
|
||||
private Authorizer saveAuthorizer(String region, String apiId, String authorizerId,
|
||||
Map<String, Object> request) {
|
||||
Authorizer authorizer = new Authorizer();
|
||||
authorizer.setId(shortId(6));
|
||||
authorizer.setId(authorizerId);
|
||||
authorizer.setName((String) request.get("name"));
|
||||
authorizer.setType((String) request.get("type"));
|
||||
authorizer.setAuthorizerUri((String) request.get("authorizerUri"));
|
||||
@@ -970,7 +977,6 @@ public class ApiGatewayService {
|
||||
}
|
||||
|
||||
authorizerStore.put(authorizerKey(region, apiId, authorizer.getId()), authorizer);
|
||||
LOG.infov("Created authorizer {0} for API {1}", authorizer.getId(), apiId);
|
||||
return authorizer;
|
||||
}
|
||||
|
||||
@@ -1727,14 +1733,20 @@ public class ApiGatewayService {
|
||||
|
||||
public RequestValidator createRequestValidator(String region, String apiId, Map<String, Object> request) {
|
||||
getRestApi(region, apiId);
|
||||
RequestValidator validator = saveRequestValidator(region, apiId, shortId(6), request);
|
||||
LOG.infov("Created request validator {0} for API {1}", validator.getId(), apiId);
|
||||
return validator;
|
||||
}
|
||||
|
||||
private RequestValidator saveRequestValidator(String region, String apiId, String validatorId,
|
||||
Map<String, Object> request) {
|
||||
RequestValidator validator = new RequestValidator();
|
||||
validator.setId(shortId(6));
|
||||
validator.setId(validatorId);
|
||||
validator.setName((String) request.get("name"));
|
||||
validator.setValidateRequestBody(Boolean.TRUE.equals(request.get("validateRequestBody")));
|
||||
validator.setValidateRequestParameters(Boolean.TRUE.equals(request.get("validateRequestParameters")));
|
||||
|
||||
requestValidatorStore.put(requestValidatorKey(region, apiId, validator.getId()), validator);
|
||||
LOG.infov("Created request validator {0} for API {1}", validator.getId(), apiId);
|
||||
return validator;
|
||||
}
|
||||
|
||||
@@ -2698,25 +2710,30 @@ public class ApiGatewayService {
|
||||
}
|
||||
|
||||
public RestApi putRestApi(String region, String apiId, String mode, String specBody, boolean failOnWarnings) {
|
||||
// Note: mode=merge is accepted but treated as overwrite (merge semantics not yet implemented)
|
||||
getRestApi(region, apiId);
|
||||
if (mode != null && !"merge".equals(mode) && !"overwrite".equals(mode)) {
|
||||
// AWS PutRestApi accepts only merge (the default) and overwrite; reject anything
|
||||
// else before parsing or mutating so a typo cannot take the destructive overwrite path.
|
||||
throw new AwsException("BadRequestException",
|
||||
"Invalid mode specified. Valid modes are 'merge' and 'overwrite'.", 400);
|
||||
}
|
||||
ParsedOpenApi parsed = parseOpenApiSpec(specBody, failOnWarnings);
|
||||
RestApiSnapshot snapshot = snapshotRestApi(region, apiId);
|
||||
try {
|
||||
RestApi api = overwriteRestApi(region, apiId, parsed.openAPI());
|
||||
RestApi api = mode == null || "merge".equals(mode)
|
||||
? updateRestApiFromOpenApi(region, apiId, parsed.openAPI())
|
||||
: overwriteRestApi(region, apiId, parsed.openAPI());
|
||||
api.setWarnings(parsed.warnings());
|
||||
apiStore.put(apiKey(region, apiId), api);
|
||||
return api;
|
||||
} catch (RuntimeException e) {
|
||||
// A failed PutRestApi leaves the API as it was; the overwrite has already cleared it by now.
|
||||
// A failed PutRestApi leaves the API as it was, including changes made during import.
|
||||
restoreRestApi(region, apiId, snapshot);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private RestApi overwriteRestApi(String region, String apiId, OpenAPI openAPI) {
|
||||
RestApi api = getRestApi(region, apiId);
|
||||
|
||||
// Delete all non-root resources
|
||||
List<ApiGatewayResource> existing = getResources(region, apiId);
|
||||
for (ApiGatewayResource r : existing) {
|
||||
@@ -2739,7 +2756,11 @@ public class ApiGatewayService {
|
||||
authorizerStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(authorizerStore::delete);
|
||||
gatewayResponseStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(gatewayResponseStore::delete);
|
||||
|
||||
// Update API metadata from spec
|
||||
return updateRestApiFromOpenApi(region, apiId, openAPI);
|
||||
}
|
||||
|
||||
private RestApi updateRestApiFromOpenApi(String region, String apiId, OpenAPI openAPI) {
|
||||
RestApi api = getRestApi(region, apiId);
|
||||
if (openAPI.getInfo() != null) {
|
||||
if (openAPI.getInfo().getTitle() != null) api.setName(openAPI.getInfo().getTitle());
|
||||
if (openAPI.getInfo().getDescription() != null) api.setDescription(openAPI.getInfo().getDescription());
|
||||
@@ -3036,6 +3057,12 @@ public class ApiGatewayService {
|
||||
|
||||
// Import x-amazon-apigateway-request-validators as RequestValidators
|
||||
Map<String, String> validatorNameToId = new HashMap<>();
|
||||
for (RequestValidator validator : getRequestValidators(region, apiId)) {
|
||||
if (validator.getName() != null) {
|
||||
validatorNameToId.putIfAbsent(validator.getName(), validator.getId());
|
||||
}
|
||||
}
|
||||
String defaultValidatorId = null;
|
||||
Map<String, Object> topExtensions = openAPI.getExtensions();
|
||||
if (topExtensions != null) {
|
||||
Map<String, Object> validators = (Map<String, Object>) topExtensions
|
||||
@@ -3050,26 +3077,40 @@ public class ApiGatewayService {
|
||||
Boolean.TRUE.equals(validatorDef.get("validateRequestBody")));
|
||||
valReq.put("validateRequestParameters",
|
||||
Boolean.TRUE.equals(validatorDef.get("validateRequestParameters")));
|
||||
RequestValidator rv = createRequestValidator(region, apiId, valReq);
|
||||
String existingId = validatorNameToId.get(validatorName);
|
||||
RequestValidator rv = existingId == null
|
||||
? createRequestValidator(region, apiId, valReq)
|
||||
: saveRequestValidator(region, apiId, existingId, valReq);
|
||||
validatorNameToId.put(validatorName, rv.getId());
|
||||
}
|
||||
}
|
||||
|
||||
// API-level default validator
|
||||
String defaultValidator = (String) topExtensions.get("x-amazon-apigateway-request-validator");
|
||||
if (defaultValidator != null && validatorNameToId.containsKey(defaultValidator)) {
|
||||
validatorNameToId.put("__default__", validatorNameToId.get(defaultValidator));
|
||||
if (defaultValidator != null) {
|
||||
defaultValidatorId = validatorNameToId.get(defaultValidator);
|
||||
}
|
||||
|
||||
importGatewayResponses(region, apiId, topExtensions.get("x-amazon-apigateway-gateway-responses"));
|
||||
}
|
||||
|
||||
// Import security schemes: create an Authorizer for each x-amazon-apigateway-authorizer scheme
|
||||
// Import security schemes: upsert an Authorizer for each x-amazon-apigateway-authorizer scheme
|
||||
// and record how each scheme name maps to a method authorizationType, so per-operation/root
|
||||
// `security` requirements can be applied to methods below. Without this, imported APIs with a
|
||||
// Lambda authorizer land as authorizationType=NONE and are silently open at runtime.
|
||||
Map<String, String> schemeToAuthorizerId = new HashMap<>();
|
||||
Map<String, String> schemeToAuthType = new HashMap<>();
|
||||
Map<String, String> authorizerNameToId = new HashMap<>();
|
||||
for (Authorizer authorizer : getAuthorizers(region, apiId)) {
|
||||
if (authorizer.getName() != null) {
|
||||
authorizerNameToId.putIfAbsent(authorizer.getName(), authorizer.getId());
|
||||
String methodType = methodAuthorizationType(authorizer.getType());
|
||||
if (methodType != null) {
|
||||
schemeToAuthType.putIfAbsent(authorizer.getName(), methodType);
|
||||
schemeToAuthorizerId.putIfAbsent(authorizer.getName(), authorizer.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (openAPI.getComponents() != null && openAPI.getComponents().getSecuritySchemes() != null) {
|
||||
for (var schemeEntry : openAPI.getComponents().getSecuritySchemes().entrySet()) {
|
||||
String schemeName = schemeEntry.getKey();
|
||||
@@ -3080,7 +3121,24 @@ public class ApiGatewayService {
|
||||
String t = importedAuthorizerType(authDef, schemeName); // token | request | cognito_user_pools
|
||||
Map<String, Object> req = new HashMap<>();
|
||||
req.put("name", schemeName);
|
||||
req.put("authorizerUri", importedAuthorizerUri(authDef, schemeName));
|
||||
String authorizerUri = importedAuthorizerUri(authDef, schemeName);
|
||||
String existingId = authorizerNameToId.get(schemeName);
|
||||
Authorizer existing = existingId == null ? null : getAuthorizer(region, apiId, existingId);
|
||||
if (existing != null && "COGNITO_USER_POOLS".equals(existing.getType())
|
||||
&& ("token".equals(t) || "request".equals(t))
|
||||
&& (authorizerUri == null || authorizerUri.isBlank())) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Lambda authorizer " + schemeName
|
||||
+ " must specify authorizerUri when replacing a Cognito authorizer.",
|
||||
400);
|
||||
}
|
||||
if (authorizerUri == null && existing != null
|
||||
&& ("token".equals(t) || "request".equals(t))) {
|
||||
if ("TOKEN".equals(existing.getType()) || "REQUEST".equals(existing.getType())) {
|
||||
authorizerUri = existing.getAuthorizerUri();
|
||||
}
|
||||
}
|
||||
req.put("authorizerUri", authorizerUri);
|
||||
req.put("authorizerResultTtlInSeconds", importedAuthorizerTtl(authDef, schemeName));
|
||||
String identitySource = resolveImportedIdentitySource(scheme, authDef, t, schemeName);
|
||||
if (identitySource != null) {
|
||||
@@ -3090,6 +3148,10 @@ public class ApiGatewayService {
|
||||
req.put("type", "COGNITO_USER_POOLS");
|
||||
// Cognito user-pool authorizers carry the pool ARNs in the authorizer extension.
|
||||
List<String> providerArns = importedProviderArns(authDef, schemeName);
|
||||
if (providerArns == null && existing != null
|
||||
&& "COGNITO_USER_POOLS".equals(existing.getType())) {
|
||||
providerArns = existing.getProviderARNs();
|
||||
}
|
||||
if (providerArns != null) {
|
||||
req.put("providerARNs", providerArns);
|
||||
}
|
||||
@@ -3098,12 +3160,25 @@ public class ApiGatewayService {
|
||||
req.put("type", t == null ? "TOKEN" : t.toUpperCase());
|
||||
schemeToAuthType.put(schemeName, "CUSTOM");
|
||||
}
|
||||
Authorizer created = createAuthorizer(region, apiId, req);
|
||||
Authorizer created = existingId == null
|
||||
? createAuthorizer(region, apiId, req)
|
||||
: saveAuthorizer(region, apiId, existingId, req);
|
||||
authorizerNameToId.put(schemeName, created.getId());
|
||||
schemeToAuthorizerId.put(schemeName, created.getId());
|
||||
if (existing != null) {
|
||||
String oldMethodType = methodAuthorizationType(existing.getType());
|
||||
String newMethodType = schemeToAuthType.get(schemeName);
|
||||
if (oldMethodType != null && !oldMethodType.equals(newMethodType)) {
|
||||
alignRetainedAuthorizerMethods(region, apiId, existingId,
|
||||
oldMethodType, newMethodType);
|
||||
}
|
||||
}
|
||||
} else if ("awsSigv4".equalsIgnoreCase(authtype)) {
|
||||
schemeToAuthType.put(schemeName, "AWS_IAM");
|
||||
schemeToAuthorizerId.remove(schemeName);
|
||||
} else {
|
||||
schemeToAuthType.put(schemeName, "NONE"); // plain apiKey scheme
|
||||
schemeToAuthorizerId.remove(schemeName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3116,9 +3191,11 @@ public class ApiGatewayService {
|
||||
.filter(r -> "/".equals(r.getPath())).findFirst().orElse(null);
|
||||
if (rootResource == null) return;
|
||||
|
||||
// Map of full path → resource ID for creating nested resources
|
||||
// Reuse existing paths when importing into an API; overwrite has already removed them.
|
||||
Map<String, String> pathToResourceId = new HashMap<>();
|
||||
pathToResourceId.put("/", rootResource.getId());
|
||||
for (ApiGatewayResource resource : resources) {
|
||||
pathToResourceId.put(resource.getPath(), resource.getId());
|
||||
}
|
||||
|
||||
for (Map.Entry<String, PathItem> pathEntry : openAPI.getPaths().entrySet()) {
|
||||
String path = pathEntry.getKey();
|
||||
@@ -3134,7 +3211,7 @@ public class ApiGatewayService {
|
||||
String httpMethod = opEntry.getKey().name().toUpperCase();
|
||||
try {
|
||||
applyOperation(region, apiId, resourceId, httpMethod, opEntry.getValue(), openAPI,
|
||||
schemeToAuthorizerId, schemeToAuthType, validatorNameToId);
|
||||
schemeToAuthorizerId, schemeToAuthType, validatorNameToId, defaultValidatorId);
|
||||
} catch (AwsException e) {
|
||||
if (PARAMETER_NAME_ERROR.equals(e.getMessage())) {
|
||||
throw importParameterNameFailure(httpMethod, path, e);
|
||||
@@ -3155,7 +3232,7 @@ public class ApiGatewayService {
|
||||
Operation anyOperation = parseAnyMethodOperation(path, anyMethodExt);
|
||||
try {
|
||||
applyOperation(region, apiId, resourceId, "ANY", anyOperation, openAPI,
|
||||
schemeToAuthorizerId, schemeToAuthType, validatorNameToId);
|
||||
schemeToAuthorizerId, schemeToAuthType, validatorNameToId, defaultValidatorId);
|
||||
} catch (AwsException e) {
|
||||
if (PARAMETER_NAME_ERROR.equals(e.getMessage())) {
|
||||
throw importParameterNameFailure("ANY", path, e);
|
||||
@@ -3167,6 +3244,30 @@ public class ApiGatewayService {
|
||||
}
|
||||
}
|
||||
|
||||
private static String methodAuthorizationType(String authorizerType) {
|
||||
if ("TOKEN".equals(authorizerType) || "REQUEST".equals(authorizerType)) {
|
||||
return "CUSTOM";
|
||||
}
|
||||
return "COGNITO_USER_POOLS".equals(authorizerType) ? "COGNITO_USER_POOLS" : null;
|
||||
}
|
||||
|
||||
private void alignRetainedAuthorizerMethods(String region, String apiId, String authorizerId,
|
||||
String oldType, String newType) {
|
||||
for (ApiGatewayResource resource : getResources(region, apiId)) {
|
||||
boolean changed = false;
|
||||
for (MethodConfig method : resource.getResourceMethods().values()) {
|
||||
if (authorizerId.equals(method.getAuthorizerId())
|
||||
&& oldType.equals(method.getAuthorizationType())) {
|
||||
method.setAuthorizationType(newType);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
resourceStore.put(resourceKey(region, apiId, resource.getId()), resource);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the typed Operation for an ANY pseudo-operation with the swagger parser's own
|
||||
* Operation reader, the one that already parses the real verbs. Binding the untyped extension
|
||||
@@ -3192,7 +3293,8 @@ public class ApiGatewayService {
|
||||
|
||||
private void applyOperation(String region, String apiId, String resourceId, String httpMethod,
|
||||
Operation operation, OpenAPI openAPI, Map<String, String> schemeToAuthorizerId,
|
||||
Map<String, String> schemeToAuthType, Map<String, String> validatorNameToId) {
|
||||
Map<String, String> schemeToAuthType, Map<String, String> validatorNameToId,
|
||||
String defaultValidatorId) {
|
||||
// Create the method
|
||||
Map<String, Object> methodRequest = new HashMap<>();
|
||||
// Apply the operation's (or the API root's) security requirement, resolving the scheme
|
||||
@@ -3275,8 +3377,8 @@ public class ApiGatewayService {
|
||||
}
|
||||
if (opValidator != null && validatorNameToId.containsKey(opValidator)) {
|
||||
methodRequest.put("requestValidatorId", validatorNameToId.get(opValidator));
|
||||
} else if (validatorNameToId.containsKey("__default__")) {
|
||||
methodRequest.put("requestValidatorId", validatorNameToId.get("__default__"));
|
||||
} else if (defaultValidatorId != null) {
|
||||
methodRequest.put("requestValidatorId", defaultValidatorId);
|
||||
}
|
||||
|
||||
putMethod(region, apiId, resourceId, httpMethod, methodRequest);
|
||||
|
||||
+108
@@ -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,
|
||||
|
||||
-1
@@ -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\"}")
|
||||
|
||||
+653
@@ -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));
|
||||
}
|
||||
}
|
||||
+366
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user