社区初始化

This commit is contained in:
lxp
2026-10-14 10:26:20 +08:00
parent fc95e7968b
commit e23d249bd0
60 changed files with 4994 additions and 1 deletions
@@ -0,0 +1,62 @@
package com.linkerbot.community.api;
import com.linkerbot.community.bean.Contracts.*;
import com.linkerbot.community.bean.entity.User;
import com.linkerbot.community.common.ApiResponse;
import com.linkerbot.community.security.*;
import com.linkerbot.community.service.UserService;
import com.linkerbot.community.service.config.CommunityProperties;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirements;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
@RestController
@RequiredArgsConstructor
@Tag(name = "登录与用户")
public class AuthController {
private final CaptchaService captcha;
private final TokenService tokens;
private final UserService users;
private final CommunityProperties config;
@GetMapping("/api/auth/captcha")
@Operation(summary = "获取一次性图片验证码")
@SecurityRequirements
public ApiResponse<CaptchaView> captcha() {
return ApiResponse.success(captcha.issue());
}
@PostMapping("/api/auth/login")
@Operation(summary = "邮箱和图片验证码登录,首次自动创建用户")
@SecurityRequirements
public ApiResponse<LoginView> login(@Valid @RequestBody LoginRequest input) {
captcha.verify(input.captchaCode(), input.captchaAnswer());
User user = users.login(input.email());
return ApiResponse.success(
new LoginView(
tokens.issue(user.getId()),
"Bearer",
config.getTokenTtl().toSeconds(),
users.view(user)));
}
@PostMapping("/api/auth/logout")
@Operation(summary = "退出登录")
public ApiResponse<Void> logout(@RequestHeader("Authorization") String authorization) {
tokens.revoke(authorization.startsWith("Bearer ") ? authorization.substring(7) : null);
return ApiResponse.success(null);
}
@GetMapping("/api/users/me")
@Operation(summary = "当前用户")
public ApiResponse<UserView> me() {
return ApiResponse.success(users.view(users.require(CurrentUser.required())));
}
}
@@ -0,0 +1,16 @@
package com.linkerbot.community.api;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
@MapperScan("com.linkerbot.community.service.mapper")
@SpringBootApplication(
scanBasePackages = "com.linkerbot.community",
exclude = UserDetailsServiceAutoConfiguration.class)
public class CommunityApplication {
public static void main(String[] args) {
SpringApplication.run(CommunityApplication.class, args);
}
}
@@ -0,0 +1,131 @@
package com.linkerbot.community.api;
import com.linkerbot.community.bean.Contracts.*;
import com.linkerbot.community.common.*;
import com.linkerbot.community.security.CurrentUser;
import com.linkerbot.community.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirements;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequiredArgsConstructor
@Tag(name = "社区")
public class CommunityController {
private final ProjectService projects;
private final FileService files;
private final InteractionService interactions;
@GetMapping("/api/project-types")
@Operation(summary = "配置中的项目类型")
@SecurityRequirements
public ApiResponse<List<TypeView>> types() {
return ApiResponse.success(projects.types());
}
@GetMapping("/api/community/projects")
@Operation(summary = "已发布项目列表,支持类型和关键词筛选")
@SecurityRequirements
public ApiResponse<PageResponse<ProjectView>> list(
@RequestParam(defaultValue = "1") long page,
@RequestParam(defaultValue = "20") long size,
@RequestParam(required = false) String type,
@RequestParam(required = false) String keyword) {
return ApiResponse.success(
projects.list(null, type, keyword, page, size, CurrentUser.optional()));
}
@GetMapping("/api/community/projects/{projectCode}")
@Operation(summary = "社区项目详情")
@SecurityRequirements
public ApiResponse<ProjectView> detail(@PathVariable String projectCode) {
return ApiResponse.success(
projects.view(projects.published(projectCode), CurrentUser.optional()));
}
@GetMapping("/api/community/projects/{projectCode}/tree")
@Operation(summary = "已发布版本的目录")
@SecurityRequirements
public ApiResponse<TreeView> tree(
@PathVariable String projectCode,
@RequestParam(defaultValue = "") String path,
@RequestParam(required = false) String commitSha) {
rejectRef(commitSha);
return ApiResponse.success(files.communityTree(projectCode, path));
}
@GetMapping("/api/community/projects/{projectCode}/files")
@Operation(summary = "已发布版本文件,download=true 时下载")
@SecurityRequirements
public ResponseEntity<?> file(
@PathVariable String projectCode,
@RequestParam String path,
@RequestParam(defaultValue = "false") boolean download,
@RequestParam(required = false) String commitSha) {
rejectRef(commitSha);
return download
? WorkspaceController.download(files.communityFile(projectCode, path))
: ResponseEntity.ok(
ApiResponse.success(files.communityFileView(projectCode, path)));
}
private void rejectRef(String sha) {
if (sha != null) throw BusinessException.badRequest("社区文件仅允许读取当前已发布版本");
}
@PostMapping("/api/community/projects/{projectCode}/forks")
@Operation(summary = "复制已发布文件到我的工作区")
public ApiResponse<ProjectView> fork(
@PathVariable String projectCode, @Valid @RequestBody ForkInput input) {
return ApiResponse.success(projects.fork(CurrentUser.required(), projectCode, input));
}
@GetMapping("/api/community/projects/{projectCode}/comments")
@Operation(summary = "评论列表")
@SecurityRequirements
public ApiResponse<PageResponse<CommentView>> comments(
@PathVariable String projectCode,
@RequestParam(defaultValue = "1") long page,
@RequestParam(defaultValue = "20") long size) {
return ApiResponse.success(interactions.list(projectCode, page, size));
}
@PostMapping("/api/community/projects/{projectCode}/comments")
@Operation(summary = "新增纯文本评论")
public ApiResponse<CommentView> comment(
@PathVariable String projectCode, @Valid @RequestBody CommentInput input) {
return ApiResponse.success(
interactions.comment(CurrentUser.required(), projectCode, input));
}
@DeleteMapping("/api/comments/{commentCode}")
@Operation(summary = "删除自己的评论")
public ApiResponse<Void> deleteComment(@PathVariable String commentCode) {
interactions.deleteComment(CurrentUser.required(), commentCode);
return ApiResponse.success(null);
}
@PutMapping("/api/community/projects/{projectCode}/like")
@Operation(summary = "幂等点赞")
public ApiResponse<Void> like(@PathVariable String projectCode) {
interactions.like(CurrentUser.required(), projectCode);
return ApiResponse.success(null);
}
@DeleteMapping("/api/community/projects/{projectCode}/like")
@Operation(summary = "幂等取消点赞")
public ApiResponse<Void> unlike(@PathVariable String projectCode) {
interactions.unlike(CurrentUser.required(), projectCode);
return ApiResponse.success(null);
}
}
@@ -0,0 +1,30 @@
package com.linkerbot.community.api;
import io.swagger.v3.oas.models.*;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.*;
import org.springframework.context.annotation.*;
@Configuration
public class OpenApiConfiguration {
@Bean
public OpenAPI openAPI() {
return new OpenAPI()
.info(
new Info()
.title("Community 首期接口")
.version("v1")
.description(
"四表社区后端。登录仅邮箱和图片验证码,无法验证邮箱归属。Gitea"
+ " 仓库统一存放在组织下。文件下载返回二进制,其余响应使用统一包装。"))
.components(
new Components()
.addSecuritySchemes(
"bearer",
new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")))
.addSecurityItem(new SecurityRequirement().addList("bearer"));
}
}
@@ -0,0 +1,32 @@
package com.linkerbot.community.api;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import java.util.List;
@Configuration(proxyBeanMethods = false)
@Profile("prod")
public class ProductionConfiguration {
public ProductionConfiguration(Environment environment) {
for (String property :
List.of(
"spring.datasource.url",
"spring.datasource.username",
"spring.datasource.password",
"community.gitea.base-url",
"community.gitea.token")) {
String value;
try {
value = environment.getRequiredProperty(property);
} catch (IllegalArgumentException | IllegalStateException error) {
// 仅提示配置项名称,避免异常链携带配置值。
throw new IllegalStateException("生产环境必须配置 " + property);
}
if (value.isBlank()) {
throw new IllegalStateException("生产环境必须配置 " + property);
}
}
}
}
@@ -0,0 +1,158 @@
package com.linkerbot.community.api;
import com.linkerbot.community.bean.Contracts.*;
import com.linkerbot.community.common.*;
import com.linkerbot.community.security.CurrentUser;
import com.linkerbot.community.service.*;
import com.linkerbot.community.service.gitea.GiteaClient;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.nio.charset.StandardCharsets;
import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/workspace/projects")
@Tag(name = "我的工作区")
public class WorkspaceController {
private final ProjectService projects;
private final FileService files;
@GetMapping
@Operation(summary = "我的项目列表")
public ApiResponse<PageResponse<ProjectView>> list(
@RequestParam(defaultValue = "1") long page,
@RequestParam(defaultValue = "20") long size,
@RequestParam(required = false) String type,
@RequestParam(required = false) String keyword) {
long user = CurrentUser.required();
return ApiResponse.success(projects.list(user, type, keyword, page, size, user));
}
@PostMapping
@Operation(summary = "创建项目和组织中的私有仓库")
public ApiResponse<ProjectView> create(@Valid @RequestBody ProjectInput input) {
return ApiResponse.success(projects.create(CurrentUser.required(), input));
}
@GetMapping("/{projectCode}")
@Operation(summary = "我的项目详情")
public ApiResponse<ProjectView> detail(@PathVariable String projectCode) {
long user = CurrentUser.required();
return ApiResponse.success(projects.view(projects.owner(user, projectCode), user));
}
@PatchMapping("/{projectCode}")
@Operation(summary = "修改名称、描述和类型")
public ApiResponse<ProjectView> update(
@PathVariable String projectCode, @Valid @RequestBody ProjectInput input) {
return ApiResponse.success(projects.update(CurrentUser.required(), projectCode, input));
}
@DeleteMapping("/{projectCode}")
@Operation(summary = "逻辑删除项目并撤回社区")
public ApiResponse<Void> delete(@PathVariable String projectCode) {
projects.delete(CurrentUser.required(), projectCode);
return ApiResponse.success(null);
}
@GetMapping("/{projectCode}/tree")
@Operation(summary = "读取目录,可指定本项目 Commit")
public ApiResponse<TreeView> tree(
@PathVariable String projectCode,
@RequestParam(defaultValue = "") String path,
@RequestParam(required = false) String commitSha) {
return ApiResponse.success(
files.ownerTree(CurrentUser.required(), projectCode, path, commitSha));
}
@GetMapping("/{projectCode}/files")
@Operation(summary = "读取文件,download=true 时下载")
public ResponseEntity<?> file(
@PathVariable String projectCode,
@RequestParam String path,
@RequestParam(required = false) String commitSha,
@RequestParam(defaultValue = "false") boolean download) {
long user = CurrentUser.required();
if (!download)
return ResponseEntity.ok(
ApiResponse.success(files.ownerFileView(user, projectCode, path, commitSha)));
return download(files.ownerFile(user, projectCode, path, commitSha));
}
public static ResponseEntity<byte[]> download(GiteaClient.StoredFile file) {
String name = file.path().substring(file.path().lastIndexOf('/') + 1);
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(
HttpHeaders.CONTENT_DISPOSITION,
ContentDisposition.attachment()
.filename(name, StandardCharsets.UTF_8)
.build()
.toString())
.body(file.bytes());
}
@PostMapping("/{projectCode}/commits")
@Operation(summary = "多文件变更提交为一个 Commit")
public ApiResponse<CommitView> commit(
@PathVariable String projectCode, @Valid @RequestBody CommitInput input) {
return ApiResponse.success(files.commit(CurrentUser.required(), projectCode, input));
}
@GetMapping("/{projectCode}/commits")
@Operation(summary = "main 提交历史")
public ApiResponse<PageResponse<HistoryEntry>> history(
@PathVariable String projectCode,
@RequestParam(defaultValue = "1") long page,
@RequestParam(defaultValue = "20") long size) {
return ApiResponse.success(files.history(CurrentUser.required(), projectCode, page, size));
}
@PostMapping(
value = "/{projectCode}/uploads/commit",
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(summary = "上传或替换文件并一次提交")
public ApiResponse<CommitView> upload(
@PathVariable String projectCode,
@RequestParam String expectedCommitSha,
@RequestParam String message,
@RequestParam(defaultValue = "") String directory,
@RequestParam("files") List<MultipartFile> uploaded,
@RequestParam(required = false) List<String> paths) {
return ApiResponse.success(
files.upload(
CurrentUser.required(),
projectCode,
expectedCommitSha,
message,
directory,
uploaded,
paths));
}
@PutMapping("/{projectCode}/publication")
@Operation(summary = "发布或手动更新社区文件版本")
public ApiResponse<ProjectView> publish(
@PathVariable String projectCode, @Valid @RequestBody PublicationInput input) {
return ApiResponse.success(
projects.publish(CurrentUser.required(), projectCode, input.commitSha()));
}
@DeleteMapping("/{projectCode}/publication")
@Operation(summary = "撤回社区")
public ApiResponse<Void> withdraw(@PathVariable String projectCode) {
projects.withdraw(CurrentUser.required(), projectCode);
return ApiResponse.success(null);
}
}
@@ -0,0 +1,23 @@
spring:
datasource:
url: ${DB_URL}
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
pool-name: CommunityHikariCP
minimum-idle: 1
maximum-pool-size: 20
connection-timeout: 5000
community:
gitea:
base-url: ${GITEA_BASE_URL}
owner: ${GITEA_ORGANIZATION:community}
token: ${GITEA_TOKEN}
logging:
file:
path: ${LOG_PATH:logs/prod}
level:
com.linkerbot.community: INFO
@@ -0,0 +1,23 @@
spring:
datasource:
url: ${DB_URL:jdbc:mysql://localhost:3306/community?useUnicode=true&characterEncoding=utf8&connectionTimeZone=UTC}
username: ${DB_USERNAME:root}
password: ${DB_PASSWORD:}
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
pool-name: CommunityHikariCP
minimum-idle: 1
maximum-pool-size: 10
connection-timeout: 5000
community:
gitea:
base-url: ${GITEA_BASE_URL:http://localhost:3000}
owner: ${GITEA_ORGANIZATION:community}
token: ${GITEA_TOKEN:}
logging:
file:
path: ${LOG_PATH:logs/test}
level:
com.linkerbot.community: DEBUG
@@ -0,0 +1,45 @@
server:
port: ${SERVER_PORT:${PORT:8993}}
spring:
application:
name: community
profiles:
default: test
sql:
init:
mode: never
servlet:
multipart:
max-file-size: 10MB
max-request-size: 52MB
jackson:
time-zone: UTC
main:
banner-mode: off
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
community:
types:
GENERAL: 通用
HUMANOID: 人形
QUADRUPED: 四足
WHEELED: 轮式
captcha-ttl: 2m
token-ttl: 24h
max-text-bytes: 1048576
max-file-bytes: 10485760
max-request-bytes: 52428800
gitea:
connect-timeout: 5s
request-timeout: 30s
springdoc:
swagger-ui:
path: /swagger-ui.html
logging:
level:
root: INFO
org.springframework: INFO
# 测试环境开启项目 DEBUG 时,不输出 SQL 参数或完整请求内容。
com.linkerbot.community.service.mapper: INFO
org.springframework.web: INFO
@@ -0,0 +1,149 @@
package com.linkerbot.community.api;
import com.linkerbot.community.bean.Contracts.*;
import com.linkerbot.community.common.PageResponse;
import com.linkerbot.community.service.gitea.*;
import java.security.MessageDigest;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
final class FakeGiteaClient implements GiteaClient {
private static final class RepoData {
Repository repository;
String head;
Map<String, Map<String, byte[]>> snapshots = new HashMap<>();
List<HistoryEntry> history = new ArrayList<>();
}
private final Map<Long, RepoData> repositories = new HashMap<>();
private final AtomicLong sequence = new AtomicLong();
boolean timeoutNextCommit;
boolean timeoutNextCreate;
boolean failNextCreate;
void reset() {
repositories.clear();
timeoutNextCommit = false;
timeoutNextCreate = false;
failNextCreate = false;
}
private String sha() {
return String.format("%040x", sequence.incrementAndGet());
}
private String blob(byte[] data) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(data));
} catch (Exception error) {
throw new IllegalStateException(error);
}
}
private RepoData repo(Repository repository) {
return repositories.get(repository.id());
}
@Override
public synchronized Repository createRepository(String name, boolean initialize) {
if (failNextCreate) {
failNextCreate = false;
throw new GiteaFailure(502, "GITEA_ERROR", "服务拒绝请求", false);
}
RepoData data = new RepoData();
data.repository = new Repository(sequence.incrementAndGet(), "community", name);
repositories.put(data.repository.id(), data);
if (initialize)
commit(
data.repository,
List.of(new Change("create", "README.md", null, "initial".getBytes())),
"Initial commit",
"system",
"system");
if (timeoutNextCreate) {
timeoutNextCreate = false;
throw new GiteaFailure(504, "REMOTE_RESULT_UNKNOWN", "创建结果未知", true);
}
return data.repository;
}
@Override
public synchronized String head(Repository repository) {
return repo(repository).head;
}
@Override
public synchronized List<TreeEntry> tree(Repository repository, String sha, String path) {
Map<String, byte[]> snapshot = repo(repository).snapshots.get(sha);
if (snapshot == null) throw new GiteaFailure(404, "NOT_FOUND", "版本不存在", false);
String prefix = path.isEmpty() ? "" : path + "/";
Map<String, TreeEntry> entries = new TreeMap<>();
for (Map.Entry<String, byte[]> file : snapshot.entrySet()) {
if (!file.getKey().startsWith(prefix)) continue;
String remainder = file.getKey().substring(prefix.length());
int separator = remainder.indexOf('/');
String name = separator < 0 ? remainder : remainder.substring(0, separator);
String entryPath = prefix + name;
entries.put(
entryPath,
separator < 0
? new TreeEntry(
entryPath,
name,
"file",
file.getValue().length,
blob(file.getValue()))
: new TreeEntry(entryPath, name, "dir", 0, ""));
}
return new ArrayList<>(entries.values());
}
@Override
public synchronized StoredFile file(Repository repository, String sha, String path) {
Map<String, byte[]> snapshot = repo(repository).snapshots.get(sha);
byte[] bytes = snapshot == null ? null : snapshot.get(path);
if (bytes == null) throw new GiteaFailure(404, "NOT_FOUND", "文件不存在", false);
return new StoredFile(path, blob(bytes), bytes.clone());
}
@Override
public synchronized CommitView commit(
Repository repository,
List<Change> changes,
String message,
String authorName,
String authorCode) {
RepoData repo = repo(repository);
Map<String, byte[]> snapshot =
repo.head == null ? new TreeMap<>() : new TreeMap<>(repo.snapshots.get(repo.head));
for (Change change : changes) {
byte[] old = snapshot.get(change.path());
if (change.operation().equals("create") && old != null)
throw new GiteaFailure(409, "GITEA_CONFLICT", "文件已存在", false);
if (!change.operation().equals("create")
&& (old == null || !blob(old).equals(change.blobSha())))
throw new GiteaFailure(409, "GITEA_CONFLICT", "文件版本冲突", false);
if (change.operation().equals("delete")) snapshot.remove(change.path());
else snapshot.put(change.path(), change.bytes().clone());
}
repo.head = sha();
repo.snapshots.put(repo.head, snapshot);
repo.history.addFirst(
new HistoryEntry(repo.head, message, authorName, "2026-10-13T00:00:00Z"));
if (timeoutNextCommit) {
timeoutNextCommit = false;
throw new GiteaFailure(504, "REMOTE_RESULT_UNKNOWN", "提交结果未知", true);
}
return new CommitView(repo.head, message);
}
@Override
public synchronized PageResponse<HistoryEntry> history(
Repository repository, long page, long size) {
List<HistoryEntry> history = repo(repository).history;
int from = (int) Math.min(history.size(), (page - 1) * size);
int to = (int) Math.min(history.size(), from + size);
return new PageResponse<>(history.subList(from, to), page, size, history.size());
}
}
@@ -0,0 +1,261 @@
package com.linkerbot.community.api;
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.*;
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 org.junit.jupiter.api.*;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
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.*;
import org.springframework.context.annotation.*;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.*;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
import java.util.*;
@SpringBootTest(
properties = {
"spring.datasource.url=jdbc:h2:mem:live;MODE=MySQL;DB_CLOSE_DELAY=-1",
"spring.datasource.username=sa",
"spring.datasource.password=",
"spring.datasource.driver-class-name=org.h2.Driver",
"logging.level.root=INFO",
"logging.level.org.springframework=WARN"
})
@ActiveProfiles("test")
@AutoConfigureMockMvc(print = MockMvcPrint.NONE)
@Import(GiteaLiveTest.Config.class)
@EnabledIfEnvironmentVariable(named = "COMMUNITY_LIVE_GITEA", matches = "true")
class GiteaLiveTest {
@TestConfiguration
static class Config {
@Bean
@Primary
CaptchaService liveCaptcha(CommunityProperties properties) {
return new CaptchaService(properties) {
@Override
protected String generateAnswer() {
return "ABCDE";
}
};
}
}
@Autowired MockMvc mvc;
@Autowired ObjectMapper json;
@Autowired JdbcTemplate jdbc;
@Autowired CommunityProperties config;
@BeforeEach
void schema() throws Exception {
SchemaSupport.reset(jdbc);
}
@AfterEach
void removeOnlyRepositoriesCreatedByThisTest() throws Exception {
HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
for (String repo : jdbc.queryForList("SELECT gitea_repo_name FROM project", String.class)) {
if (!repo.matches("p_[0-9a-f]{32}")) throw new IllegalStateException("拒绝清理非测试仓库");
HttpRequest request =
HttpRequest.newBuilder(
URI.create(
config.getGitea().getBaseUrl()
+ "/api/v1/repos/"
+ config.getGitea().getOwner()
+ "/"
+ repo))
.timeout(Duration.ofSeconds(30))
.header("Authorization", "token " + config.getGitea().getToken())
.DELETE()
.build();
assertThat(http.send(request, HttpResponse.BodyHandlers.discarding()).statusCode())
.isIn(204, 404);
}
}
private MockHttpServletRequestBuilder body(MockHttpServletRequestBuilder request, Object body)
throws Exception {
return request.contentType(MediaType.APPLICATION_JSON)
.content(json.writeValueAsBytes(body));
}
private MockHttpServletRequestBuilder auth(
MockHttpServletRequestBuilder request, String token) {
return request.header("Authorization", "Bearer " + token);
}
private JsonNode perform(MockHttpServletRequestBuilder request, int expected) throws Exception {
MvcResult result = mvc.perform(request).andReturn();
JsonNode response = json.readTree(result.getResponse().getContentAsByteArray());
assertThat(result.getResponse().getStatus())
.withFailMessage(
"请求失败 code=%s requestId=%s",
response.path("code").asText(), response.path("requestId").asText())
.isEqualTo(expected);
return response.path("data");
}
private String login(String email) throws Exception {
String captcha = perform(get("/api/auth/captcha"), 200).path("captchaCode").asText();
return perform(
body(
post("/api/auth/login"),
Map.of(
"email",
email,
"captchaCode",
captcha,
"captchaAnswer",
"ABCDE")),
200)
.path("token")
.asText();
}
@Test
void realOrganizationRepositoryCommitPublishUploadAndSnapshotFork() throws Exception {
String owner = login("live-owner@example.invalid"),
other = login("live-fork@example.invalid");
String code =
perform(
body(
auth(post("/api/workspace/projects"), owner),
Map.of("name", "集成测试临时项目", "projectType", "GENERAL")),
200)
.path("projectCode")
.asText();
String a =
perform(auth(get("/api/workspace/projects/" + code + "/tree"), owner), 200)
.path("commitSha")
.asText();
JsonNode before =
perform(
auth(
get("/api/workspace/projects/" + code + "/files")
.param("path", "README.md"),
owner),
200);
perform(
body(
auth(put("/api/workspace/projects/" + code + "/publication"), owner),
Map.of("commitSha", a)),
200);
JsonNode b =
perform(
body(
auth(post("/api/workspace/projects/" + code + "/commits"), owner),
Map.of(
"expectedCommitSha",
a,
"message",
"集成验证多文件提交",
"changes",
List.of(
Map.of(
"action",
"UPDATE_FILE",
"path",
"README.md",
"content",
"unpublished"),
Map.of("action", "CREATE_DIRECTORY", "path", "空目录"),
Map.of(
"action",
"CREATE_FILE",
"path",
"源码/hello world.txt",
"content",
"你好")))),
200);
assertThat(
perform(
get("/api/community/projects/" + code + "/files")
.param("path", "README.md"),
200)
.path("content")
.asText())
.isEqualTo(before.path("content").asText());
byte[] binary = {0, 1, 2, 3, 4};
MockMultipartFile upload =
new MockMultipartFile("files", "part.bin", "application/octet-stream", binary);
JsonNode c =
perform(
auth(
multipart("/api/workspace/projects/" + code + "/uploads/commit")
.file(upload)
.param("message", "验证二进制")
.param("expectedCommitSha", b.path("commitSha").asText())
.param("directory", "模型"),
owner),
200);
mvc.perform(
auth(
get("/api/workspace/projects/" + code + "/files")
.param("path", "模型/part.bin")
.param("download", "true"),
owner))
.andExpect(status().isOk())
.andExpect(content().bytes(binary));
perform(
body(
auth(put("/api/workspace/projects/" + code + "/publication"), owner),
Map.of("commitSha", c.path("commitSha").asText())),
200);
JsonNode fork =
perform(
body(
auth(post("/api/community/projects/" + code + "/forks"), other),
Map.of(
"name",
"集成测试临时副本",
"publishedCommitSha",
c.path("commitSha").asText())),
200);
String copy = fork.path("projectCode").asText();
assertThat(
perform(
auth(
get("/api/workspace/projects/" + copy + "/files")
.param("path", "源码/hello world.txt"),
other),
200)
.path("content")
.asText())
.isEqualTo("你好");
mvc.perform(
auth(
get("/api/workspace/projects/" + copy + "/files")
.param("path", "模型/part.bin")
.param("download", "true"),
other))
.andExpect(status().isOk())
.andExpect(content().bytes(binary));
assertThat(
perform(
auth(
get("/api/workspace/projects/" + code + "/commits"),
owner),
200)
.path("total")
.asLong())
.isGreaterThanOrEqualTo(3);
perform(auth(delete("/api/workspace/projects/" + code + "/publication"), owner), 200);
perform(get("/api/community/projects/" + code), 404);
perform(auth(get("/api/workspace/projects/" + copy + "/tree"), other), 200);
}
}
@@ -0,0 +1,28 @@
package com.linkerbot.community.api;
import org.springframework.jdbc.core.JdbcTemplate;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.*;
final class SchemaSupport {
static void reset(JdbcTemplate jdbc) throws IOException {
Path path = Path.of("../docs/database.md");
if (!Files.exists(path)) path = Path.of("docs/database.md");
String content = Files.readString(path);
Matcher matcher = Pattern.compile("CREATE TABLE [\\s\\S]*?;").matcher(content);
jdbc.execute("DROP ALL OBJECTS");
int tables = 0;
while (matcher.find()) {
String ddl =
matcher.group()
.replaceAll(" COMMENT '[^']*'", "")
.replaceAll("\\) ENGINE=InnoDB[^;]*;", ");");
jdbc.execute(ddl);
tables++;
}
if (tables != 4) throw new IllegalStateException("必须只有四张业务表");
}
}
@@ -0,0 +1,601 @@
package com.linkerbot.community.api;
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.*;
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 org.junit.jupiter.api.*;
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.*;
import org.springframework.context.annotation.*;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.*;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import java.util.*;
import java.util.concurrent.*;
@SpringBootTest(
properties = {
"spring.datasource.url=jdbc:h2:mem:workflow;MODE=MySQL;DB_CLOSE_DELAY=-1",
"spring.datasource.username=sa",
"spring.datasource.password=",
"spring.datasource.driver-class-name=org.h2.Driver",
"logging.level.root=INFO",
"logging.level.org.springframework=WARN"
})
@ActiveProfiles("test")
@AutoConfigureMockMvc(print = MockMvcPrint.NONE)
@Import(WorkflowTest.Config.class)
class WorkflowTest {
@TestConfiguration
static class Config {
@Bean
@Primary
FakeGiteaClient fakeGitea() {
return new FakeGiteaClient();
}
@Bean
@Primary
CaptchaService fixedCaptcha(CommunityProperties properties) {
return new CaptchaService(properties) {
@Override
protected String generateAnswer() {
return "ABCDE";
}
};
}
}
@Autowired MockMvc mvc;
@Autowired ObjectMapper json;
@Autowired JdbcTemplate jdbc;
@Autowired FakeGiteaClient gitea;
@BeforeEach
void reset() throws Exception {
SchemaSupport.reset(jdbc);
gitea.reset();
}
private JsonNode perform(MockHttpServletRequestBuilder builder, int status) throws Exception {
String body =
mvc.perform(builder)
.andExpect(status().is(status))
.andReturn()
.getResponse()
.getContentAsString();
return body.isEmpty() ? json.createObjectNode() : json.readTree(body);
}
private MockHttpServletRequestBuilder body(MockHttpServletRequestBuilder request, Object body)
throws Exception {
return request.contentType(MediaType.APPLICATION_JSON)
.content(json.writeValueAsBytes(body));
}
private JsonNode loginData(String email) throws Exception {
String captcha =
perform(get("/api/auth/captcha"), 200).path("data").path("captchaCode").asText();
return perform(
body(
post("/api/auth/login"),
Map.of(
"email",
email,
"captchaCode",
captcha,
"captchaAnswer",
"abcde")),
200)
.path("data");
}
private String login(String email) throws Exception {
return loginData(email).path("token").asText();
}
private MockHttpServletRequestBuilder auth(
MockHttpServletRequestBuilder request, String token) {
return request.header("Authorization", "Bearer " + token);
}
private String create(String token, String name) throws Exception {
JsonNode result =
perform(
body(
auth(post("/api/workspace/projects"), token),
Map.of(
"name",
name,
"description",
"测试项目",
"projectType",
"GENERAL")),
200);
assertThat(result.path("data").has("id")).isFalse();
return result.path("data").path("projectCode").asText();
}
private String head(String token, String code) throws Exception {
return perform(auth(get("/api/workspace/projects/" + code + "/tree"), token), 200)
.path("data")
.path("commitSha")
.asText();
}
private String commit(String token, String code, String expected, String content)
throws Exception {
return perform(
body(
auth(post("/api/workspace/projects/" + code + "/commits"), token),
Map.of(
"expectedCommitSha",
expected,
"message",
"修改说明",
"changes",
List.of(
Map.of(
"action",
"UPDATE_FILE",
"path",
"README.md",
"content",
content)))),
200)
.path("data")
.path("commitSha")
.asText();
}
private void publish(String token, String code, String sha) throws Exception {
perform(
body(
auth(put("/api/workspace/projects/" + code + "/publication"), token),
Map.of("commitSha", sha)),
200);
}
@Test
void loginNormalizesEmailAndConsumesCaptchaAndLogout() throws Exception {
JsonNode first = loginData("OWNER@example.com");
JsonNode second = loginData("owner@example.com");
assertThat(first.path("user").path("userCode").asText())
.isEqualTo(second.path("user").path("userCode").asText());
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_user", Long.class)).isEqualTo(1L);
JsonNode challenge = perform(get("/api/auth/captcha"), 200).path("data");
assertThat(challenge.path("image").asText()).startsWith("data:image/png;base64,");
Map<String, String> input =
Map.of(
"email",
"test@example.com",
"captchaCode",
challenge.path("captchaCode").asText(),
"captchaAnswer",
"WRONG");
perform(body(post("/api/auth/login"), input), 400);
perform(
body(
post("/api/auth/login"),
Map.of(
"email",
"test@example.com",
"captchaCode",
challenge.path("captchaCode").asText(),
"captchaAnswer",
"ABCDE")),
400);
String token = first.path("token").asText();
JsonNode me = perform(auth(get("/api/users/me"), token), 200).path("data");
assertThat(me.has("id")).isFalse();
perform(auth(post("/api/auth/logout"), token), 200);
perform(auth(get("/api/users/me"), token), 401);
perform(get("/api/workspace/projects"), 401);
}
@Test
void openApiMatchesRoutesAndPublicAuthenticationAndOnlyFourTablesExist() throws Exception {
JsonNode spec = perform(get("/v3/api-docs"), 200);
assertThat(spec.path("paths").has("/api/workspace/projects")).isTrue();
assertThat(spec.path("paths").has("/api/repository-operations/{operationCode}")).isFalse();
assertThat(spec.path("paths").path("/api/auth/login").path("post").path("security").size())
.isZero();
assertThat(spec.path("security").size()).isEqualTo(1);
assertThat(
jdbc.queryForList(
"SELECT table_name FROM information_schema.tables WHERE"
+ " table_schema='PUBLIC'",
String.class))
.containsExactlyInAnyOrder(
"SYS_USER", "PROJECT", "PROJECT_COMMENT", "PROJECT_LIKE");
}
@Test
void publishPinsFilesAndForkCopiesOnlyPublishedSnapshot() throws Exception {
String owner = login("owner@example.com");
String other = login("other@example.com");
String code = create(owner, "测试项目");
String a = head(owner, code);
publish(owner, code, a);
String b = commit(owner, code, a, "未发布内容");
JsonNode file =
perform(
get("/api/community/projects/" + code + "/files")
.param("path", "README.md"),
200)
.path("data");
assertThat(file.path("content").asText()).isEqualTo("initial");
assertThat(file.path("commitSha").asText()).isEqualTo(a);
perform(
get("/api/community/projects/" + code + "/files")
.param("path", "README.md")
.param("commitSha", b),
400);
JsonNode fork =
perform(
body(
auth(
post("/api/community/projects/" + code + "/forks"),
other),
Map.of("publishedCommitSha", a, "name", "我的副本")),
200)
.path("data");
String copy = fork.path("projectCode").asText();
assertThat(fork.path("sourceProjectCode").asText()).isEqualTo(code);
assertThat(
perform(
auth(
get("/api/workspace/projects/" + copy + "/files")
.param("path", "README.md"),
other),
200)
.path("data")
.path("content")
.asText())
.isEqualTo("initial");
publish(owner, code, b);
assertThat(
perform(
get("/api/community/projects/" + code + "/files")
.param("path", "README.md"),
200)
.path("data")
.path("content")
.asText())
.isEqualTo("未发布内容");
perform(
body(
auth(post("/api/community/projects/" + code + "/forks"), other),
Map.of("publishedCommitSha", a, "name", "过时副本")),
409);
perform(auth(delete("/api/workspace/projects/" + code), owner), 200);
perform(get("/api/community/projects/" + code), 404);
perform(auth(get("/api/workspace/projects/" + copy + "/tree"), other), 200);
}
@Test
void permissionsAndFlatCommentsAndIdempotentLikes() throws Exception {
String owner = login("owner@example.com");
String other = login("other@example.com");
String code = create(owner, "权限项目");
perform(auth(get("/api/workspace/projects/" + code), other), 404);
perform(auth(get("/api/workspace/projects/" + code + "/tree"), other), 404);
perform(auth(delete("/api/workspace/projects/" + code), other), 404);
perform(get("/api/community/projects/" + code), 404);
publish(owner, code, head(owner, code));
perform(put("/api/community/projects/" + code + "/like"), 401);
perform(auth(put("/api/community/projects/" + code + "/like"), other), 200);
perform(auth(put("/api/community/projects/" + code + "/like"), other), 200);
assertThat(
perform(get("/api/community/projects/" + code), 200)
.path("data")
.path("likeCount")
.asLong())
.isEqualTo(1);
JsonNode comment =
perform(
body(
auth(
post(
"/api/community/projects/"
+ code
+ "/comments"),
other),
Map.of("content", "纯文本评论")),
200)
.path("data");
assertThat(comment.path("author").has("email")).isFalse();
assertThat(comment.path("author").has("id")).isFalse();
String commentCode = comment.path("commentCode").asText();
perform(auth(delete("/api/comments/" + commentCode), owner), 404);
perform(auth(delete("/api/comments/" + commentCode), other), 200);
assertThat(
perform(get("/api/community/projects/" + code + "/comments"), 200)
.path("data")
.path("total")
.asLong())
.isZero();
perform(auth(delete("/api/community/projects/" + code + "/like"), other), 200);
perform(auth(delete("/api/community/projects/" + code + "/like"), other), 200);
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM project_like", Long.class)).isZero();
perform(auth(delete("/api/workspace/projects/" + code + "/publication"), owner), 200);
perform(get("/api/community/projects/" + code), 404);
perform(auth(get("/api/workspace/projects/" + code + "/tree"), owner), 200);
}
@Test
void directoriesAndBinaryUploadAndDeletionAndPagination() throws Exception {
String owner = login("files@example.com");
String code = create(owner, "文件项目");
String sha = head(owner, code);
JsonNode changed =
perform(
body(
auth(
post(
"/api/workspace/projects/"
+ code
+ "/commits"),
owner),
Map.of(
"expectedCommitSha",
sha,
"message",
"创建目录和文件",
"changes",
List.of(
Map.of(
"action",
"CREATE_DIRECTORY",
"path",
"models"),
Map.of(
"action",
"CREATE_FILE",
"path",
"src/main.txt",
"content",
"hello")))),
200)
.path("data");
byte[] bytes = {0, 1, 2, 3};
MockMultipartFile upload =
new MockMultipartFile("files", "model.bin", "application/octet-stream", bytes);
JsonNode committed =
perform(
auth(
multipart(
"/api/workspace/projects/"
+ code
+ "/uploads/commit")
.file(upload)
.param(
"expectedCommitSha",
changed.path("commitSha").asText())
.param("message", "上传模型")
.param("directory", "models"),
owner),
200)
.path("data");
mvc.perform(
auth(
get("/api/workspace/projects/" + code + "/files")
.param("path", "models/model.bin")
.param("download", "true"),
owner))
.andExpect(status().isOk())
.andExpect(content().bytes(bytes));
JsonNode binary =
perform(
auth(
get("/api/workspace/projects/" + code + "/files")
.param("path", "models/model.bin"),
owner),
200)
.path("data");
assertThat(binary.path("editable").asBoolean()).isFalse();
assertThat(binary.path("encoding").asText()).isEqualTo("base64");
perform(
body(
auth(post("/api/workspace/projects/" + code + "/commits"), owner),
Map.of(
"expectedCommitSha",
committed.path("commitSha").asText(),
"message",
"删除文件",
"changes",
List.of(Map.of("action", "DELETE_FILE", "path", "src/main.txt")))),
200);
perform(
auth(
get("/api/workspace/projects/" + code + "/files")
.param("path", "src/main.txt"),
owner),
404);
assertThat(
perform(
auth(
get("/api/workspace/projects/" + code + "/commits")
.param("size", "2"),
owner),
200)
.path("data")
.path("items")
.size())
.isEqualTo(2);
perform(auth(get("/api/workspace/projects").param("size", "101"), owner), 400);
}
@Test
void staleAndConcurrentSubmissionsCannotOverwrite() throws Exception {
String owner = login("concurrent@example.com");
String code = create(owner, "并发项目");
String sha = head(owner, code);
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
Callable<Integer> submit =
() ->
mvc.perform(
body(
auth(
post(
"/api/workspace/projects/"
+ code
+ "/commits"),
owner),
Map.of(
"expectedCommitSha",
sha,
"message",
"并发提交",
"changes",
List.of(
Map.of(
"action",
"UPDATE_FILE",
"path",
"README.md",
"content",
"new")))))
.andReturn()
.getResponse()
.getStatus();
List<Future<Integer>> results = executor.invokeAll(List.of(submit, submit));
assertThat(List.of(results.get(0).get(), results.get(1).get()))
.containsExactlyInAnyOrder(200, 409);
} finally {
executor.shutdownNow();
}
perform(
body(
auth(put("/api/workspace/projects/" + code + "/publication"), owner),
Map.of("commitSha", sha)),
409);
}
@Test
void unsafePathsOversizedTextAndUnsupportedTypeAreRejected() throws Exception {
String owner = login("paths@example.com");
perform(
body(
auth(post("/api/workspace/projects"), owner),
Map.of("name", "x", "projectType", "UNKNOWN")),
400);
String code = create(owner, "路径项目");
String sha = head(owner, code);
for (String path : List.of("../secret", "/tmp/secret", ".git/config", "a/../b", "a\\b")) {
perform(
auth(
get("/api/workspace/projects/" + code + "/files").param("path", path),
owner),
400);
}
perform(
body(
auth(post("/api/workspace/projects/" + code + "/commits"), owner),
Map.of(
"expectedCommitSha",
sha,
"message",
"大文件",
"changes",
List.of(
Map.of(
"action",
"CREATE_FILE",
"path",
"large.txt",
"content",
"x".repeat(1048577))))),
413);
}
@Test
void unknownRemoteWritesAreNotRepeatedAndFailedCreatesRemainVisible() throws Exception {
String owner = login("failure@example.com");
gitea.failNextCreate = true;
JsonNode failure =
perform(
body(
auth(post("/api/workspace/projects"), owner),
Map.of("name", "失败项目", "projectType", "GENERAL")),
502);
String failed = failure.path("data").path("projectCode").asText();
assertThat(
perform(auth(get("/api/workspace/projects/" + failed), owner), 200)
.path("data")
.path("repoStatus")
.asText())
.isEqualTo("FAILED");
gitea.timeoutNextCreate = true;
JsonNode pending =
perform(
body(
auth(post("/api/workspace/projects"), owner),
Map.of("name", "待核对项目", "projectType", "GENERAL")),
504);
assertThat(
perform(
auth(
get(
"/api/workspace/projects/"
+ pending.path("data")
.path("projectCode")
.asText()),
owner),
200)
.path("data")
.path("repoStatus")
.asText())
.isEqualTo("CREATING");
String code = create(owner, "超时项目");
String sha = head(owner, code);
gitea.timeoutNextCommit = true;
Map<String, Object> request =
Map.of(
"expectedCommitSha",
sha,
"message",
"超时提交",
"changes",
List.of(
Map.of(
"action",
"UPDATE_FILE",
"path",
"README.md",
"content",
"实际成功")));
perform(
body(auth(post("/api/workspace/projects/" + code + "/commits"), owner), request),
504);
perform(
body(auth(post("/api/workspace/projects/" + code + "/commits"), owner), request),
409);
assertThat(
perform(
auth(
get("/api/workspace/projects/" + code + "/files")
.param("path", "README.md"),
owner),
200)
.path("data")
.path("content")
.asText())
.isEqualTo("实际成功");
perform(auth(delete("/api/workspace/projects/" + code + "/publication"), owner), 200);
perform(auth(delete("/api/workspace/projects/" + code), owner), 200);
}
}