跨域配置和fork修改为git原生fork

This commit is contained in:
lxp
2026-10-16 16:39:14 +08:00
parent 61c60f8052
commit 909abe9f1d
35 changed files with 2305 additions and 88 deletions
@@ -11,6 +11,9 @@ spring:
connection-timeout: 5000
community:
cors:
allowed-origins:
- https://vibemake.robotquan.com
oss:
root-directory: vibemake
gitea:
@@ -11,6 +11,9 @@ spring:
connection-timeout: 5000
community:
cors:
allowed-origins:
- https://dev-vibemake.robotquan.com
oss:
root-directory: vibemake_dev
gitea:
@@ -55,6 +55,12 @@ community:
gitea:
connect-timeout: 5s
request-timeout: 30s
fork:
git-executable: ${FORK_GIT_EXECUTABLE:git}
timeout: ${FORK_TIMEOUT:5m}
max-concurrent: ${FORK_MAX_CONCURRENT:2}
max-temporary-bytes: ${FORK_MAX_TEMPORARY_BYTES:5368709120}
temporary-directory: ${FORK_TEMPORARY_DIRECTORY:${java.io.tmpdir}/community-fork}
springdoc:
swagger-ui:
path: /swagger-ui.html
@@ -21,6 +21,7 @@ import com.linkerbot.community.service.ProjectService;
import com.linkerbot.community.service.ai.AiModelClient;
import com.linkerbot.community.service.ai.AiProjectAssistant;
import com.linkerbot.community.service.config.AiProperties;
import com.linkerbot.community.service.config.ForkProperties;
import com.linkerbot.community.service.gitea.GiteaClient.Change;
import com.linkerbot.community.service.mapper.ProjectMapper;
import com.linkerbot.community.service.mapper.UserMapper;
@@ -61,6 +62,8 @@ import org.springframework.test.web.servlet.*;
class AiSearchTest {
@TestConfiguration
static class Config {
@Bean @Primary FakeGitSnapshotCopier fakeSnapshots(FakeGiteaClient gitea) { return new FakeGitSnapshotCopier(gitea); }
@Bean @Primary FakeModel fakeModel() { return new FakeModel(); }
@Bean @Primary FakeGiteaClient fakeGitea() { return new FakeGiteaClient(); }
}
@@ -86,12 +89,17 @@ class AiSearchTest {
@Autowired FakeGiteaClient gitea;
@Autowired ProjectService projectService;
@Autowired AiProjectAssistant assistant;
@Autowired FakeGitSnapshotCopier snapshots;
@Autowired ForkProperties forkProperties;
private User user;
private String token;
@BeforeEach void reset() throws Exception {
SchemaSupport.reset(jdbc);
gitea.reset();
snapshots.available = true;
snapshots.beforePush = null;
forkProperties.setTimeout(Duration.ofMinutes(5));
user = new User();
user.setId(USER_SEQUENCE.incrementAndGet());
user.setUserCode(Codes.next());
@@ -178,6 +186,28 @@ class AiSearchTest {
return events.getLast();
}
@Test
void crossOriginSseKeepsCorsHeadersAcrossAsyncDispatch() throws Exception {
String origin = "https://dev-vibemake.robotquan.com";
MvcResult initial = mvc.perform(post("/api/community/ai/chat")
.header("Origin", origin)
.header("Authorization", "Bearer " + token)
.accept("text/event-stream")
.contentType("application/json")
.content(json.writeValueAsBytes(Map.of("message", "推荐机器人项目"))))
.andExpect(status().isOk())
.andExpect(request().asyncStarted())
.andExpect(header().string("Access-Control-Allow-Origin", origin))
.andReturn();
initial.getAsyncResult(6000);
mvc.perform(asyncDispatch(initial))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith("text/event-stream"))
.andExpect(header().string("Access-Control-Allow-Origin", origin))
.andExpect(header().exists("Access-Control-Expose-Headers"))
.andExpect(header().exists("X-Request-Id"));
}
private ObjectNode createIntent(String type, String name) {
return intent(type, List.of()).put("action", "CREATE").put("projectName", name)
.put("description", "计划用于机器人教学实验");
@@ -293,6 +323,45 @@ class AiSearchTest {
.containsExactly("understanding", "forking");
}
@Test void forkGetsItsOwnDeadlineAfterUnderstandingRatherThanTheSearchTimeout() throws Exception {
Project source = publishedRepository("教学项目");
properties.setSearchTimeout(Duration.ofMillis(150));
forkProperties.setTimeout(Duration.ofSeconds(2));
model.handler = (name, input) -> forkIntent(source.getProjectCode(), null);
snapshots.beforePush = () -> {
try { Thread.sleep(350); }
catch (InterruptedException error) { Thread.currentThread().interrupt(); throw new BusinessException(499, "FORK_CANCELLED", "已取消"); }
};
JsonNode result = finish(start(Map.of("message", "Fork " + source.getProjectCode()))).getLast();
assertThat(result.path("code").asText()).isEqualTo("OK");
assertThat(result.path("data").path("status").asText()).isEqualTo("FORKED");
}
@Test void disconnectDuringForkInterruptsItsWorkerAndFinishesTheProjectState() throws Exception {
Project source = publishedRepository("取消 Fork 测试");
model.handler = (name, input) -> forkIntent(source.getProjectCode(), null);
CountDownLatch entered = new CountDownLatch(1);
CountDownLatch interrupted = new CountDownLatch(1);
snapshots.beforePush = () -> {
entered.countDown();
try { new CountDownLatch(1).await(); }
catch (InterruptedException error) { interrupted.countDown(); Thread.currentThread().interrupt(); }
throw new BusinessException(499, "FORK_CANCELLED", "已取消");
};
MvcResult active = start(Map.of("message", "Fork " + source.getProjectCode()));
assertThat(entered.await(2, TimeUnit.SECONDS)).isTrue();
MockAsyncContext context = (MockAsyncContext) active.getRequest().getAsyncContext();
for (AsyncListener listener : context.getListeners()) listener.onError(new AsyncEvent(context, new IOException("closed")));
assertThat(interrupted.await(2, TimeUnit.SECONDS)).isTrue();
await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> {
List<Project> copies = projects.selectList(null).stream().filter(project -> !project.getProjectCode().equals(source.getProjectCode())).toList();
assertThat(copies).singleElement().satisfies(copy -> assertThat(copy.getRepoStatus()).isEqualTo("FAILED"));
});
snapshots.beforePush = null;
assertThat(finish(start(Map.of("message", "Fork " + source.getProjectCode()))).getLast()
.path("data").path("status").asText()).isEqualTo("FORKED");
}
@Test void forksCurrentPublicationRatherThanTheVersionShownPreviously() throws Exception {
Project source = publishedRepository("教学项目");
String latest = gitea.commit(projectService.repository(source),
@@ -0,0 +1,49 @@
package com.linkerbot.community.api;
import static org.assertj.core.api.Assertions.assertThat;
import com.linkerbot.community.security.CorsProperties;
import com.linkerbot.community.security.SecurityConfiguration;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
class CorsProfileTest {
@ParameterizedTest
@CsvSource({
"test, https://dev-vibemake.robotquan.com, https://vibemake.robotquan.com",
"prod, https://vibemake.robotquan.com, https://dev-vibemake.robotquan.com"
})
void profilesAllowOnlyTheirOwnHttpsFrontend(String profile, String allowedOrigin, String otherOrigin)
throws Exception {
StandardEnvironment environment = new StandardEnvironment();
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
for (PropertySource<?> source : loader.load(profile,
new ClassPathResource("application-" + profile + ".yml"))) {
environment.getPropertySources().addFirst(source);
}
CorsProperties properties = Binder.get(environment)
.bind("community.cors", Bindable.of(CorsProperties.class)).get();
assertThat(properties.getAllowedOrigins()).containsExactly(allowedOrigin);
UrlBasedCorsConfigurationSource source =
new SecurityConfiguration().corsConfigurationSource(properties);
CorsConfiguration configuration = source.getCorsConfiguration(
new MockHttpServletRequest("OPTIONS", "/api/workspace/projects"));
assertThat(configuration).isNotNull();
assertThat(configuration.checkOrigin(allowedOrigin)).isEqualTo(allowedOrigin);
assertThat(configuration.checkOrigin(otherOrigin)).isNull();
assertThat(configuration.checkOrigin(allowedOrigin.replace("https://", "http://"))).isNull();
assertThat(configuration.checkOrigin(allowedOrigin + ":8443")).isNull();
assertThat(configuration.checkOrigin("http://localhost:5173")).isNull();
}
}
@@ -0,0 +1,165 @@
package com.linkerbot.community.api;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest(properties = {
"spring.datasource.url=jdbc:h2:mem:cors;MODE=MySQL;DB_CLOSE_DELAY=-1",
"spring.datasource.username=sa",
"spring.datasource.password=",
"spring.datasource.driver-class-name=org.h2.Driver",
"community.ai.enabled=false",
"community.oss.enabled=false",
"logging.level.org.springframework=WARN"
})
@ActiveProfiles("test")
@AutoConfigureMockMvc(print = MockMvcPrint.NONE)
class CorsTest {
private static final String FRONTEND_ORIGIN = "https://dev-vibemake.robotquan.com";
@Autowired MockMvc mvc;
@ParameterizedTest
@CsvSource({
"GET, /api/users/me",
"HEAD, /api/workspace/projects",
"POST, /api/auth/login",
"POST, /api/community/ai/chat",
"PUT, /api/workspace/projects/example/publication",
"PATCH, /api/workspace/projects/example",
"DELETE, /api/workspace/projects/example",
"OPTIONS, /api/workspace/projects"
})
void preflightAllowsSupportedMethodsAndHeadersWithoutAuthentication(String method, String path)
throws Exception {
mvc.perform(options(path)
.header(HttpHeaders.ORIGIN, FRONTEND_ORIGIN)
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, method)
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS,
"authorization, content-type, accept"))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, FRONTEND_ORIGIN))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, containsString(method)))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, containsString("authorization")))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, containsString("content-type")))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, containsString("accept")))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600"))
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
}
@Test
void preflightRunsBeforeBearerTokenValidation() throws Exception {
mvc.perform(options("/api/users/me")
.header(HttpHeaders.ORIGIN, FRONTEND_ORIGIN)
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")
.header(HttpHeaders.AUTHORIZATION, "Bearer invalid-test-token"))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, FRONTEND_ORIGIN));
}
@Test
void publicResponsesExposeRequestIdAndDownloadHeaders() throws Exception {
mvc.perform(get("/api/project-types").header(HttpHeaders.ORIGIN, FRONTEND_ORIGIN))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value("OK"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, FRONTEND_ORIGIN))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, containsString("X-Request-Id")))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, containsString("Content-Disposition")))
.andExpect(header().exists("X-Request-Id"))
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
}
@Test
void unauthenticatedAndInvalidTokenResponsesKeepCorsHeaders() throws Exception {
mvc.perform(get("/api/users/me").header(HttpHeaders.ORIGIN, FRONTEND_ORIGIN))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.code").value("UNAUTHORIZED"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, FRONTEND_ORIGIN));
mvc.perform(get("/api/project-types")
.header(HttpHeaders.ORIGIN, FRONTEND_ORIGIN)
.header(HttpHeaders.AUTHORIZATION, "Bearer invalid-test-token"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.code").value("UNAUTHORIZED"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, FRONTEND_ORIGIN));
}
@Test
void validationErrorsKeepCorsHeaders() throws Exception {
mvc.perform(post("/api/auth/login")
.header(HttpHeaders.ORIGIN, FRONTEND_ORIGIN)
.contentType(MediaType.APPLICATION_JSON)
.content("{}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.code").value("BAD_REQUEST"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, FRONTEND_ORIGIN));
}
@ParameterizedTest
@ValueSource(strings = {
"https://untrusted.example",
"http://dev-vibemake.robotquan.com",
"https://vibemake.robotquan.com",
"http://localhost:5173",
"https://dev-vibemake.robotquan.com:8443",
"https://dev-vibemake.robotquan.com.untrusted.example",
"null"
})
void unlistedOriginsAreRejectedForPreflightAndActualRequests(String origin) throws Exception {
mvc.perform(options("/api/workspace/projects")
.header(HttpHeaders.ORIGIN, origin)
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST"))
.andExpect(status().isForbidden())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
mvc.perform(get("/api/project-types").header(HttpHeaders.ORIGIN, origin))
.andExpect(status().isForbidden())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@ParameterizedTest
@CsvSource({"TRACE, Authorization", "POST, X-Unapproved-Header"})
void unsupportedMethodsOrHeadersAreRejected(String method, String requestedHeader)
throws Exception {
mvc.perform(options("/api/workspace/projects")
.header(HttpHeaders.ORIGIN, FRONTEND_ORIGIN)
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, method)
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, requestedHeader))
.andExpect(status().isForbidden())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
void requestsWithoutOriginKeepExistingAuthenticationBehavior() throws Exception {
mvc.perform(get("/api/project-types"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value("OK"))
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
mvc.perform(get("/api/users/me"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.code").value("UNAUTHORIZED"))
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
void corsDoesNotExposeNonApiRoutes() throws Exception {
mvc.perform(get("/v3/api-docs").header(HttpHeaders.ORIGIN, FRONTEND_ORIGIN))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
@@ -0,0 +1,39 @@
package com.linkerbot.community.api;
import com.linkerbot.community.common.BusinessException;
import com.linkerbot.community.service.fork.ForkDeadline;
import com.linkerbot.community.service.fork.GitSnapshotCopier;
import com.linkerbot.community.service.gitea.GiteaClient;
import java.util.List;
import java.util.Map;
/** 业务测试只替换仓库传输,真实 Git/LFS 由独立协议测试覆盖。 */
final class FakeGitSnapshotCopier implements GitSnapshotCopier {
private final FakeGiteaClient gitea;
volatile boolean available = true;
volatile Runnable beforePush;
FakeGitSnapshotCopier(FakeGiteaClient gitea) { this.gitea = gitea; }
@Override public void checkAvailable() {
if (!available) throw new BusinessException(503, "FORK_UNAVAILABLE", "模拟 Git 依赖不可用");
}
@Override
public PreparedSnapshot prepare(GiteaClient.Repository source, String sha, String authorName, String authorCode, ForkDeadline deadline) {
deadline.check();
Map<String, byte[]> files = gitea.snapshot(source, sha);
return new PreparedSnapshot() {
@Override public String push(GiteaClient.Repository target) {
if (beforePush != null) beforePush.run();
deadline.beginWrite();
List<GiteaClient.Change> changes = files.entrySet().stream()
.map(file -> new GiteaClient.Change("create", file.getKey(), null, file.getValue())).toList();
String commit = gitea.commit(target, changes, "Fork community snapshot", authorName, authorCode).commitSha();
deadline.confirmWrite();
return commit;
}
@Override public void close() {}
};
}
}
@@ -45,6 +45,15 @@ final class FakeGiteaClient implements GiteaClient {
return repositories.get(repository.id());
}
synchronized Map<String, byte[]> snapshot(Repository repository, String sha) {
RepoData data = repo(repository);
Map<String, byte[]> snapshot = data == null ? null : data.snapshots.get(sha);
if (snapshot == null) throw new GiteaFailure(404, "NOT_FOUND", "发布版本不存在", false);
Map<String, byte[]> copy = new TreeMap<>();
snapshot.forEach((name, bytes) -> copy.put(name, bytes.clone()));
return copy;
}
@Override
public synchronized Repository createRepository(String name, boolean initialize) {
if (failNextCreate) {
@@ -8,9 +8,13 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.community.security.CaptchaService;
import com.linkerbot.community.service.config.CommunityProperties;
import com.linkerbot.community.service.fork.ForkDeadline;
import com.linkerbot.community.service.fork.GitCommandRunner;
import com.linkerbot.community.service.gitea.GiteaClient;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint;
@@ -26,6 +30,10 @@ import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilde
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.util.*;
@SpringBootTest(
@@ -34,6 +42,8 @@ import java.util.*;
"spring.datasource.username=sa",
"spring.datasource.password=",
"spring.datasource.driver-class-name=org.h2.Driver",
"community.ai.enabled=false",
"community.oss.enabled=false",
"logging.level.root=INFO",
"logging.level.org.springframework=WARN"
})
@@ -60,6 +70,9 @@ class GiteaLiveTest {
@Autowired ObjectMapper json;
@Autowired JdbcTemplate jdbc;
@Autowired CommunityProperties config;
@Autowired GitCommandRunner nativeGit;
@Autowired GiteaClient remote;
@TempDir Path gitFixtures;
@BeforeEach
void schema() throws Exception {
@@ -128,6 +141,122 @@ class GiteaLiveTest {
.asText();
}
@Test
void realSnapshotForkPreservesLargeCadGitlinksSymlinksAndLfsWithoutUnpublishedHistory() throws Exception {
String owner = login("live-snapshot-owner@example.invalid");
String other = login("live-snapshot-fork@example.invalid");
String source = perform(body(auth(post("/api/workspace/projects"), owner),
Map.of("name", "HyperDog OpenFish 类型快照联调", "projectType", "GENERAL")), 200).path("projectCode").asText();
String original = perform(auth(get("/api/workspace/projects/" + source + "/tree"), owner), 200).path("commitSha").asText();
Path staging = Files.createDirectory(gitFixtures.resolve("fixture.git"));
String base = config.getGitea().getBaseUrl().replaceAll("/+$", "");
String url = base + "/" + config.getGitea().getOwner() + "/p_" + source + ".git";
String basic = Base64.getEncoder().encodeToString((remote.authenticatedUsername() + ":" + config.getGitea().getToken())
.getBytes(StandardCharsets.UTF_8));
Map<String, String> settings = new LinkedHashMap<>();
settings.put("http." + base + "/.extraHeader", "Authorization: Basic " + basic);
settings.put("lfs.url", url + "/info/lfs");
settings.put("lfs.pushurl", url + "/info/lfs");
settings.put("lfs.basictransfersonly", "true");
fixtureGit(staging, settings, "init", "--bare", "--quiet");
fixtureGit(staging, settings, "remote", "add", "origin", url);
fixtureGit(staging, settings, "fetch", "--quiet", "origin", "refs/heads/main");
fixtureGit(staging, settings, "read-tree", original);
String ordinary = fixtureBlob(staging, settings, "published".getBytes(StandardCharsets.UTF_8));
String cad = fixtureBlob(staging, settings, new byte[13 * 1024 * 1024]);
String link = fixtureBlob(staging, settings, "README.md".getBytes(StandardCharsets.UTF_8));
byte[] lfsBytes = new byte[256 * 1024];
new Random(42).nextBytes(lfsBytes);
String oid = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(lfsBytes));
Path object = staging.resolve("lfs/objects/" + oid.substring(0, 2) + "/" + oid.substring(2, 4) + "/" + oid);
Files.createDirectories(object.getParent());
Files.write(object, lfsBytes);
String pointer = fixtureBlob(staging, settings, ("version https://git-lfs.github.com/spec/v1\noid sha256:" + oid
+ "\nsize " + lfsBytes.length + "\n").getBytes(StandardCharsets.UTF_8));
String attributes = fixtureBlob(staging, settings, "model.bin filter=lfs diff=lfs merge=lfs -text\n".getBytes(StandardCharsets.UTF_8));
Map<String, String> files = new LinkedHashMap<>();
files.put("README.md", "100644," + ordinary);
files.put("说明/示例.txt", "100644," + ordinary);
files.put("run.sh", "100755," + ordinary);
files.put("SOLIDWORKS_FILES/Assembly_#1.SLDASM", "100644," + cad);
files.put("readme-link", "120000," + link);
files.put("model.bin", "100644," + pointer);
files.put(".gitattributes", "100644," + attributes);
for (String path : List.of("uros/drive_base", "uros/micro-ROS-Agent", "uros/micro_ros_msgs", "uros_pkg/src/micro_ros_setup"))
files.put(path, "160000," + "a".repeat(40));
for (Map.Entry<String, String> file : files.entrySet()) {
String[] modeAndHash = file.getValue().split(",");
fixtureGit(staging, settings, "update-index", "--add", "--cacheinfo", modeAndHash[0], modeAndHash[1], file.getKey());
}
String tree = fixtureGit(staging, settings, "write-tree");
String publication = fixtureGit(staging, settings, "commit-tree", tree, "-p", original, "-m", "Special Git/LFS fixture");
fixtureGit(staging, settings, "update-ref", "refs/heads/fixture", publication);
fixtureGit(staging, settings, "lfs", "push", "--all", "origin", "refs/heads/fixture");
fixtureGit(staging, settings, "push", "--quiet", "origin", publication + ":refs/heads/main");
perform(body(auth(put("/api/workspace/projects/" + source + "/publication"), owner), Map.of("commitSha", publication)), 200);
perform(body(auth(post("/api/workspace/projects/" + source + "/commits"), owner), Map.of(
"expectedCommitSha", publication, "message", "unpublished change", "changes", List.of(Map.of(
"action", "UPDATE_FILE", "path", "README.md", "content", "private unpublished")))), 200);
Set<String> copies = new HashSet<>();
for (String token : List.of(owner, other)) {
JsonNode fork = perform(body(auth(post("/api/community/projects/" + source + "/forks"), token),
Map.of("name", "快照联调副本", "publishedCommitSha", publication)), 200);
String code = fork.path("projectCode").asText();
assertThat(copies.add(code)).isTrue();
assertThat(fork.path("repoStatus").asText()).isEqualTo("READY");
assertThat(fork.path("sourceCommitSha").asText()).isEqualTo(publication);
GiteaClient.Repository repository = new GiteaClient.Repository(0, config.getGitea().getOwner(), "p_" + code);
JsonNode metadata = readRepository("p_" + code, "");
assertThat(metadata.path("empty").asBoolean()).as("Gitea metadata empty; defaultBranch=%s", metadata.path("default_branch").asText()).isFalse();
String head = readRepository("p_" + code, "/branches/main").path("commit").path("id").asText();
JsonNode commit = readRepository("p_" + code, "/git/commits/" + head);
assertThat(commit.path("parents").isArray()).isTrue();
assertThat(commit.path("parents").isEmpty()).isTrue();
String copyRemote = "copy" + copies.size();
fixtureGit(staging, settings, "remote", "add", copyRemote, base + "/" + config.getGitea().getOwner() + "/p_" + code + ".git");
fixtureGit(staging, settings, "fetch", "--quiet", "--no-tags", copyRemote, "refs/heads/main");
assertThat(fixtureGit(staging, settings, "rev-parse", head + "^{tree}")).isEqualTo(tree);
assertThat(remote.history(repository, 1, 20).total()).isEqualTo(1);
JsonNode entries = readRepository("p_" + code, "/git/trees/" + head + "?recursive=true");
assertThat(entries.path("tree").findValuesAsText("mode")).contains("100755", "120000", "160000");
assertThat(perform(auth(get("/api/workspace/projects/" + code + "/files").param("path", "README.md"), token), 200)
.path("content").asText()).isEqualTo("published");
mvc.perform(auth(get("/api/workspace/projects/" + code + "/files")
.param("path", "SOLIDWORKS_FILES/Assembly_#1.SLDASM").param("download", "true"), token)).andExpect(status().is(413));
}
}
private String fixtureGit(Path staging, Map<String, String> settings, String... args) {
GitCommandRunner.Result result = nativeGit.run(staging, new ForkDeadline(Duration.ofMinutes(2)), "live-fixture", settings,
Map.of("GIT_AUTHOR_NAME", "Fixture", "GIT_AUTHOR_EMAIL", "fixture@users.community.invalid",
"GIT_COMMITTER_NAME", "Fixture", "GIT_COMMITTER_EMAIL", "fixture@users.community.invalid"), args);
assertThat(result.exitCode()).as("live Git fixture command completed").isZero();
return result.output();
}
private String fixtureBlob(Path staging, Map<String, String> settings, byte[] bytes) throws Exception {
Path input = Files.createTempFile(gitFixtures, "blob-", ".bin");
Files.write(input, bytes);
return fixtureGit(staging, settings, "hash-object", "-w", input.toString());
}
private JsonNode readRepository(String repository, String suffix) throws Exception {
String url = config.getGitea().getBaseUrl().replaceAll("/+$", "") + "/api/v1/repos/"
+ config.getGitea().getOwner() + "/" + repository + suffix;
HttpRequest request = HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(30))
.header("Authorization", "token " + config.getGitea().getToken()).GET().build();
HttpResponse<byte[]> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofByteArray());
if (response.statusCode() != 200) {
String diagnostic = new String(response.body(), StandardCharsets.UTF_8)
.replace(config.getGitea().getToken(), "[redacted]")
.replaceAll("(?im)(Authorization|Cookie|Set-Cookie):[^\\r\\n]*", "$1: [redacted]");
if (diagnostic.length() > 18000) diagnostic = diagnostic.substring(0, 18000);
assertThat(response.statusCode()).withFailMessage("Fixture Gitea response: %s", diagnostic).isEqualTo(200);
}
assertThat(response.statusCode()).isEqualTo(200);
return json.readTree(response.body());
}
@Test
void realOrganizationRepositoryCommitPublishUploadAndSnapshotFork() throws Exception {
String owner = login("live-owner@example.invalid"),
@@ -228,6 +357,8 @@ class GiteaLiveTest {
c.path("commitSha").asText())),
200);
String copy = fork.path("projectCode").asText();
readRepository("p_" + copy, "/contents/%E6%BA%90%E7%A0%81/hello%20world.txt?ref="
+ readRepository("p_" + copy, "/branches/main").path("commit").path("id").asText());
assertThat(
perform(
auth(
@@ -1,6 +1,7 @@
package com.linkerbot.community.api;
import static org.assertj.core.api.Assertions.*;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@@ -10,6 +11,7 @@ import com.linkerbot.community.security.CaptchaService;
import com.linkerbot.community.service.config.CommunityProperties;
import com.linkerbot.community.service.config.OssProperties;
import com.linkerbot.community.service.config.UrdfProperties;
import com.linkerbot.community.common.BusinessException;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
@@ -42,6 +44,8 @@ import java.util.concurrent.*;
class WorkflowTest {
@TestConfiguration
static class Config {
@Bean @Primary FakeGitSnapshotCopier fakeSnapshots(FakeGiteaClient gitea) { return new FakeGitSnapshotCopier(gitea); }
@Bean
@Primary
FakeOssObjectStore fakeOss() { return new FakeOssObjectStore(); }
@@ -71,11 +75,14 @@ class WorkflowTest {
@Autowired OssProperties oss;
@Autowired FakeOssObjectStore ossObjects;
@Autowired UrdfProperties urdfLimits;
@Autowired FakeGitSnapshotCopier snapshots;
@BeforeEach
void reset() throws Exception {
SchemaSupport.reset(jdbc);
gitea.reset();
snapshots.available = true;
snapshots.beforePush = null;
oss.setEnabled(false);
ossObjects.reset();
urdfLimits.setMaxFileBytes(52428800);
@@ -182,6 +189,54 @@ class WorkflowTest {
200);
}
@Test
void crossOriginLoginDownloadsAndBusinessErrorsKeepCorsHeaders() throws Exception {
String origin = "https://dev-vibemake.robotquan.com";
String captchaCode = perform(get("/api/auth/captcha").header("Origin", origin), 200)
.path("data").path("captchaCode").asText();
MvcResult loginResult = mvc.perform(body(post("/api/auth/login").header("Origin", origin),
Map.of("email", "cors-owner@example.invalid", "captchaCode", captchaCode,
"captchaAnswer", "ABCDE")))
.andExpect(status().isOk())
.andExpect(header().string("Access-Control-Allow-Origin", origin))
.andExpect(jsonPath("$.code").value("OK"))
.andReturn();
String owner = json.readTree(loginResult.getResponse().getContentAsString())
.path("data").path("token").asText();
String code = create(owner, "跨域下载项目");
mvc.perform(auth(get("/api/workspace/projects/" + code + "/files"), owner)
.header("Origin", origin)
.param("path", "README.md").param("download", "true"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM))
.andExpect(header().string("Content-Disposition", containsString("attachment")))
.andExpect(header().string("Access-Control-Allow-Origin", origin))
.andExpect(header().string("Access-Control-Expose-Headers", containsString("Content-Disposition")))
.andExpect(header().string("Access-Control-Expose-Headers", containsString("X-Request-Id")));
String other = login("cors-other@example.invalid");
mvc.perform(auth(get("/api/workspace/projects/" + code), other).header("Origin", origin))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.code").value("NOT_FOUND"))
.andExpect(header().string("Access-Control-Allow-Origin", origin));
mvc.perform(auth(get("/api/workspace/projects/missing-project"), owner).header("Origin", origin))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.code").value("NOT_FOUND"))
.andExpect(header().string("Access-Control-Allow-Origin", origin));
jdbc.update("UPDATE sys_user SET status = 'DISABLED' WHERE email = ?", "cors-other@example.invalid");
String disabledCaptchaCode = perform(get("/api/auth/captcha").header("Origin", origin), 200)
.path("data").path("captchaCode").asText();
mvc.perform(body(post("/api/auth/login").header("Origin", origin),
Map.of("email", "cors-other@example.invalid", "captchaCode", disabledCaptchaCode,
"captchaAnswer", "ABCDE")))
.andExpect(status().isForbidden())
.andExpect(jsonPath("$.code").value("ACCOUNT_DISABLED"))
.andExpect(header().string("Access-Control-Allow-Origin", origin));
}
@Test
void roboticArmTypeSupportsDiscoveryCreationEditingAndCommunityFiltering() throws Exception {
JsonNode types = perform(get("/api/project-types"), 200).path("data");
@@ -583,6 +638,43 @@ class WorkflowTest {
"SYS_USER", "PROJECT", "PROJECT_COMMENT", "PROJECT_LIKE");
}
@Test
void unavailableForkRejectsBeforeCreatingAnyProjectRecord() throws Exception {
String token = login("fork-runtime@example.invalid");
String source = create(token, "来源");
String sha = head(token, source);
publish(token, source, sha);
snapshots.available = false;
JsonNode error = perform(body(auth(post("/api/community/projects/" + source + "/forks"), token),
Map.of("name", "副本", "publishedCommitSha", sha)), 503);
assertThat(error.path("code").asText()).isEqualTo("FORK_UNAVAILABLE");
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM project", Integer.class)).isEqualTo(1);
}
@Test
void failedAndUncertainGitCopiesPreserveProjectCodeAndRepositoryAssociation() throws Exception {
String token = login("fork-status@example.invalid");
String source = create(token, "来源");
String sha = head(token, source);
publish(token, source, sha);
snapshots.beforePush = () -> { throw new BusinessException(502, "FORK_COPY_FAILED", "模拟复制失败"); };
JsonNode failed = perform(body(auth(post("/api/community/projects/" + source + "/forks"), token),
Map.of("name", "失败副本", "publishedCommitSha", sha)), 502);
String failedCode = failed.path("data").path("projectCode").asText();
assertThat(failed.path("code").asText()).isEqualTo("FORK_COPY_FAILED");
assertThat(jdbc.queryForObject("SELECT repo_status FROM project WHERE project_code = ?", String.class, failedCode)).isEqualTo("FAILED");
assertThat(jdbc.queryForObject("SELECT gitea_repo_id FROM project WHERE project_code = ?", Long.class, failedCode)).isPositive();
snapshots.beforePush = null;
gitea.timeoutNextCommit = true;
JsonNode unknown = perform(body(auth(post("/api/community/projects/" + source + "/forks"), token),
Map.of("name", "待核对副本", "publishedCommitSha", sha)), 504);
String unknownCode = unknown.path("data").path("projectCode").asText();
assertThat(unknown.path("code").asText()).isEqualTo("REMOTE_RESULT_UNKNOWN");
assertThat(jdbc.queryForObject("SELECT repo_status FROM project WHERE project_code = ?", String.class, unknownCode)).isEqualTo("CREATING");
assertThat(jdbc.queryForObject("SELECT gitea_repo_id FROM project WHERE project_code = ?", Long.class, unknownCode)).isPositive();
assertThat(jdbc.queryForObject("SELECT repo_status FROM project WHERE project_code = ?", String.class, source)).isEqualTo("READY");
}
@Test
void publishPinsFilesAndForkCopiesOnlyPublishedSnapshot() throws Exception {
String owner = login("owner@example.com");