Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.apache.shenyu.admin.service.SwaggerImportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
Expand Down Expand Up @@ -60,6 +61,10 @@ public ShenyuAdminResult importSwagger(@Valid @RequestBody final SwaggerImportRe
String result = swaggerImportService.importSwagger(request);
return ShenyuAdminResult.success(result);

} catch (IllegalArgumentException e) {
// Oversized Swagger bodies and other invalid import inputs are client request errors.
LOG.error("Failed to import swagger document", e);
return ShenyuAdminResult.error(HttpStatus.BAD_REQUEST.value(), "Import failed: " + e.getMessage());
} catch (Exception e) {
LOG.error("Failed to import swagger document", e);

Expand All @@ -79,6 +84,10 @@ public ShenyuAdminResult importMcpConfig(@Valid @RequestBody final SwaggerImport
try {
String result = swaggerImportService.importMcpConfig(request);
return ShenyuAdminResult.success(result);
} catch (IllegalArgumentException e) {
// Oversized Swagger bodies and other invalid import inputs are client request errors.
LOG.error("Failed to import mcp server config", e);
return ShenyuAdminResult.error(HttpStatus.BAD_REQUEST.value(), "Import failed: " + e.getMessage());
} catch (Exception e) {
LOG.error("Failed to import mcp server config", e);
return ShenyuAdminResult.error("Import failed" + e.getMessage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.parser.OpenAPIV3Parser;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.apache.shenyu.admin.model.bean.UpstreamInstance;
import org.apache.shenyu.admin.model.dto.SwaggerImportRequest;
import org.apache.shenyu.admin.service.SwaggerImportService;
Expand All @@ -42,12 +43,17 @@
import org.apache.shenyu.register.common.dto.MetaDataRegisterDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
Expand All @@ -65,10 +71,18 @@ public class SwaggerImportServiceImpl implements SwaggerImportService {

private static final Logger LOG = LoggerFactory.getLogger(SwaggerImportServiceImpl.class);

private static final int READ_BUFFER_SIZE = 8192;

private static final long DEFAULT_MAX_SWAGGER_BODY_SIZE = 10L * 1024 * 1024;

private final DocManager docManager;

private final HttpUtils httpUtils;

// Default is 10 MB and can be overridden by shenyu.swagger.max-body-size.
@Value("${shenyu.swagger.max-body-size:10485760}")
private long maxSwaggerBodySize = DEFAULT_MAX_SWAGGER_BODY_SIZE;

@Resource
private ShenyuClientRegisterMcpServiceImpl shenyuClientRegisterMcpService;

Expand Down Expand Up @@ -102,6 +116,10 @@ public String importSwagger(final SwaggerImportRequest request) {

return "Import successful, supports Swagger 2.0 and OpenAPI 3.0 formats";

} catch (IllegalArgumentException e) {
// Keep bad user input unwrapped so the controller can return HTTP 400.
LOG.error("Failed to import swagger document: {}", request.getProjectName(), e);
throw e;
} catch (Exception e) {
LOG.error("Failed to import swagger document: {}", request.getProjectName(), e);
throw new RuntimeException("Import failed: " + e.getMessage(), e);
Expand All @@ -124,6 +142,10 @@ public String importMcpConfig(final SwaggerImportRequest request) {
});

return "Import mcp server config successful, supports Swagger 2.0 and OpenAPI 3.0 formats";
} catch (IllegalArgumentException e) {
// Keep bad user input unwrapped so the controller can return HTTP 400.
LOG.error("Failed to import mcp config: {}", request.getProjectName(), e);
throw e;
} catch (IOException e) {
LOG.error("Failed to import mcp config: {}", request.getProjectName(), e);
throw new RuntimeException("Import mcp server config failed: " + e.getMessage(), e);
Expand Down Expand Up @@ -252,9 +274,48 @@ private String fetchSwaggerDoc(final String swaggerUrl) throws IOException {
if (response.code() != 200) {
throw new RuntimeException("Failed to get Swagger document, HTTP status code: " + response.code());
}

return response.body().string();

return readLimitedResponseBody(response.body(), maxSwaggerBodySize);
}
}


private String readLimitedResponseBody(final ResponseBody responseBody, final long maxBodySize) throws IOException {
if (Objects.isNull(responseBody)) {
throw new IllegalArgumentException("Swagger document response body is empty");
}
if (maxBodySize < 0) {
throw new IllegalArgumentException("Max Swagger response body size must not be negative");
}

long contentLength = responseBody.contentLength();
// Reject early when the server declares a body larger than the configured limit.
if (contentLength > maxBodySize) {
throw new IllegalArgumentException(String.format(
"Swagger document response body exceeds maximum size of %d bytes", maxBodySize));
}

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[READ_BUFFER_SIZE];
long totalBytes = 0;
try (InputStream inputStream = responseBody.byteStream()) {
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
totalBytes += bytesRead;
// Content-Length can be missing or wrong, so enforce the limit while streaming.
if (totalBytes > maxBodySize) {
throw new IllegalArgumentException(String.format(
"Swagger document response body exceeds maximum size of %d bytes", maxBodySize));
}
outputStream.write(buffer, 0, bytesRead);
}
}

// Preserve the server-declared charset; default to UTF-8 when it is absent.
Charset charset = Objects.isNull(responseBody.contentType())
? StandardCharsets.UTF_8
: responseBody.contentType().charset(StandardCharsets.UTF_8);
return outputStream.toString(charset.name());
}

private void validateSwaggerContent(final String swaggerJson) {
Expand Down
2 changes: 2 additions & 0 deletions shenyu-admin/src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,8 @@ shenyu:
- /v3/api-docs/**
- /csrf
- /alert/report
swagger:
max-body-size: 10485760
dashboard:
core:
onlySuperAdminPermission:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.shenyu.admin.controller;

import org.apache.shenyu.admin.model.dto.SwaggerImportRequest;
import org.apache.shenyu.admin.service.SwaggerImportService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.hamcrest.core.Is.is;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* Test for {@link SwaggerImportController}.
*/
@ExtendWith(MockitoExtension.class)
public class SwaggerImportControllerTest {

private static final String IMPORT_REQUEST = "{"
+ "\"swaggerUrl\":\"https://8.8.8.8/swagger.json\","
+ "\"projectName\":\"test\""
+ "}";

private MockMvc mockMvc;

@InjectMocks
private SwaggerImportController swaggerImportController;

@Mock
private SwaggerImportService swaggerImportService;

@BeforeEach
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(swaggerImportController).build();
}

@Test
public void importSwaggerShouldReturnBadRequestCodeWhenBodyExceedsLimit() throws Exception {
when(swaggerImportService.importSwagger(any(SwaggerImportRequest.class)))
.thenThrow(new IllegalArgumentException(
"Swagger document response body exceeds maximum size of 10 bytes"));

mockMvc.perform(MockMvcRequestBuilders.post("/swagger/import")
.contentType(MediaType.APPLICATION_JSON)
.content(IMPORT_REQUEST))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code", is(HttpStatus.BAD_REQUEST.value())));
}

@Test
public void importMcpConfigShouldReturnBadRequestCodeWhenBodyExceedsLimit() throws Exception {
when(swaggerImportService.importMcpConfig(any(SwaggerImportRequest.class)))
.thenThrow(new IllegalArgumentException(
"Swagger document response body exceeds maximum size of 10 bytes"));

mockMvc.perform(MockMvcRequestBuilders.post("/swagger/import/mcp")
.contentType(MediaType.APPLICATION_JSON)
.content(IMPORT_REQUEST))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code", is(HttpStatus.BAD_REQUEST.value())));
}
}
Loading
Loading