后台管理初始化
This commit is contained in:
@@ -0,0 +1,183 @@
|
||||
package com.linkerbot.cadworld;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.cadworld.entity.OperationLog;
|
||||
import com.linkerbot.cadworld.service.OperationLogService;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@SpringBootTest(properties = {
|
||||
"spring.datasource.url=jdbc:h2:mem:admin;MODE=MySQL;DB_CLOSE_DELAY=-1",
|
||||
"spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.username=sa", "spring.datasource.password=",
|
||||
"spring.sql.init.mode=always", "spring.sql.init.schema-locations=classpath:test-schema.sql",
|
||||
"app.storage.provider=local", "app.storage.local-root=target/test-assets", "logging.file.path=target/test-logs"
|
||||
})
|
||||
@ActiveProfiles("verification")
|
||||
@AutoConfigureMockMvc
|
||||
class AdminApiTest {
|
||||
@Autowired MockMvc mvc;
|
||||
@Autowired ObjectMapper json;
|
||||
@Autowired JdbcTemplate jdbc;
|
||||
@Autowired OperationLogService logs;
|
||||
@Autowired TransactionTemplate transactions;
|
||||
|
||||
@BeforeEach
|
||||
void clean() {
|
||||
for (String table : new String[]{"component_asset", "component", "interface_definition_revision", "interface_definition_v2", "sys_user", "sys_operation_log"}) {
|
||||
jdbc.update("DELETE FROM " + table);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void userCrudFiltersAndLogicalDeletionKeepPhoneReserved() throws Exception {
|
||||
JsonNode created = send("/admin-api/users", Map.of("phone", "13812345678", "nickname", "测试用户"));
|
||||
long id = created.path("data").path("id").asLong();
|
||||
assertThat(created.path("data").path("status").asText()).isEqualTo("ACTIVE");
|
||||
assertThat(created.path("data").path("userType").asText()).isEqualTo("NORMAL");
|
||||
mvc.perform(put("/admin-api/users/{id}", id).contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"phone\":\"13812345678\",\"nickname\":\"管理员\",\"status\":\"DISABLED\",\"userType\":\"ADMIN\"}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.data.userType").value("ADMIN"));
|
||||
mvc.perform(get("/admin-api/users").param("keyword", "管理员").param("userType", "ADMIN").param("status", "DISABLED"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.data.total").value(1));
|
||||
mvc.perform(get("/admin-api/users/{id}", id)).andExpect(status().isOk());
|
||||
mvc.perform(delete("/admin-api/users/{id}", id)).andExpect(status().isOk());
|
||||
mvc.perform(get("/admin-api/users/{id}", id)).andExpect(status().isNotFound());
|
||||
mvc.perform(get("/admin-api/users")).andExpect(jsonPath("$.data.total").value(0));
|
||||
assertThat(jdbc.queryForObject("SELECT deleted FROM sys_user WHERE id=?", Integer.class, id)).isEqualTo(1);
|
||||
mvc.perform(post("/admin-api/users").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"phone\":\"13812345678\",\"nickname\":\"新用户\"}"))
|
||||
.andExpect(status().isConflict()).andExpect(jsonPath("$.code").value("USER_PHONE_DUPLICATE"));
|
||||
assertThat(logCount()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidUserFieldsEnumsAndPaginationAreRejected() throws Exception {
|
||||
for (String body : new String[]{
|
||||
"{\"phone\":\"123\",\"nickname\":\"x\"}",
|
||||
"{\"phone\":\"13812345678\",\"nickname\":\" \"}",
|
||||
"{\"phone\":\"13812345678\",\"nickname\":\"x\",\"status\":\"INVALID\"}",
|
||||
"{\"phone\":\"13812345678\",\"nickname\":\"x\",\"userType\":\"ROOT\"}"}) {
|
||||
mvc.perform(post("/admin-api/users").contentType(MediaType.APPLICATION_JSON).content(body)).andExpect(status().isUnprocessableEntity());
|
||||
}
|
||||
mvc.perform(get("/admin-api/users").param("page", "0")).andExpect(status().isUnprocessableEntity());
|
||||
mvc.perform(get("/admin-api/users").param("size", "0")).andExpect(status().isUnprocessableEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void componentCrudAndEveryFailureAreAuditedButReadsAreExcluded() throws Exception {
|
||||
JsonNode result = send("/admin-api/components", component("sample"));
|
||||
long id = result.path("data").path("id").asLong();
|
||||
assertThat(result.path("data").path("sourceUrl").asText()).contains("/admin-api/component-assets/");
|
||||
mvc.perform(put("/admin-api/components/{id}", id).contentType(MediaType.APPLICATION_JSON).content(json.writeValueAsString(component("renamed"))))
|
||||
.andExpect(status().isOk());
|
||||
mvc.perform(get("/admin-api/components")).andExpect(status().isOk());
|
||||
mvc.perform(get("/admin-api/components/{id}", id)).andExpect(status().isOk());
|
||||
mvc.perform(delete("/admin-api/components/{id}", id)).andExpect(status().isOk());
|
||||
mvc.perform(delete("/admin-api/components/{id}", id)).andExpect(status().isNotFound());
|
||||
mvc.perform(post("/admin-api/components").contentType(MediaType.APPLICATION_JSON).content("{}"))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
mvc.perform(post("/admin-api/components").contentType(MediaType.APPLICATION_JSON).content("{invalid"))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
assertThat(logCount()).isEqualTo(6);
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log WHERE success=FALSE", Long.class)).isEqualTo(3);
|
||||
mvc.perform(get("/admin-api/operation-logs").param("module", "COMPONENT").param("success", "false").param("operatorId", "0"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.data.total").value(3));
|
||||
Long logId = jdbc.queryForObject("SELECT MIN(id) FROM sys_operation_log", Long.class);
|
||||
mvc.perform(get("/admin-api/operation-logs/{id}", logId)).andExpect(status().isOk()).andExpect(jsonPath("$.data.operatorName").value("TEST_OPERATOR"));
|
||||
assertThat(logCount()).isEqualTo(6);
|
||||
}
|
||||
|
||||
@Test
|
||||
void interfaceRevisionsAndRejectedStaleEditsAreAudited() throws Exception {
|
||||
JsonNode request = json.readTree("""
|
||||
{"id":"mount","name":"安装接口","geometry":{"plane":{"pointM":[0,0,0],"outwardNormal":[0,0,1]},
|
||||
"holes":[{"id":"a","pointOnPlaneM":[-0.02,0,0],"axis":[0,0,1],"diameterM":0.004},
|
||||
{"id":"b","pointOnPlaneM":[0.02,0,0],"axis":[0,0,1],"diameterM":0.004}]},
|
||||
"tolerances":{"positionM":0.0002,"axisAngleRad":0.0174533,"planeAngleRad":0.0174533}}
|
||||
""");
|
||||
JsonNode created = send("/admin-api/interfaces", request).path("data");
|
||||
((com.fasterxml.jackson.databind.node.ObjectNode) created).put("name", "新版");
|
||||
mvc.perform(put("/admin-api/interfaces/mount").contentType(MediaType.APPLICATION_JSON).content(created.toString()))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.data.geometryRevision").value(2));
|
||||
mvc.perform(put("/admin-api/interfaces/mount").contentType(MediaType.APPLICATION_JSON).content(created.toString()))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM interface_definition_revision", Long.class)).isEqualTo(2);
|
||||
mvc.perform(get("/admin-api/interfaces")).andExpect(status().isOk());
|
||||
mvc.perform(delete("/admin-api/interfaces/mount")).andExpect(status().isOk());
|
||||
assertThat(logCount()).isEqualTo(4);
|
||||
// Historical revisions survive deletion and still prohibit ID reuse.
|
||||
mvc.perform(post("/admin-api/interfaces").contentType(MediaType.APPLICATION_JSON).content(request.toString()))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadWorkflowUsesAdminUrlsAndDoesNotStoreToken() throws Exception {
|
||||
JsonNode session = send("/admin-api/components/cover-image-upload-sessions", null).path("data");
|
||||
String token = session.path("uploadSessionToken").asText();
|
||||
JsonNode upload = send("/admin-api/components/cover-image-upload-sessions/upload-url",
|
||||
Map.of("uploadSessionToken", token, "objectPath", "cover.png", "contentType", "image/png")).path("data");
|
||||
assertThat(upload.path("uploadUrl").asText()).contains("/admin-api/component-assets/upload");
|
||||
String key = upload.path("objectKey").asText();
|
||||
mvc.perform(put("/admin-api/component-assets/upload").param("objectKey", key).contentType("image/png").content(new byte[]{1, 2, 3}))
|
||||
.andExpect(status().isNoContent());
|
||||
send("/admin-api/components/cover-image-upload-sessions/complete", Map.of("uploadSessionToken", token, "objectKeys", new String[]{key}));
|
||||
mvc.perform(get("/admin-api/component-assets/" + key)).andExpect(status().isOk()).andExpect(content().bytes(new byte[]{1, 2, 3}));
|
||||
assertThat(logCount()).isEqualTo(4);
|
||||
assertThat(jdbc.queryForList("SELECT * FROM sys_operation_log").toString()).doesNotContain(token);
|
||||
}
|
||||
|
||||
@Test
|
||||
void requiresNewLogSurvivesOuterRollbackAndOldRoutesAreAbsent() throws Exception {
|
||||
transactions.executeWithoutResult(tx -> {
|
||||
jdbc.update("INSERT INTO sys_user(phone,nickname,status,user_type,deleted) VALUES ('13912345678','rollback','ACTIVE','NORMAL',0)");
|
||||
OperationLog event = new OperationLog();
|
||||
event.setModule("COMPONENT"); event.setAction("CREATE"); event.setOperatorId(0L); event.setOperatorName("TEST_OPERATOR");
|
||||
event.setRequestPath("/admin-api/components"); event.setRequestMethod("POST"); event.setOperatedAt(java.time.LocalDateTime.now());
|
||||
event.setDurationMs(1L); event.setSuccess(false); event.setHttpStatus(422);
|
||||
logs.record(event);
|
||||
tx.setRollbackOnly();
|
||||
});
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_user", Long.class)).isZero();
|
||||
assertThat(logCount()).isEqualTo(1);
|
||||
for (String path : new String[]{"/api/interfaces", "/api/components", "/api/component-assets/a", "/api/auth/me", "/api/projects"}) {
|
||||
mvc.perform(get(path)).andExpect(status().isNotFound());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void analysisAndPoseCalculationsAreExcludedFromAudit() throws Exception {
|
||||
mvc.perform(multipart("/admin-api/interface-brep/analyze")
|
||||
.file(new org.springframework.mock.web.MockMultipartFile("file", "bad.stl", "application/octet-stream", new byte[]{1})))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
mvc.perform(post("/admin-api/interfaces/missing/pose-candidates").contentType(MediaType.APPLICATION_JSON).content("{}"))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
assertThat(logCount()).isZero();
|
||||
}
|
||||
|
||||
private JsonNode send(String path, Object body) throws Exception {
|
||||
var request = post(path);
|
||||
if (body != null) request.contentType(MediaType.APPLICATION_JSON).content(json.writeValueAsString(body));
|
||||
return json.readTree(mvc.perform(request).andExpect(status().isOk()).andReturn().getResponse().getContentAsString());
|
||||
}
|
||||
|
||||
private Map<String, Object> component(String name) {
|
||||
return Map.of("componentName", name, "robotType", "humanoid", "company", "test", "model", "m1", "source", "components/sample.rfs",
|
||||
"componentJson", Map.of("interfaces", new Object[0]), "assemblyMetadata", Map.of("tags", new String[]{"test"}, "capabilities", new Object[0], "dimensions", Map.of()));
|
||||
}
|
||||
|
||||
private long logCount() { return jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log", Long.class); }
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.linkerbot.cadworld;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.sql.DriverManager;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.jdbc.datasource.init.ScriptUtils;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
/** Opt-in integration profile: dedicated disposable MySQL schema and MinIO bucket only. */
|
||||
@SpringBootTest(properties = {
|
||||
"spring.datasource.url=${cadworld.it.db-url:jdbc:mysql://127.0.0.1:13306/cadworld_verification?serverTimezone=Asia/Shanghai}",
|
||||
"spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver",
|
||||
"spring.datasource.username=${cadworld.it.db-user:root}", "spring.datasource.password=${cadworld.it.db-password:}",
|
||||
"spring.sql.init.mode=never", "app.storage.provider=minio",
|
||||
"app.minio.endpoint=${cadworld.it.minio-endpoint:http://127.0.0.1:19000}",
|
||||
"app.minio.access-key=${cadworld.it.minio-user:cadworld-test}", "app.minio.secret-key=${cadworld.it.minio-password:cadworld-test-secret}",
|
||||
"app.minio.bucket=cadworld-verification", "logging.file.path=target/integration-logs"
|
||||
})
|
||||
class ExternalServicesIT extends AdminApiTest {
|
||||
@BeforeAll
|
||||
static void prepareAndVerifySql() throws Exception {
|
||||
String url = System.getProperty("cadworld.it.db-url", "jdbc:mysql://127.0.0.1:13306/cadworld_verification?serverTimezone=Asia/Shanghai");
|
||||
// Refuse accidental execution against the shared cadworld database.
|
||||
if (!url.matches("jdbc:mysql://[^/]+/cadworld_verification(?:\\?.*)?")) {
|
||||
throw new IllegalArgumentException("Integration database must be named cadworld_verification");
|
||||
}
|
||||
Path db = Path.of(System.getProperty("cadworld.project-root", "..")).resolve("db");
|
||||
try (var connection = DriverManager.getConnection(url, System.getProperty("cadworld.it.db-user", "root"), System.getProperty("cadworld.it.db-password", ""));
|
||||
var statement = connection.createStatement()) {
|
||||
statement.execute("DROP TABLE IF EXISTS component_asset, component, interface_definition_revision, interface_definition_v2, sys_operation_log, sys_user");
|
||||
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("init.sql")));
|
||||
statement.executeUpdate("INSERT INTO sys_user(phone,nickname,status,user_type) VALUES ('13800000000','sentinel','ACTIVE','NORMAL')");
|
||||
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("init.sql")));
|
||||
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("upgrade.sql")));
|
||||
try (var result = statement.executeQuery("SELECT COUNT(*) FROM sys_user WHERE nickname='sentinel' AND deleted=0")) {
|
||||
result.next(); assertThat(result.getInt(1)).isEqualTo(1);
|
||||
}
|
||||
// Simulate precisely the supplied pre-upgrade tables while retaining a real user row.
|
||||
statement.execute("DROP TABLE component_asset, interface_definition_revision, interface_definition_v2, sys_operation_log");
|
||||
statement.execute("ALTER TABLE sys_user DROP COLUMN deleted");
|
||||
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("upgrade.sql")));
|
||||
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("upgrade.sql")));
|
||||
try (var result = statement.executeQuery("SELECT COUNT(*) FROM sys_user WHERE nickname='sentinel' AND deleted=0")) {
|
||||
result.next(); assertThat(result.getInt(1)).isEqualTo(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.linkerbot.cadworld;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
|
||||
"spring.datasource.url=jdbc:h2:mem:upload-http;MODE=MySQL;DB_CLOSE_DELAY=-1",
|
||||
"spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.username=sa", "spring.datasource.password=",
|
||||
"spring.sql.init.mode=always", "spring.sql.init.schema-locations=classpath:test-schema.sql",
|
||||
"spring.servlet.multipart.max-file-size=1KB", "spring.servlet.multipart.max-request-size=2KB",
|
||||
"app.storage.provider=local", "app.storage.local-root=target/test-http-assets", "logging.file.path=target/test-logs"
|
||||
})
|
||||
@ActiveProfiles("verification")
|
||||
class UploadHttpTest {
|
||||
@Autowired TestRestTemplate http;
|
||||
@Autowired JdbcTemplate jdbc;
|
||||
|
||||
@Test
|
||||
void realServletMultipartSizeFailureReturns413AndPersistsAudit() {
|
||||
var body = new LinkedMultiValueMap<String, Object>();
|
||||
body.add("file", new ByteArrayResource(new byte[4096]) {
|
||||
@Override public String getFilename() { return "oversize.step"; }
|
||||
});
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
|
||||
var response = http.postForEntity("/admin-api/interfaces/missing/assets?geometryRevision=1", new HttpEntity<>(body, headers), String.class);
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.PAYLOAD_TOO_LARGE);
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log WHERE module='INTERFACE' AND action='UPLOAD' AND http_status=413 AND success=FALSE AND target_id='missing'", Long.class))
|
||||
.isEqualTo(1);
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.linkerbot.cadworld.audit;
|
||||
|
||||
import com.linkerbot.cadworld.config.AdminOperatorProperties;
|
||||
import com.linkerbot.cadworld.service.AdminOperatorProvider;
|
||||
import com.linkerbot.cadworld.service.OperationLogService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class OperationAuditInterceptorTest {
|
||||
@Test
|
||||
void multipartFailureBeforeMvcIsAuditedOnce() throws Exception {
|
||||
OperationLogService service = mock(OperationLogService.class);
|
||||
OperationAuditInterceptor audit = new OperationAuditInterceptor(service, new AdminOperatorProvider(new AdminOperatorProperties(0, "TEST_OPERATOR")));
|
||||
var mappings = mock(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.class);
|
||||
var request = new MockHttpServletRequest("POST", "/admin-api/components");
|
||||
var response = new MockHttpServletResponse();
|
||||
var handler = new HandlerMethod(this, getClass().getDeclaredMethod("operation"));
|
||||
when(mappings.getHandler(request)).thenReturn(new org.springframework.web.servlet.HandlerExecutionChain(handler));
|
||||
var filter = new EarlyFailureAuditFilter(mappings, audit);
|
||||
filter.doFilter(request, response, (req, res) -> ((jakarta.servlet.http.HttpServletResponse) res).setStatus(413));
|
||||
var captured = org.mockito.ArgumentCaptor.forClass(com.linkerbot.cadworld.entity.OperationLog.class);
|
||||
verify(service).record(captured.capture());
|
||||
assertThat(captured.getValue().getSuccess()).isFalse();
|
||||
assertThat(captured.getValue().getHttpStatus()).isEqualTo(413);
|
||||
}
|
||||
|
||||
@Test
|
||||
void logFailureDoesNotChangeTheBusinessResponse() throws Exception {
|
||||
OperationLogService service = mock(OperationLogService.class);
|
||||
doThrow(new IllegalStateException("database unavailable")).when(service).record(any());
|
||||
OperationAuditInterceptor audit = new OperationAuditInterceptor(service, new AdminOperatorProvider(new AdminOperatorProperties(0, "TEST_OPERATOR")));
|
||||
var request = new MockHttpServletRequest("POST", "/admin-api/components");
|
||||
var response = new MockHttpServletResponse();
|
||||
var handler = new HandlerMethod(this, getClass().getDeclaredMethod("operation"));
|
||||
audit.preHandle(request, response, handler);
|
||||
audit.afterCompletion(request, response, handler, null);
|
||||
verify(service).record(any());
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "CREATE")
|
||||
void operation() { }
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.linkerbot.cadworld.mechanicalinterface;
|
||||
|
||||
import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.linkerbot.cadworld.controller.InterfacePoseController;
|
||||
import com.linkerbot.cadworld.service.InterfaceDefinitionService;
|
||||
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class InterfaceBoundaryTest {
|
||||
final ObjectMapper mapper=new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
|
||||
final MechanicalInterfaceSolver solver=new MechanicalInterfaceSolver();
|
||||
final MountGeometry geometry=new MountGeometry(new Plane(new double[3],new double[]{0,0,1}),List.of(
|
||||
new Hole("a",new double[]{-.02,0,0},new double[]{0,0,1},.004),
|
||||
new Hole("b",new double[]{.02,0,0},new double[]{0,0,1},.004)));
|
||||
final Definition definition=new Definition("two",1,"two",geometry,Tolerances.defaults());
|
||||
|
||||
@Test void endpointsRejectUnknownRotationEvenWhenGlobalJacksonIgnoresUnknownFields(){
|
||||
InterfaceDefinitionService definitions=mock(InterfaceDefinitionService.class);
|
||||
InterfacePoseController controller=new InterfacePoseController(definitions,solver,mapper);
|
||||
ObjectNode request=mapper.valueToTree(new PoseRequest(1,"base",geometry,"sha"));
|
||||
request.put("mountRotationRpy",0);
|
||||
assertThatThrownBy(()->controller.candidates("two",request)).hasMessageContaining("不支持");
|
||||
verifyNoInteractions(definitions);
|
||||
}
|
||||
@Test void confirmationRecomputesTransformAndMappingFromCandidateId(){
|
||||
PoseCandidate chosen=solver.enumeratePortPoses(definition,new PoseRequest(1,"base",geometry,"sha")).candidates().get(0);
|
||||
Port submitted=new Port("port","base","two",1,geometry,
|
||||
new SelectedPose(chosen.id(),new RigidPose(new double[]{99,99,99},new double[4]),List.of(),chosen.orientationDirectionInLink()),"sha",SOLVER_VERSION);
|
||||
Port confirmed=solver.confirmPortPose(definition,submitted);
|
||||
assertThat(confirmed.selectedPose().templateInLink().positionM()).containsExactly(chosen.templateInLink().positionM());
|
||||
assertThat(confirmed.selectedPose().holeMapping()).isEqualTo(chosen.holeMapping());
|
||||
InterfaceDefinitionService definitions=mock(InterfaceDefinitionService.class);
|
||||
assertThatThrownBy(()->new InterfacePoseController(definitions,solver,mapper).confirm("another",mapper.valueToTree(submitted)))
|
||||
.hasMessageContaining("不一致");
|
||||
}
|
||||
@Test void confirmFlattensCascaderPathTargetsBeforeStrictPortBinding(){
|
||||
PoseCandidate chosen=solver.enumeratePortPoses(definition,new PoseRequest(1,"base",geometry,"sha")).candidates().get(0);
|
||||
ObjectNode request=mapper.valueToTree(new Port("port","base","two",1,geometry,
|
||||
new SelectedPose(chosen.id(),chosen.templateInLink(),chosen.holeMapping(),chosen.orientationDirectionInLink()),"sha",SOLVER_VERSION,
|
||||
List.of("humanoid/left_arm")));
|
||||
request.set("connectableTargets",mapper.createArrayNode().add(mapper.createArrayNode().add("humanoid").add("left_arm")));
|
||||
InterfaceDefinitionService definitions=mock(InterfaceDefinitionService.class);
|
||||
when(definitions.geometryDefinition("two",1)).thenReturn(definition);
|
||||
Port confirmed=new InterfacePoseController(definitions,solver,mapper).confirm("two",request).getData();
|
||||
assertThat(confirmed.connectableTargets()).containsExactly("humanoid/left_arm");
|
||||
}
|
||||
@Test void storedBytesAreVerifiedAndUnsafeStorageKeysNeverFetched() throws Exception {
|
||||
byte[] bytes="real mesh bytes".getBytes(StandardCharsets.UTF_8);
|
||||
String hash=HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
ObjectStorageClient storage=mock(ObjectStorageClient.class);
|
||||
doAnswer(invocation->{invocation.<OutputStream>getArgument(1).write(bytes);return null;}).when(storage).writeObjectTo(eq("objects/mesh"),any());
|
||||
UrdfAssetVerifier verifier=new UrdfAssetVerifier(storage);
|
||||
ObjectNode source=mapper.createObjectNode();source.putArray("resources").addObject().put("reference","a.stl").put("sourceKey","objects/mesh").put("sha256",hash);
|
||||
verifier.verify(source);
|
||||
((ObjectNode)source.path("resources").get(0)).put("sha256","tampered");
|
||||
assertThatThrownBy(()->verifier.verify(source)).hasMessageContaining("已变化");
|
||||
clearInvocations(storage);
|
||||
for(String key:List.of("https://remote.test/a","/etc/passwd","objects/../secret","objects\\secret")) {
|
||||
((ObjectNode)source.path("resources").get(0)).put("sourceKey",key);
|
||||
assertThatThrownBy(()->verifier.verify(source)).hasMessageContaining("存储对象");
|
||||
}
|
||||
verifyNoInteractions(storage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
-- Run against a selected empty cadworld database. No database is created or selected here.
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `sys_user` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`phone` varchar(32) NOT NULL,
|
||||
`nickname` varchar(64) NOT NULL,
|
||||
`status` varchar(32) NOT NULL DEFAULT 'ACTIVE',
|
||||
`deleted` tinyint NOT NULL DEFAULT 0,
|
||||
`user_type` varchar(32) NOT NULL DEFAULT 'NORMAL',
|
||||
`created_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`updated_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_sys_user_phone` (`phone`)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `component` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`component_name` varchar(64) NOT NULL DEFAULT '',
|
||||
`category` varchar(64) NOT NULL,
|
||||
`robot_type` varchar(32) NOT NULL DEFAULT 'humanoid',
|
||||
`company` varchar(64) NOT NULL DEFAULT '',
|
||||
`model` varchar(64) NOT NULL DEFAULT '',
|
||||
`source` varchar(255) NOT NULL DEFAULT '',
|
||||
`cover_image_key` varchar(512) NOT NULL DEFAULT '',
|
||||
`description` text NOT NULL,
|
||||
`component_json` LONGTEXT NOT NULL,
|
||||
`assembly_metadata` LONGTEXT NOT NULL,
|
||||
`created_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`updated_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_component_type_company` (`category`,`company`),
|
||||
KEY `idx_component_type_model` (`category`,`model`),
|
||||
KEY `idx_component_robot_type_component_type` (`robot_type`,`category`)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS interface_definition_v2 (
|
||||
id VARCHAR(64) NOT NULL PRIMARY KEY,
|
||||
name VARCHAR(128) NOT NULL,
|
||||
description VARCHAR(500) NULL,
|
||||
geometry_revision INT NOT NULL,
|
||||
geometry_json LONGTEXT NOT NULL,
|
||||
tolerances_json LONGTEXT NOT NULL,
|
||||
connectable_targets_json LONGTEXT NULL,
|
||||
display_forward_json LONGTEXT NULL,
|
||||
source_asset_key VARCHAR(512) NULL,
|
||||
source_geometry_hash VARCHAR(128) NULL,
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS interface_definition_revision (
|
||||
id VARCHAR(96) NOT NULL PRIMARY KEY,
|
||||
definition_id VARCHAR(64) NOT NULL,
|
||||
geometry_revision INT NOT NULL,
|
||||
definition_json LONGTEXT NOT NULL,
|
||||
UNIQUE KEY uk_interface_geometry_revision (definition_id, geometry_revision)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS component_asset (
|
||||
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
component_id BIGINT NOT NULL,
|
||||
object_key VARCHAR(512) NOT NULL,
|
||||
relative_path VARCHAR(512) NOT NULL,
|
||||
asset_kind VARCHAR(32) NOT NULL,
|
||||
content_type VARCHAR(128) NULL,
|
||||
size BIGINT NOT NULL DEFAULT 0,
|
||||
sha256 VARCHAR(128) NULL,
|
||||
is_primary TINYINT NOT NULL DEFAULT 0,
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||
CONSTRAINT fk_component_asset_component FOREIGN KEY (component_id) REFERENCES component(id) ON DELETE CASCADE,
|
||||
UNIQUE KEY uk_component_asset_object_key (object_key),
|
||||
KEY idx_component_asset_component (component_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sys_operation_log (
|
||||
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
module VARCHAR(32) NOT NULL,
|
||||
action VARCHAR(32) NOT NULL,
|
||||
target_id VARCHAR(512) NULL,
|
||||
operator_id BIGINT NOT NULL,
|
||||
operator_name VARCHAR(64) NOT NULL,
|
||||
request_path VARCHAR(512) NOT NULL,
|
||||
request_method VARCHAR(16) NOT NULL,
|
||||
client_ip VARCHAR(64) NULL,
|
||||
request_id VARCHAR(64) NULL,
|
||||
operated_at DATETIME(3) NOT NULL,
|
||||
duration_ms BIGINT NOT NULL,
|
||||
success TINYINT NOT NULL,
|
||||
http_status INT NOT NULL,
|
||||
error_summary VARCHAR(1000) NULL,
|
||||
KEY idx_operation_module_time (module, operated_at),
|
||||
KEY idx_operation_operator_time (operator_id, operated_at),
|
||||
KEY idx_operation_result_time (success, operated_at)
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user