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 @@ -12,12 +12,19 @@
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UrlPathHelper;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;

/**
* C++层HTTP接口调用控制层
Expand All @@ -31,6 +38,9 @@
public class CppHttpController extends BaseController {

private static final String CPP_SERVER_IP_HEADER = "Cpp-Server-IP";
private static final String PROXY_PREFIX = "/v1/cpp";
private static final String UPGRADE_UPLOAD = "/api/system/upgrade/upload";
private static final String UPGRADE_ACTION = "/api/system/upgrade/action";

@Resource
private CppHttpProxyService cppHttpProxyService;
Expand Down Expand Up @@ -62,38 +72,21 @@ public Object proxyRequest(
HttpServletRequest request,
@RequestBody(required = false) byte[] body) {
try {
// 获取实际请求路径
String path = request.getRequestURI().substring(request.getContextPath().length() + "/v1/cpp".length());
if (HttpMethod.POST.matches(request.getMethod()) && ("/api/system/upgrade/upload".equals(path)
|| ("/api/system/upgrade/action".equals(path) && body != null
&& "confirm".equals(JSONUtil.parseObj(new String(body, StandardCharsets.UTF_8)).getStr("action"))))) {
cppHttpProxyService.assertUpgradeIdle(serverIp);
}
String targetUrl = buildUrl(serverIp, path);
log.info("调用C++接口,URL: {}, Method: {}", targetUrl, request.getMethod());
// 构建 HTTP 请求对象
HttpRequest httpRequest = HttpUtil.createRequest(Method.valueOf(request.getMethod()), targetUrl);

// 转发所有请求头(可选:只转发特定头如 Accept-Language)
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
// 仅转发设备接口需要的白名单头,避免把代理控制头透传给设备
if ("Accept-Language".equalsIgnoreCase(headerName)
|| "Content-Type".equalsIgnoreCase(headerName)) {
String headerValue = request.getHeader(headerName);
httpRequest.header(headerName, headerValue);
}
}

// 发送请求
HttpResponse response;
String path = request.getRequestURI().substring(request.getContextPath().length() + PROXY_PREFIX.length());
if (HttpMethod.POST.matches(request.getMethod())) {
response = httpRequest.body(body).execute();
} else {
response = httpRequest.execute();
String decodedPath = UrlPathHelper.defaultInstance.getPathWithinApplication(request);
String normalized = normalizeUpgradePath(decodedPath);
if (normalized.equals(PROXY_PREFIX + UPGRADE_UPLOAD)) {
return forwardUpgrade(serverIp, UPGRADE_UPLOAD, request, body);
}
if (normalized.equals(PROXY_PREFIX + UPGRADE_ACTION)) {
if ("confirm".equalsIgnoreCase(readUpgradeAction(body))) {
return forwardUpgrade(serverIp, UPGRADE_ACTION, request, body);
}
path = UPGRADE_ACTION;
}
}
return buildProxyResponse(response);
return forward(buildUrl(serverIp, path), request, body);
} catch (CryBusinessException e) {
throw e;
} catch (Exception e) {
Expand All @@ -102,6 +95,59 @@ public Object proxyRequest(
}
}

private Object forwardUpgrade(String serverIp, String path, HttpServletRequest request, byte[] body) {
try (var target = cppHttpProxyService.openFirmwareTarget(serverIp, path)) {
return forward(target.url(), request, body);
}
}

private static String normalizeUpgradePath(String path) {
StringBuilder collapsed = new StringBuilder(path.length());
boolean previousSlash = false;
for (int index = 0; index < path.length(); index++) {
char value = path.charAt(index);
if (value != '/' || !previousSlash) {
collapsed.append(value);
}
previousSlash = value == '/';
}
String normalized = StringUtils.cleanPath(collapsed.toString());
int end = normalized.length();
while (end > 0 && normalized.charAt(end - 1) == '/') {
end--;
}
return normalized.substring(0, end);
}

private static String readUpgradeAction(byte[] body) {
try {
String action = JSONUtil.parseObj(new String(body == null ? new byte[0] : body, StandardCharsets.UTF_8))
.getStr("action");
if (StrUtil.isNotBlank(action)) return action.trim();
} catch (RuntimeException ignored) {
// Invalid JSON and a missing action are both parameter errors.
}
throw new CryBusinessException(ErrorCode.PARAMETER, "固件升级操作缺少有效的 action");
}

private Object forward(String targetUrl, HttpServletRequest request, byte[] body) {
log.info("调用C++接口,URL: {}, Method: {}", targetUrl, request.getMethod());
HttpRequest httpRequest = HttpUtil.createRequest(Method.valueOf(request.getMethod()), targetUrl);
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
if ("Accept-Language".equalsIgnoreCase(headerName) || "Content-Type".equalsIgnoreCase(headerName)) {
httpRequest.header(headerName, request.getHeader(headerName));
}
}
if (HttpMethod.POST.matches(request.getMethod())) {
httpRequest.body(body);
}
try (HttpResponse response = httpRequest.execute()) {
return buildProxyResponse(response);
}
}

private Object buildProxyResponse(HttpResponse response) {
int status = response.getStatus();
String responseBody = response.body();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package com.opentest.controller;

import com.opentest.common.exception.CryBusinessException;
import com.opentest.common.exception.ErrorCode;
import com.opentest.service.CppHttpProxyService;
import com.opentest.service.jni.FirmwareUpgradeAccess;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.util.ReflectionTestUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

class CppHttpFirmwareUpgradeTest {
private static final String DEVICE = "192.0.2.50";
private static final String UPLOAD = "/api/system/upgrade/upload";
private static final String ACTION = "/api/system/upgrade/action";

private final CppHttpProxyService service = mock(CppHttpProxyService.class);
private final CppHttpController controller = new CppHttpController();

CppHttpFirmwareUpgradeTest() {
ReflectionTestUtils.setField(controller, "cppHttpProxyService", service);
}

@Test void uploadAndConfirmTakeTheSameGuardThroughNormalizedRoutes() {
when(service.openFirmwareTarget(DEVICE, UPLOAD)).thenThrow(new CryBusinessException(ErrorCode.JNI_DEVICE_BUSY));
when(service.openFirmwareTarget(DEVICE, ACTION)).thenThrow(new CryBusinessException(ErrorCode.JNI_DEVICE_BUSY));

assertBusy(UPLOAD + "/", new byte[]{1});
assertBusy(ACTION, bytes("{\"action\":\"Confirm\"}"));
verify(service).openFirmwareTarget(DEVICE, UPLOAD);
verify(service).openFirmwareTarget(DEVICE, ACTION);
verify(service, never()).buildTargetUrl(anyString(), anyString());
}

@Test void rejectsMalformedUpgradeActionsAsParameterErrors() {
assertEquals(ErrorCode.PARAMETER.getErrcode(), assertThrows(CryBusinessException.class,
() -> controller.proxyRequest(DEVICE, post(ACTION), bytes("not-json"))).getErrcode());
verifyNoInteractions(service);
}

@ParameterizedTest
@ValueSource(strings = {"/api//system/upgrade/upload", "/api/system/upgrade/%75pload", "/api/system/upgrade/./upload", "/api/system/upgrade/upload/"})
void equivalentUploadPathsCannotBypassTheGuard(String path) {
when(service.openFirmwareTarget(DEVICE, UPLOAD)).thenThrow(new CryBusinessException(ErrorCode.JNI_DEVICE_BUSY));
assertBusy(path, new byte[]{1});
verify(service).openFirmwareTarget(DEVICE, UPLOAD);
verify(service, never()).buildTargetUrl(anyString(), anyString());
}

@Test void holdsTheUpgradeReservationDuringForwardingAndAllowsCancelSeparately() throws Exception {
var access = new FirmwareUpgradeAccess();
var heldDuringUpload = new AtomicBoolean();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext(UPLOAD, exchange -> {
try (var activity = access.reserveActivity(List.of(DEVICE))) {
heldDuringUpload.set(false);
} catch (CryBusinessException busy) {
heldDuringUpload.set(busy.getErrcode() == ErrorCode.JNI_DEVICE_BUSY.getErrcode());
}
exchange.getRequestBody().readAllBytes();
reply(exchange);
});
server.createContext(ACTION, exchange -> {
exchange.getRequestBody().readAllBytes();
reply(exchange);
});
server.start();
try {
String base = "http://127.0.0.1:" + server.getAddress().getPort();
when(service.openFirmwareTarget(DEVICE, UPLOAD))
.thenAnswer(invocation -> new CppHttpProxyService.FirmwareTarget(base + UPLOAD, access.reserveUpgrade(DEVICE)));
when(service.buildTargetUrl(DEVICE, ACTION)).thenReturn(base + ACTION);

controller.proxyRequest(DEVICE, post(UPLOAD), new byte[]{1});
assertTrue(heldDuringUpload.get());
try (var activity = access.reserveActivity(List.of(DEVICE))) {
controller.proxyRequest(DEVICE, post(ACTION), bytes("{\"action\":\"cancel\"}"));
}
verify(service, never()).openFirmwareTarget(DEVICE, ACTION);
} finally {
server.stop(0);
}
}

private void assertBusy(String path, byte[] body) {
assertEquals(ErrorCode.JNI_DEVICE_BUSY.getErrcode(), assertThrows(CryBusinessException.class,
() -> controller.proxyRequest(DEVICE, post(path), body)).getErrcode());
}

private static MockHttpServletRequest post(String path) {
return new MockHttpServletRequest("POST", "/v1/cpp" + path);
}

private static byte[] bytes(String text) {
return text.getBytes(StandardCharsets.UTF_8);
}

private static void reply(HttpExchange exchange) throws IOException {
byte[] response = bytes("{\"code\":0}");
exchange.sendResponseHeaders(200, response.length);
try (var output = exchange.getResponseBody()) {
output.write(response);
}
}
}
Loading
Loading