后台管理adminapi模块
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.linkerbot</groupId>
|
||||
<artifactId>community</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>community-adminapi</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.linkerbot</groupId>
|
||||
<artifactId>community-security</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.linkerbot.community.adminapi;
|
||||
|
||||
import com.linkerbot.community.security.TokenService;
|
||||
|
||||
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;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@EnableScheduling
|
||||
@MapperScan("com.linkerbot.community.service.mapper")
|
||||
@Import(TokenService.class)
|
||||
@SpringBootApplication(
|
||||
scanBasePackages = {
|
||||
"com.linkerbot.community.adminapi",
|
||||
"com.linkerbot.community.service",
|
||||
"com.linkerbot.community.common"
|
||||
},
|
||||
exclude = UserDetailsServiceAutoConfiguration.class)
|
||||
public class AdminApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(AdminApplication.class, args);
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.linkerbot.community.adminapi.config;
|
||||
|
||||
import com.linkerbot.community.adminapi.security.AdminAuthService;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.boot.*;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.Console;
|
||||
import java.util.Arrays;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AdminBootstrap implements ApplicationRunner {
|
||||
private final AdminAuthService auth;
|
||||
private final ConfigurableApplicationContext context;
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments arguments) {
|
||||
if (!arguments.containsOption("bootstrap-admin-user-code")) return;
|
||||
Console console = System.console();
|
||||
if (console == null) throw new IllegalStateException("初始化管理员需要交互终端,请直接运行 jar");
|
||||
char[] password = console.readPassword("请输入管理员密码(至少12字符):");
|
||||
char[] confirmation = console.readPassword("请再次输入密码:");
|
||||
try {
|
||||
if (password == null || confirmation == null || !Arrays.equals(password, confirmation))
|
||||
throw new IllegalArgumentException("两次密码不一致");
|
||||
auth.bootstrap(
|
||||
arguments.getOptionValues("bootstrap-admin-user-code").getFirst(),
|
||||
new String(password));
|
||||
} finally {
|
||||
if (password != null) Arrays.fill(password, '\0');
|
||||
if (confirmation != null) Arrays.fill(confirmation, '\0');
|
||||
}
|
||||
SpringApplication.exit(context);
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.linkerbot.community.adminapi.config;
|
||||
|
||||
import io.swagger.v3.oas.models.Components;
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
import io.swagger.v3.oas.models.security.*;
|
||||
|
||||
import org.springframework.context.annotation.*;
|
||||
|
||||
@Configuration
|
||||
public class AdminOpenApiConfiguration {
|
||||
@Bean
|
||||
public OpenAPI adminOpenApi() {
|
||||
return new OpenAPI()
|
||||
.info(new Info().title("Community 管理端接口").version("v1"))
|
||||
.components(
|
||||
new Components()
|
||||
.addSecuritySchemes(
|
||||
"bearerAuth",
|
||||
new SecurityScheme()
|
||||
.type(SecurityScheme.Type.HTTP)
|
||||
.scheme("bearer")))
|
||||
.addSecurityItem(new SecurityRequirement().addList("bearerAuth"));
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package com.linkerbot.community.adminapi.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.community.adminapi.security.AdminTokenFilter;
|
||||
import com.linkerbot.community.common.*;
|
||||
import com.linkerbot.community.service.config.AdminProperties;
|
||||
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.*;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.web.cors.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
public class AdminSecurityConfiguration {
|
||||
@Bean
|
||||
public FilterRegistrationBean<AdminTokenFilter> disableAdminFilterRegistration(
|
||||
AdminTokenFilter filter) {
|
||||
FilterRegistrationBean<AdminTokenFilter> registration =
|
||||
new FilterRegistrationBean<>(filter);
|
||||
registration.setEnabled(false);
|
||||
return registration;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain adminSecurity(
|
||||
HttpSecurity http,
|
||||
AdminTokenFilter filter,
|
||||
ObjectMapper json,
|
||||
AdminProperties properties)
|
||||
throws Exception {
|
||||
CorsConfiguration cors = new CorsConfiguration();
|
||||
cors.setAllowedOrigins(properties.getAllowedOrigins());
|
||||
cors.setAllowedMethods(List.of("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
|
||||
cors.setAllowedHeaders(List.of("Authorization", "Content-Type", "Accept"));
|
||||
cors.setExposedHeaders(List.of("X-Request-Id", "Content-Disposition"));
|
||||
cors.setAllowCredentials(false);
|
||||
cors.setMaxAge(3600L);
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/admin-api/**", cors);
|
||||
http.cors(config -> config.configurationSource(source))
|
||||
.csrf(config -> config.disable())
|
||||
.sessionManagement(
|
||||
config -> config.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.formLogin(config -> config.disable())
|
||||
.httpBasic(config -> config.disable())
|
||||
.logout(config -> config.disable())
|
||||
.authorizeHttpRequests(
|
||||
config ->
|
||||
config.requestMatchers(HttpMethod.OPTIONS, "/**")
|
||||
.permitAll()
|
||||
.requestMatchers(
|
||||
"/admin-api/auth/login",
|
||||
"/error",
|
||||
"/v3/api-docs/**",
|
||||
"/swagger-ui/**",
|
||||
"/swagger-ui.html")
|
||||
.permitAll()
|
||||
.requestMatchers("/admin-api/**")
|
||||
.hasRole("ADMIN")
|
||||
.anyRequest()
|
||||
.denyAll())
|
||||
.exceptionHandling(
|
||||
config ->
|
||||
config.authenticationEntryPoint(
|
||||
(request, response, error) -> {
|
||||
response.setStatus(401);
|
||||
response.setContentType(
|
||||
"application/json;charset=UTF-8");
|
||||
json.writeValue(
|
||||
response.getOutputStream(),
|
||||
ApiResponse.failure(
|
||||
new BusinessException(
|
||||
401,
|
||||
"UNAUTHORIZED",
|
||||
"请登录后台")));
|
||||
})
|
||||
.accessDeniedHandler(
|
||||
(request, response, error) -> {
|
||||
response.setStatus(403);
|
||||
response.setContentType(
|
||||
"application/json;charset=UTF-8");
|
||||
json.writeValue(
|
||||
response.getOutputStream(),
|
||||
ApiResponse.failure(
|
||||
new BusinessException(
|
||||
403,
|
||||
"FORBIDDEN",
|
||||
"无后台访问权限")));
|
||||
}))
|
||||
.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package com.linkerbot.community.adminapi.config;
|
||||
|
||||
import com.linkerbot.community.service.admin.AdminImportService;
|
||||
import com.linkerbot.community.service.config.AdminProperties;
|
||||
|
||||
import jakarta.annotation.PreDestroy;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.concurrent.*;
|
||||
|
||||
@Component
|
||||
public class ImportWorker {
|
||||
private static final Logger log = LoggerFactory.getLogger(ImportWorker.class);
|
||||
private final AdminImportService imports;
|
||||
private final boolean enabled;
|
||||
private final ExecutorService pool;
|
||||
private final Semaphore permits;
|
||||
private boolean recovered;
|
||||
|
||||
public ImportWorker(
|
||||
AdminImportService imports,
|
||||
AdminProperties properties,
|
||||
ApplicationArguments arguments) {
|
||||
this.imports = imports;
|
||||
this.enabled =
|
||||
properties.isWorkerEnabled()
|
||||
&& !arguments.containsOption("bootstrap-admin-user-code");
|
||||
this.permits = new Semaphore(properties.getImportConcurrency());
|
||||
this.pool =
|
||||
new ThreadPoolExecutor(
|
||||
properties.getImportConcurrency(),
|
||||
properties.getImportConcurrency(),
|
||||
0,
|
||||
TimeUnit.MILLISECONDS,
|
||||
new ArrayBlockingQueue<>(properties.getImportConcurrency()),
|
||||
Thread.ofPlatform().name("admin-import-", 0).factory());
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 1000, initialDelay = 1000)
|
||||
public void dispatch() {
|
||||
if (!enabled || pool.isShutdown()) return;
|
||||
try {
|
||||
if (!recovered) {
|
||||
imports.recover();
|
||||
recovered = true;
|
||||
}
|
||||
if (permits.availablePermits() == 0) return;
|
||||
for (String code : imports.queued()) {
|
||||
if (!permits.tryAcquire()) break;
|
||||
try {
|
||||
pool.execute(
|
||||
() -> {
|
||||
try {
|
||||
imports.run(code);
|
||||
} catch (RuntimeException error) {
|
||||
log.error(
|
||||
"迁移工作线程异常 taskCode={} errorType={}",
|
||||
code,
|
||||
error.getClass().getSimpleName());
|
||||
} finally {
|
||||
permits.release();
|
||||
}
|
||||
});
|
||||
} catch (RejectedExecutionException error) {
|
||||
permits.release();
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException error) {
|
||||
log.error("迁移任务调度失败 errorType={}", error.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void close() throws InterruptedException {
|
||||
pool.shutdown();
|
||||
if (!pool.awaitTermination(5, TimeUnit.SECONDS)) pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.linkerbot.community.adminapi.config;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.linkerbot.community.adminapi.controller;
|
||||
|
||||
import com.linkerbot.community.adminapi.security.*;
|
||||
import com.linkerbot.community.bean.AdminContracts.*;
|
||||
import com.linkerbot.community.common.ApiResponse;
|
||||
|
||||
import io.swagger.v3.oas.annotations.security.SecurityRequirements;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/admin-api/auth")
|
||||
public class AdminAuthController {
|
||||
private final AdminAuthService auth;
|
||||
|
||||
@PostMapping("/login")
|
||||
@SecurityRequirements
|
||||
public ResponseEntity<ApiResponse<LoginView>> login(
|
||||
@Valid @RequestBody LoginInput input, HttpServletRequest request) {
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.noStore())
|
||||
.body(ApiResponse.success(auth.login(input, request.getRemoteAddr())));
|
||||
}
|
||||
|
||||
@GetMapping("/me")
|
||||
public ApiResponse<AdminView> me() {
|
||||
return ApiResponse.success(auth.view(CurrentAdmin.required()));
|
||||
}
|
||||
|
||||
@PostMapping("/logout")
|
||||
public ApiResponse<Void> logout(@RequestHeader("Authorization") String header) {
|
||||
auth.logout(header.substring(7));
|
||||
return ApiResponse.success(null);
|
||||
}
|
||||
|
||||
@PutMapping("/password")
|
||||
public ApiResponse<Void> password(@Valid @RequestBody PasswordInput input) {
|
||||
auth.password(CurrentAdmin.required(), input);
|
||||
return ApiResponse.success(null);
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.linkerbot.community.adminapi.controller;
|
||||
|
||||
import com.linkerbot.community.bean.AdminContracts.*;
|
||||
import com.linkerbot.community.common.*;
|
||||
import com.linkerbot.community.service.admin.AdminImportService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/admin-api/project-imports")
|
||||
public class AdminImportController {
|
||||
private final AdminImportService service;
|
||||
|
||||
@PostMapping("/preview")
|
||||
public ApiResponse<ImportPreview> preview(@Valid @RequestBody PreviewInput input) {
|
||||
return ApiResponse.success(service.preview(input.repositoryUrl()));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<ApiResponse<TaskView>> create(@Valid @RequestBody ImportInput input) {
|
||||
return ResponseEntity.accepted().body(ApiResponse.success(service.create(input)));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<PageResponse<TaskView>> list(
|
||||
@RequestParam(defaultValue = "1") long page,
|
||||
@RequestParam(defaultValue = "20") long size,
|
||||
@RequestParam(required = false) String status,
|
||||
@RequestParam(required = false) String projectCode) {
|
||||
return ApiResponse.success(service.list(page, size, status, projectCode));
|
||||
}
|
||||
|
||||
@GetMapping("/{taskCode}")
|
||||
public ApiResponse<TaskView> detail(@PathVariable String taskCode) {
|
||||
return ApiResponse.success(service.view(service.task(taskCode)));
|
||||
}
|
||||
|
||||
@PostMapping("/{taskCode}/retry")
|
||||
public ResponseEntity<ApiResponse<TaskView>> retry(@PathVariable String taskCode) {
|
||||
return ResponseEntity.accepted().body(ApiResponse.success(service.retry(taskCode)));
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
package com.linkerbot.community.adminapi.controller;
|
||||
|
||||
import com.linkerbot.community.bean.AdminContracts.*;
|
||||
import com.linkerbot.community.bean.Contracts.*;
|
||||
import com.linkerbot.community.common.*;
|
||||
import com.linkerbot.community.service.*;
|
||||
import com.linkerbot.community.service.admin.AdminManagementService;
|
||||
import com.linkerbot.community.service.gitea.GiteaClient;
|
||||
|
||||
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("/admin-api/projects")
|
||||
public class AdminProjectController {
|
||||
private final AdminManagementService management;
|
||||
private final ProjectService projects;
|
||||
private final FileService files;
|
||||
private final UrdfService urdf;
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<PageResponse<ManagedProjectView>> list(
|
||||
@RequestParam(defaultValue = "1") long page,
|
||||
@RequestParam(defaultValue = "20") long size,
|
||||
@RequestParam(required = false) String ownerUserCode,
|
||||
@RequestParam(required = false) String type,
|
||||
@RequestParam(required = false) String keyword,
|
||||
@RequestParam(required = false) String publishStatus,
|
||||
@RequestParam(required = false) String repoStatus,
|
||||
@RequestParam(required = false) String moderationStatus) {
|
||||
return ApiResponse.success(
|
||||
management.projects(
|
||||
page,
|
||||
size,
|
||||
ownerUserCode,
|
||||
type,
|
||||
keyword,
|
||||
publishStatus,
|
||||
repoStatus,
|
||||
moderationStatus));
|
||||
}
|
||||
|
||||
@GetMapping("/types")
|
||||
public ApiResponse<List<TypeView>> types() {
|
||||
return ApiResponse.success(projects.types());
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ApiResponse<ProjectView> create(@Valid @RequestBody CreateProjectInput input) {
|
||||
return ApiResponse.success(management.create(input));
|
||||
}
|
||||
|
||||
@GetMapping("/{projectCode}")
|
||||
public ApiResponse<ManagedProjectView> detail(@PathVariable String projectCode) {
|
||||
return ApiResponse.success(management.detail(projectCode));
|
||||
}
|
||||
|
||||
@PatchMapping("/{projectCode}")
|
||||
public ApiResponse<ProjectView> update(
|
||||
@PathVariable String projectCode, @Valid @RequestBody ProjectInput input) {
|
||||
return ApiResponse.success(projects.update(0, projectCode, input));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{projectCode}")
|
||||
public ApiResponse<Void> delete(@PathVariable String projectCode) {
|
||||
projects.delete(0, projectCode);
|
||||
return ApiResponse.success(null);
|
||||
}
|
||||
|
||||
@GetMapping("/{projectCode}/tree")
|
||||
public ApiResponse<TreeView> tree(
|
||||
@PathVariable String projectCode,
|
||||
@RequestParam(defaultValue = "") String path,
|
||||
@RequestParam(required = false) String commitSha) {
|
||||
return ApiResponse.success(files.ownerTree(0, projectCode, path, commitSha));
|
||||
}
|
||||
|
||||
@GetMapping("/{projectCode}/files")
|
||||
public ResponseEntity<?> file(
|
||||
@PathVariable String projectCode,
|
||||
@RequestParam String path,
|
||||
@RequestParam(required = false) String commitSha,
|
||||
@RequestParam(defaultValue = "false") boolean download) {
|
||||
if (!download)
|
||||
return ResponseEntity.ok(
|
||||
ApiResponse.success(files.ownerFileView(0, projectCode, path, commitSha)));
|
||||
GiteaClient.StoredFile file = files.ownerFile(0, projectCode, path, commitSha);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||
.header(
|
||||
HttpHeaders.CONTENT_DISPOSITION,
|
||||
ContentDisposition.attachment()
|
||||
.filename(
|
||||
file.path().substring(file.path().lastIndexOf('/') + 1),
|
||||
StandardCharsets.UTF_8)
|
||||
.build()
|
||||
.toString())
|
||||
.body(file.bytes());
|
||||
}
|
||||
|
||||
@GetMapping("/{projectCode}/commits")
|
||||
public ApiResponse<PageResponse<HistoryEntry>> history(
|
||||
@PathVariable String projectCode,
|
||||
@RequestParam(defaultValue = "1") long page,
|
||||
@RequestParam(defaultValue = "20") long size) {
|
||||
return ApiResponse.success(files.history(0, projectCode, page, size));
|
||||
}
|
||||
|
||||
@PostMapping("/{projectCode}/commits")
|
||||
public ApiResponse<CommitView> commit(
|
||||
@PathVariable String projectCode, @Valid @RequestBody CommitInput input) {
|
||||
return ApiResponse.success(files.commit(0, projectCode, input));
|
||||
}
|
||||
|
||||
@PostMapping(
|
||||
value = "/{projectCode}/uploads/commit",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
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(
|
||||
0, projectCode, expectedCommitSha, message, directory, uploaded, paths));
|
||||
}
|
||||
|
||||
@PutMapping("/{projectCode}/publication")
|
||||
public ApiResponse<ProjectView> publish(
|
||||
@PathVariable String projectCode, @Valid @RequestBody PublicationInput input) {
|
||||
return ApiResponse.success(projects.publish(0, projectCode, input.commitSha()));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{projectCode}/publication")
|
||||
public ApiResponse<Void> withdraw(@PathVariable String projectCode) {
|
||||
projects.withdraw(0, projectCode);
|
||||
return ApiResponse.success(null);
|
||||
}
|
||||
|
||||
@PutMapping("/{projectCode}/moderation")
|
||||
public ApiResponse<Void> block(
|
||||
@PathVariable String projectCode, @Valid @RequestBody ReasonInput input) {
|
||||
management.moderate(projectCode, true, input.reason());
|
||||
return ApiResponse.success(null);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{projectCode}/moderation")
|
||||
public ApiResponse<Void> unblock(@PathVariable String projectCode) {
|
||||
management.moderate(projectCode, false, null);
|
||||
return ApiResponse.success(null);
|
||||
}
|
||||
|
||||
@PostMapping("/{projectCode}/urdf/signature")
|
||||
public ApiResponse<UrdfUploadSignature> urdfSignature(
|
||||
@PathVariable String projectCode, @Valid @RequestBody UrdfUploadInput input) {
|
||||
return ApiResponse.success(urdf.signature(0, projectCode, input));
|
||||
}
|
||||
|
||||
@PutMapping("/{projectCode}/urdf")
|
||||
public ApiResponse<ProjectView> urdfConfirm(
|
||||
@PathVariable String projectCode, @Valid @RequestBody UrdfConfirmInput input) {
|
||||
return ApiResponse.success(urdf.confirm(0, projectCode, input));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{projectCode}/urdf")
|
||||
public ApiResponse<Void> urdfClear(@PathVariable String projectCode) {
|
||||
urdf.clear(0, projectCode);
|
||||
return ApiResponse.success(null);
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.linkerbot.community.adminapi.controller;
|
||||
|
||||
import com.linkerbot.community.bean.Contracts.*;
|
||||
import com.linkerbot.community.common.ApiResponse;
|
||||
import com.linkerbot.community.service.CoverUploadService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/admin-api/uploads")
|
||||
public class AdminUploadController {
|
||||
private final CoverUploadService covers;
|
||||
|
||||
@PostMapping("/project-covers/signature")
|
||||
public ResponseEntity<ApiResponse<CoverUploadSignature>> signature(
|
||||
@Valid @RequestBody CoverUploadInput input) {
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.noStore())
|
||||
.body(ApiResponse.success(covers.signature(0, input)));
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.linkerbot.community.adminapi.controller;
|
||||
|
||||
import com.linkerbot.community.bean.AdminContracts.*;
|
||||
import com.linkerbot.community.common.*;
|
||||
import com.linkerbot.community.service.admin.AdminManagementService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/admin-api/users")
|
||||
public class AdminUserController {
|
||||
private final AdminManagementService service;
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<PageResponse<UserView>> list(
|
||||
@RequestParam(defaultValue = "1") long page,
|
||||
@RequestParam(defaultValue = "20") long size,
|
||||
@RequestParam(required = false) String userCode,
|
||||
@RequestParam(required = false) String nickname,
|
||||
@RequestParam(required = false) String email,
|
||||
@RequestParam(required = false) String role,
|
||||
@RequestParam(required = false) String status) {
|
||||
return ApiResponse.success(
|
||||
service.users(page, size, userCode, nickname, email, role, status));
|
||||
}
|
||||
|
||||
@GetMapping("/{userCode}")
|
||||
public ApiResponse<UserView> detail(@PathVariable String userCode) {
|
||||
return ApiResponse.success(service.userView(service.user(userCode)));
|
||||
}
|
||||
|
||||
@PatchMapping("/{userCode}")
|
||||
public ApiResponse<UserView> nickname(
|
||||
@PathVariable String userCode, @Valid @RequestBody NicknameInput input) {
|
||||
return ApiResponse.success(service.nickname(userCode, input.nickname()));
|
||||
}
|
||||
|
||||
@PutMapping("/{userCode}/status")
|
||||
public ApiResponse<Void> status(
|
||||
@PathVariable String userCode, @Valid @RequestBody StatusInput input) {
|
||||
service.status(userCode, input.status());
|
||||
return ApiResponse.success(null);
|
||||
}
|
||||
|
||||
@GetMapping("/{userCode}/projects")
|
||||
public ApiResponse<PageResponse<ManagedProjectView>> projects(
|
||||
@PathVariable String userCode,
|
||||
@RequestParam(defaultValue = "1") long page,
|
||||
@RequestParam(defaultValue = "20") long size) {
|
||||
return ApiResponse.success(
|
||||
service.projects(page, size, userCode, null, null, null, null, null));
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
package com.linkerbot.community.adminapi.security;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import com.linkerbot.community.bean.AdminContracts.*;
|
||||
import com.linkerbot.community.bean.entity.User;
|
||||
import com.linkerbot.community.common.BusinessException;
|
||||
import com.linkerbot.community.security.TokenService;
|
||||
import com.linkerbot.community.service.config.CommunityProperties;
|
||||
import com.linkerbot.community.service.mapper.UserMapper;
|
||||
import com.linkerbot.community.service.support.ProjectSupport;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Locale;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AdminAuthService {
|
||||
private static final Logger log = LoggerFactory.getLogger(AdminAuthService.class);
|
||||
private final UserMapper users;
|
||||
private final TokenService tokens;
|
||||
private final CommunityProperties properties;
|
||||
private final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(12);
|
||||
private final String dummyHash = encoder.encode("invalid-admin-password");
|
||||
private final Cache<String, Integer> failures =
|
||||
Caffeine.newBuilder()
|
||||
.maximumSize(10000)
|
||||
.expireAfterWrite(Duration.ofMinutes(15))
|
||||
.build();
|
||||
|
||||
public LoginView login(LoginInput input, String remoteAddress) {
|
||||
String email = input.email().trim().toLowerCase(Locale.ROOT);
|
||||
checkLimit("ip:" + remoteAddress, 30);
|
||||
checkLimit("account:" + email, 5);
|
||||
User user = users.selectOne(new LambdaQueryWrapper<User>().eq(User::getEmail, email));
|
||||
String hash =
|
||||
user == null || user.getPasswordHash() == null ? dummyHash : user.getPasswordHash();
|
||||
boolean matches =
|
||||
input.password().getBytes(StandardCharsets.UTF_8).length <= 72
|
||||
&& encoder.matches(input.password(), hash);
|
||||
if (!matches
|
||||
|| user == null
|
||||
|| !"ACTIVE".equals(user.getStatus())
|
||||
|| !"ADMIN".equals(user.getRole())) {
|
||||
failure("ip:" + remoteAddress);
|
||||
failure("account:" + email);
|
||||
log.warn("后台登录失败 code=ADMIN_LOGIN_FAILED");
|
||||
throw new BusinessException(401, "ADMIN_LOGIN_FAILED", "账号或密码错误");
|
||||
}
|
||||
failures.invalidate("account:" + email);
|
||||
log.info("后台登录 userCode={}", user.getUserCode());
|
||||
return new LoginView(
|
||||
tokens.issue(user.getId(), user.getSessionVersion()),
|
||||
"Bearer",
|
||||
properties.getTokenTtl().toSeconds(),
|
||||
view(user));
|
||||
}
|
||||
|
||||
private void checkLimit(String key, int limit) {
|
||||
Integer count = failures.getIfPresent(key);
|
||||
if (count != null && count >= limit)
|
||||
throw new BusinessException(429, "ADMIN_LOGIN_LIMITED", "尝试次数过多,请15分钟后重试");
|
||||
}
|
||||
|
||||
private void failure(String key) {
|
||||
failures.asMap().compute(key, (ignored, count) -> count == null ? 1 : count + 1);
|
||||
}
|
||||
|
||||
public User authenticate(String token) {
|
||||
TokenService.Session session = tokens.session(token);
|
||||
if (session == null) throw new BusinessException(401, "UNAUTHORIZED", "请登录后台");
|
||||
User user = users.selectById(session.userId());
|
||||
if (user == null
|
||||
|| !"ACTIVE".equals(user.getStatus())
|
||||
|| user.getSessionVersion() != session.version())
|
||||
throw new BusinessException(401, "UNAUTHORIZED", "登录已失效");
|
||||
if (!"ADMIN".equals(user.getRole()))
|
||||
throw new BusinessException(403, "FORBIDDEN", "无后台访问权限");
|
||||
return user;
|
||||
}
|
||||
|
||||
public AdminView view(User user) {
|
||||
return new AdminView(
|
||||
user.getUserCode(), user.getEmail(), user.getNickname(), user.getRole());
|
||||
}
|
||||
|
||||
public void logout(String token) {
|
||||
tokens.revoke(token);
|
||||
}
|
||||
|
||||
public void password(User user, PasswordInput input) {
|
||||
validatePassword(input.newPassword());
|
||||
if (input.oldPassword().getBytes(StandardCharsets.UTF_8).length > 72
|
||||
|| !encoder.matches(input.oldPassword(), user.getPasswordHash()))
|
||||
throw new BusinessException(400, "PASSWORD_INVALID", "原密码不正确");
|
||||
int updated =
|
||||
users.update(
|
||||
null,
|
||||
new LambdaUpdateWrapper<User>()
|
||||
.eq(User::getId, user.getId())
|
||||
.eq(User::getSessionVersion, user.getSessionVersion())
|
||||
.eq(User::getRole, "ADMIN")
|
||||
.eq(User::getStatus, "ACTIVE")
|
||||
.set(User::getPasswordHash, encoder.encode(input.newPassword()))
|
||||
.setSql("session_version = session_version + 1")
|
||||
.set(User::getUpdatedAt, ProjectSupport.now()));
|
||||
if (updated != 1) throw BusinessException.conflict("账号状态已变化,请重新登录");
|
||||
log.info("后台修改密码 userCode={}", user.getUserCode());
|
||||
}
|
||||
|
||||
public void bootstrap(String userCode, String password) {
|
||||
validatePassword(password);
|
||||
int updated =
|
||||
users.update(
|
||||
null,
|
||||
new LambdaUpdateWrapper<User>()
|
||||
.eq(User::getUserCode, userCode)
|
||||
.eq(User::getRole, "USER")
|
||||
.eq(User::getStatus, "ACTIVE")
|
||||
.set(User::getRole, "ADMIN")
|
||||
.set(User::getPasswordHash, encoder.encode(password))
|
||||
.setSql("session_version = session_version + 1")
|
||||
.set(User::getUpdatedAt, ProjectSupport.now()));
|
||||
if (updated != 1) throw BusinessException.conflict("只能从已有正常普通用户初始化管理员");
|
||||
log.info("初始化管理员 userCode={}", userCode);
|
||||
}
|
||||
|
||||
private void validatePassword(String password) {
|
||||
if (password.length() < 12 || password.getBytes(StandardCharsets.UTF_8).length > 72)
|
||||
throw BusinessException.badRequest("密码至少12字符,UTF-8编码最多72字节");
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package com.linkerbot.community.adminapi.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.community.bean.entity.User;
|
||||
import com.linkerbot.community.common.*;
|
||||
import com.linkerbot.community.service.support.ProjectActors;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.*;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AdminTokenFilter extends OncePerRequestFilter {
|
||||
private static final Logger log = LoggerFactory.getLogger(AdminTokenFilter.class);
|
||||
private final AdminAuthService auth;
|
||||
private final ObjectMapper json;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
String header = request.getHeader("Authorization");
|
||||
if (header == null || !header.startsWith("Bearer ")) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
User user;
|
||||
try {
|
||||
user = auth.authenticate(header.substring(7));
|
||||
} catch (BusinessException error) {
|
||||
response.setStatus(error.status());
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
json.writeValue(response.getOutputStream(), ApiResponse.failure(error));
|
||||
return;
|
||||
}
|
||||
SecurityContextHolder.getContext()
|
||||
.setAuthentication(
|
||||
new UsernamePasswordAuthenticationToken(
|
||||
user, null, List.of(new SimpleGrantedAuthority("ROLE_ADMIN"))));
|
||||
long started = System.nanoTime();
|
||||
try (ProjectActors.Scope scope =
|
||||
ProjectActors.enter(
|
||||
new ProjectActors.AdminActor(user.getUserCode(), user.getNickname()))) {
|
||||
chain.doFilter(request, response);
|
||||
} finally {
|
||||
if (!List.of("GET", "HEAD", "OPTIONS").contains(request.getMethod())) {
|
||||
String targetCode = user.getUserCode();
|
||||
for (String segment : request.getRequestURI().split("/"))
|
||||
if (segment.matches("[a-z0-9]{12,32}")) targetCode = segment;
|
||||
Object pattern =
|
||||
request.getAttribute(
|
||||
org.springframework.web.servlet.HandlerMapping
|
||||
.BEST_MATCHING_PATTERN_ATTRIBUTE);
|
||||
String resource = pattern instanceof String route ? route : "unknown";
|
||||
log.info(
|
||||
"后台操作 userCode={} targetCode={} action={}:{} result={} code=HTTP_{}"
|
||||
+ " durationMs={}",
|
||||
user.getUserCode(),
|
||||
targetCode,
|
||||
request.getMethod(),
|
||||
resource,
|
||||
response.getStatus() < 400 ? "SUCCESS" : "FAILED",
|
||||
response.getStatus(),
|
||||
(System.nanoTime() - started) / 1_000_000);
|
||||
}
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.linkerbot.community.adminapi.security;
|
||||
|
||||
import com.linkerbot.community.bean.entity.User;
|
||||
import com.linkerbot.community.common.BusinessException;
|
||||
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
public final class CurrentAdmin {
|
||||
private CurrentAdmin() {}
|
||||
|
||||
public static User required() {
|
||||
org.springframework.security.core.Authentication authentication =
|
||||
SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication == null || !(authentication.getPrincipal() instanceof User user))
|
||||
throw new BusinessException(401, "UNAUTHORIZED", "请登录后台");
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: ${DB_URL}
|
||||
username: ${DB_USERNAME}
|
||||
password: ${DB_PASSWORD}
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
hikari:
|
||||
pool-name: CommunityAdminHikariCP
|
||||
minimum-idle: 1
|
||||
maximum-pool-size: 20
|
||||
connection-timeout: 5000
|
||||
|
||||
community:
|
||||
cors:
|
||||
allowed-origins:
|
||||
- https://vibemake.robotquan.com
|
||||
oss:
|
||||
root-directory: vibemake
|
||||
gitea:
|
||||
base-url: ${GITEA_BASE_URL}
|
||||
owner: ${GITEA_ORGANIZATION:vibemake}
|
||||
token: ${GITEA_TOKEN}
|
||||
|
||||
logging:
|
||||
level:
|
||||
com.linkerbot.community: INFO
|
||||
@@ -0,0 +1,26 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: ${DB_URL:jdbc:mysql://localhost:3306/community?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai}
|
||||
username: ${DB_USERNAME:root}
|
||||
password: ${DB_PASSWORD:}
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
hikari:
|
||||
pool-name: CommunityAdminHikariCP
|
||||
minimum-idle: 1
|
||||
maximum-pool-size: 10
|
||||
connection-timeout: 5000
|
||||
|
||||
community:
|
||||
cors:
|
||||
allowed-origins:
|
||||
- https://dev-vibemake.robotquan.com
|
||||
oss:
|
||||
root-directory: vibemake_dev
|
||||
gitea:
|
||||
base-url: ${GITEA_BASE_URL:http://localhost:3000}
|
||||
owner: ${GITEA_ORGANIZATION:community}
|
||||
token: ${GITEA_TOKEN:}
|
||||
|
||||
logging:
|
||||
level:
|
||||
com.linkerbot.community: DEBUG
|
||||
@@ -0,0 +1,83 @@
|
||||
server:
|
||||
port: ${ADMIN_SERVER_PORT:8994}
|
||||
spring:
|
||||
application:
|
||||
name: community-adminapi
|
||||
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:
|
||||
admin:
|
||||
allowed-origins: ${ADMIN_ALLOWED_ORIGINS:}
|
||||
github-token: ${GITHUB_TOKEN:}
|
||||
worker-enabled: ${ADMIN_IMPORT_WORKER_ENABLED:true}
|
||||
migration-timeout: ${ADMIN_MIGRATION_TIMEOUT:30m}
|
||||
import-concurrency: ${ADMIN_IMPORT_CONCURRENCY:2}
|
||||
oss:
|
||||
enabled: ${OSS_ENABLED:true}
|
||||
region: ${OSS_REGION:cn-beijing}
|
||||
bucket: ${OSS_BUCKET:linkerbot}
|
||||
access-key-id: ${OSS_ACCESS_KEY_ID:}
|
||||
access-key-secret: ${OSS_ACCESS_KEY_SECRET:}
|
||||
public-base-url: ${OSS_PUBLIC_BASE_URL:https://linkerbot.oss-cn-beijing.aliyuncs.com}
|
||||
legacy-public-base-urls: ${OSS_LEGACY_PUBLIC_BASE_URLS:}
|
||||
urdf:
|
||||
max-file-bytes: ${URDF_MAX_FILE_BYTES:52428800}
|
||||
max-total-bytes: ${URDF_MAX_TOTAL_BYTES:209715200}
|
||||
max-files: ${URDF_MAX_FILES:500}
|
||||
ai:
|
||||
enabled: false
|
||||
api-key: ${ARK_API_KEY:}
|
||||
model: ${ARK_MODEL:doubao-seed-2-1-lite-260915}
|
||||
endpoint: ${ARK_ENDPOINT:https://ark.cn-beijing.volces.com/api/v3/responses}
|
||||
request-timeout: ${AI_REQUEST_TIMEOUT:30s}
|
||||
search-timeout: ${AI_SEARCH_TIMEOUT:65s}
|
||||
heartbeat-interval: 10s
|
||||
max-concurrent: ${AI_MAX_CONCURRENT:4}
|
||||
requests-per-minute: ${AI_REQUESTS_PER_MINUTE:10}
|
||||
types:
|
||||
GENERAL: 通用
|
||||
HUMANOID: 人形
|
||||
QUADRUPED: 四足
|
||||
WHEELED: 轮式
|
||||
ROBOTIC_ARM: 机械臂
|
||||
captcha-ttl: 2m
|
||||
token-ttl: 8h
|
||||
max-text-bytes: 1048576
|
||||
max-file-bytes: 10485760
|
||||
max-request-bytes: 52428800
|
||||
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
|
||||
logging:
|
||||
file:
|
||||
path: ${LOG_PATH:logs}
|
||||
level:
|
||||
root: INFO
|
||||
# 测试环境开启项目 DEBUG 时,仍不输出 SQL 参数或完整请求内容。
|
||||
com.linkerbot.community.service.mapper: INFO
|
||||
org.springframework.web: INFO
|
||||
|
||||
# 管理端有独立的跨域配置,不复用社区前端来源。
|
||||
+589
@@ -0,0 +1,589 @@
|
||||
package com.linkerbot.community.adminapi;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.linkerbot.community.adminapi.security.AdminAuthService;
|
||||
import com.linkerbot.community.bean.entity.*;
|
||||
import com.linkerbot.community.common.BusinessException;
|
||||
import com.linkerbot.community.security.TokenService;
|
||||
import com.linkerbot.community.service.*;
|
||||
import com.linkerbot.community.service.admin.AdminImportService;
|
||||
import com.linkerbot.community.service.mapper.*;
|
||||
import com.linkerbot.community.service.migration.GitHubSourceChecks;
|
||||
import com.linkerbot.community.service.support.*;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.*;
|
||||
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.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.regex.*;
|
||||
|
||||
@SpringBootTest(
|
||||
properties = {
|
||||
"spring.datasource.url=jdbc:h2:mem:admin;MODE=MySQL;DB_CLOSE_DELAY=-1",
|
||||
"spring.datasource.username=sa",
|
||||
"spring.datasource.password=",
|
||||
"spring.datasource.driver-class-name=org.h2.Driver",
|
||||
"community.admin.worker-enabled=false",
|
||||
"community.oss.enabled=false",
|
||||
"logging.level.root=WARN"
|
||||
})
|
||||
@ActiveProfiles("test")
|
||||
@AutoConfigureMockMvc(print = MockMvcPrint.NONE)
|
||||
@Import(AdminWorkflowTest.Fakes.class)
|
||||
class AdminWorkflowTest {
|
||||
private static final java.util.concurrent.atomic.AtomicLong SOURCES =
|
||||
new java.util.concurrent.atomic.AtomicLong(12345);
|
||||
|
||||
@TestConfiguration
|
||||
static class Fakes {
|
||||
@Bean
|
||||
@Primary
|
||||
FakeGiteaClient fakeGitea() {
|
||||
return new FakeGiteaClient();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
GitHubSourceChecks fakeSources() {
|
||||
return new GitHubSourceChecks("") {
|
||||
@Override
|
||||
public Repository repository(String url) {
|
||||
return new Repository(
|
||||
SOURCES.get(),
|
||||
"https://github.com/example/robot",
|
||||
"master",
|
||||
"robot",
|
||||
"robot project",
|
||||
"MIT");
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@Autowired MockMvc mvc;
|
||||
@Autowired JdbcTemplate jdbc;
|
||||
@Autowired UserMapper users;
|
||||
@Autowired ProjectMapper projects;
|
||||
@Autowired ProjectImportTaskMapper tasks;
|
||||
@Autowired AdminAuthService auth;
|
||||
@Autowired AdminImportService imports;
|
||||
@Autowired TokenService tokens;
|
||||
@Autowired ObjectMapper json;
|
||||
@Autowired FakeGiteaClient gitea;
|
||||
@Autowired ProjectService projectService;
|
||||
@Autowired UserService userService;
|
||||
@Autowired ProjectLocks locks;
|
||||
private User admin;
|
||||
private User ordinary;
|
||||
private String token;
|
||||
private static final String PASSWORD = "test-only-password-123";
|
||||
|
||||
@BeforeEach
|
||||
void setup() throws Exception {
|
||||
jdbc.execute("DROP ALL OBJECTS");
|
||||
for (String name : List.of("database.md", "admin-database.md")) {
|
||||
Matcher matcher =
|
||||
Pattern.compile("CREATE TABLE [\\s\\S]*?;")
|
||||
.matcher(Files.readString(Path.of("../docs/" + name)));
|
||||
while (matcher.find())
|
||||
jdbc.execute(
|
||||
matcher.group()
|
||||
.replace(
|
||||
"JSON NOT NULL DEFAULT (JSON_ARRAY())",
|
||||
"CLOB NOT NULL DEFAULT '[]'")
|
||||
.replace(" CHARACTER SET utf8mb4 COLLATE utf8mb4_bin", "")
|
||||
.replaceAll(" COMMENT '[^']*'", "")
|
||||
.replaceAll("\\) ENGINE=InnoDB[^;]*;", ");"));
|
||||
}
|
||||
SOURCES.incrementAndGet();
|
||||
gitea.reset();
|
||||
admin = userService.login(UUID.randomUUID() + "@example.invalid");
|
||||
ordinary = userService.login(UUID.randomUUID() + "@example.invalid");
|
||||
auth.bootstrap(admin.getUserCode(), PASSWORD);
|
||||
admin = users.selectById(admin.getId());
|
||||
token = login(admin.getEmail(), PASSWORD, 200).path("data").path("token").asText();
|
||||
}
|
||||
|
||||
private JsonNode request(MockHttpServletRequestBuilder request, int status) throws Exception {
|
||||
MvcResult result = mvc.perform(request).andReturn();
|
||||
assertThat(result.getResponse().getStatus())
|
||||
.as(result.getResponse().getContentAsString())
|
||||
.isEqualTo(status);
|
||||
return json.readTree(result.getResponse().getContentAsString());
|
||||
}
|
||||
|
||||
private MockHttpServletRequestBuilder body(MockHttpServletRequestBuilder request, Object value)
|
||||
throws Exception {
|
||||
return request.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json.writeValueAsBytes(value));
|
||||
}
|
||||
|
||||
private MockHttpServletRequestBuilder signed(MockHttpServletRequestBuilder request) {
|
||||
return request.header("Authorization", "Bearer " + token);
|
||||
}
|
||||
|
||||
private JsonNode login(String email, String password, int status) throws Exception {
|
||||
return request(
|
||||
body(post("/admin-api/auth/login"), Map.of("email", email, "password", password)),
|
||||
status);
|
||||
}
|
||||
|
||||
private Map<String, Object> metadata() {
|
||||
return Map.of("name", "测试项目", "description", "内容", "projectType", "WHEELED");
|
||||
}
|
||||
|
||||
private String createProject() throws Exception {
|
||||
return request(
|
||||
signed(body(post("/admin-api/projects"), Map.of("project", metadata()))),
|
||||
200)
|
||||
.path("data")
|
||||
.path("projectCode")
|
||||
.asText();
|
||||
}
|
||||
|
||||
private JsonNode createImport() throws Exception {
|
||||
return request(
|
||||
signed(
|
||||
body(
|
||||
post("/admin-api/project-imports"),
|
||||
Map.of(
|
||||
"repositoryUrl",
|
||||
"https://github.com/example/robot",
|
||||
"project",
|
||||
metadata()))),
|
||||
202)
|
||||
.path("data");
|
||||
}
|
||||
|
||||
@Test
|
||||
void authenticationRolesIsolationAndCodeOnlyResponses() throws Exception {
|
||||
request(get("/admin-api/users"), 401);
|
||||
request(get("/api/users/me"), 401);
|
||||
login(ordinary.getEmail(), PASSWORD, 401);
|
||||
String ordinaryToken = tokens.issue(ordinary.getId(), ordinary.getSessionVersion());
|
||||
request(get("/admin-api/users").header("Authorization", "Bearer " + ordinaryToken), 403);
|
||||
assertThatThrownBy(() -> userService.login(admin.getEmail()))
|
||||
.isInstanceOf(BusinessException.class);
|
||||
JsonNode me = request(signed(get("/admin-api/auth/me")), 200).path("data");
|
||||
assertThat(me.path("role").asText()).isEqualTo("ADMIN");
|
||||
assertThat(me.has("id")).isFalse();
|
||||
assertThat(me.has("passwordHash")).isFalse();
|
||||
TokenService anotherProcess =
|
||||
new TokenService(new com.linkerbot.community.service.config.CommunityProperties());
|
||||
assertThat(anotherProcess.resolve(token)).isNull();
|
||||
request(signed(post("/admin-api/auth/logout")), 200);
|
||||
request(signed(get("/admin-api/auth/me")), 401);
|
||||
}
|
||||
|
||||
@Test
|
||||
void disableAndEnableInvalidateExistingUserSession() throws Exception {
|
||||
String old = tokens.issue(ordinary.getId(), 0);
|
||||
request(
|
||||
signed(
|
||||
body(
|
||||
put("/admin-api/users/" + ordinary.getUserCode() + "/status"),
|
||||
Map.of("status", "DISABLED"))),
|
||||
200);
|
||||
assertThatThrownBy(() -> auth.authenticate(old)).isInstanceOf(BusinessException.class);
|
||||
request(
|
||||
signed(
|
||||
body(
|
||||
put("/admin-api/users/" + ordinary.getUserCode() + "/status"),
|
||||
Map.of("status", "ACTIVE"))),
|
||||
200);
|
||||
assertThatThrownBy(() -> auth.authenticate(old)).isInstanceOf(BusinessException.class);
|
||||
assertThat(users.selectById(ordinary.getId()).getSessionVersion()).isEqualTo(2);
|
||||
request(
|
||||
signed(
|
||||
body(
|
||||
put("/admin-api/users/" + admin.getUserCode() + "/status"),
|
||||
Map.of("status", "DISABLED"))),
|
||||
409);
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordChangeAndRoleChangeInvalidateSession() throws Exception {
|
||||
request(
|
||||
signed(
|
||||
body(
|
||||
put("/admin-api/auth/password"),
|
||||
Map.of(
|
||||
"oldPassword",
|
||||
PASSWORD,
|
||||
"newPassword",
|
||||
"new-test-password-123"))),
|
||||
200);
|
||||
request(signed(get("/admin-api/auth/me")), 401);
|
||||
login(admin.getEmail(), "new-test-password-123", 200);
|
||||
jdbc.update(
|
||||
"UPDATE sys_user SET role='USER', session_version=session_version+1 WHERE"
|
||||
+ " user_code=?",
|
||||
admin.getUserCode());
|
||||
request(signed(get("/admin-api/auth/me")), 401);
|
||||
}
|
||||
|
||||
@Test
|
||||
void repeatedInvalidPasswordIsRateLimited() throws Exception {
|
||||
for (int i = 0; i < 5; i++) login(admin.getEmail(), "wrong", 401);
|
||||
login(admin.getEmail(), PASSWORD, 429);
|
||||
}
|
||||
|
||||
@Test
|
||||
void officialOwnershipFileUploadPublicationAndModeration() throws Exception {
|
||||
String code = createProject();
|
||||
JsonNode detail = request(signed(get("/admin-api/projects/" + code)), 200).path("data");
|
||||
String ownerCode = detail.path("project").path("owner").path("userCode").asText();
|
||||
User owner =
|
||||
users.selectOne(
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<
|
||||
User>()
|
||||
.eq(User::getUserCode, ownerCode));
|
||||
assertThat(owner.getRole()).isEqualTo("OFFICIAL");
|
||||
assertThatThrownBy(() -> userService.login(OfficialUsers.EMAIL))
|
||||
.isInstanceOf(BusinessException.class);
|
||||
request(
|
||||
signed(
|
||||
body(
|
||||
put("/admin-api/users/" + ownerCode + "/status"),
|
||||
Map.of("status", "DISABLED"))),
|
||||
409);
|
||||
String initial =
|
||||
request(signed(get("/admin-api/projects/" + code + "/tree")), 200)
|
||||
.path("data")
|
||||
.path("commitSha")
|
||||
.asText();
|
||||
MockMultipartFile file =
|
||||
new MockMultipartFile(
|
||||
"files",
|
||||
"机器人.txt",
|
||||
"text/plain",
|
||||
"hello".getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
String sha =
|
||||
request(
|
||||
signed(
|
||||
multipart("/admin-api/projects/" + code + "/uploads/commit")
|
||||
.file(file)
|
||||
.param("expectedCommitSha", initial)
|
||||
.param("message", "上传文件")
|
||||
.param("paths", "models/机器人.txt")),
|
||||
200)
|
||||
.path("data")
|
||||
.path("commitSha")
|
||||
.asText();
|
||||
assertThat(gitea.lastAuthorCode).isEqualTo(admin.getUserCode());
|
||||
request(
|
||||
signed(
|
||||
body(
|
||||
put("/admin-api/projects/" + code + "/publication"),
|
||||
Map.of("commitSha", initial))),
|
||||
409);
|
||||
request(
|
||||
signed(
|
||||
body(
|
||||
put("/admin-api/projects/" + code + "/publication"),
|
||||
Map.of("commitSha", sha))),
|
||||
200);
|
||||
assertThat(projectService.published(code).getPublishedCommitSha()).isEqualTo(sha);
|
||||
request(
|
||||
signed(
|
||||
body(
|
||||
post("/admin-api/projects/" + code + "/commits"),
|
||||
Map.of(
|
||||
"expectedCommitSha",
|
||||
sha,
|
||||
"message",
|
||||
"添加文件",
|
||||
"changes",
|
||||
List.of(
|
||||
Map.of(
|
||||
"action",
|
||||
"CREATE_FILE",
|
||||
"path",
|
||||
"next.txt",
|
||||
"content",
|
||||
"next"))))),
|
||||
200);
|
||||
assertThat(projectService.published(code).getPublishedCommitSha()).isEqualTo(sha);
|
||||
request(
|
||||
signed(
|
||||
body(
|
||||
put("/admin-api/projects/" + code + "/moderation"),
|
||||
Map.of("reason", "测试下架"))),
|
||||
200);
|
||||
assertThatThrownBy(() -> projectService.published(code))
|
||||
.isInstanceOf(BusinessException.class);
|
||||
JsonNode blocked = request(signed(get("/admin-api/projects/" + code)), 200).path("data");
|
||||
assertThat(blocked.path("project").path("publishStatus").asText()).isEqualTo("BLOCKED");
|
||||
assertThat(blocked.path("moderationStatus").asText()).isEqualTo("BLOCKED");
|
||||
assertThat(blocked.path("moderationReason").asText()).isEqualTo("测试下架");
|
||||
projectService.withdraw(owner.getId(), code);
|
||||
assertThat(projectService.owner(owner.getId(), code).getPublishStatus())
|
||||
.isEqualTo("BLOCKED");
|
||||
assertThatThrownBy(() -> projectService.publish(owner.getId(), code, sha))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("下架");
|
||||
request(signed(delete("/admin-api/projects/" + code + "/moderation")), 200);
|
||||
assertThatThrownBy(() -> projectService.published(code))
|
||||
.isInstanceOf(BusinessException.class);
|
||||
request(signed(delete("/admin-api/projects/" + code)), 200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void migrationPreservesSourceAndRequiresManualPublication() throws Exception {
|
||||
JsonNode task = createImport();
|
||||
String taskCode = task.path("taskCode").asText();
|
||||
String code = task.path("projectCode").asText();
|
||||
imports.run(taskCode);
|
||||
JsonNode done =
|
||||
request(signed(get("/admin-api/project-imports/" + taskCode)), 200).path("data");
|
||||
assertThat(done.path("status").asText()).isEqualTo("SUCCEEDED");
|
||||
assertThat(gitea.migrations).isEqualTo(1);
|
||||
assertThatThrownBy(() -> projectService.published(code))
|
||||
.isInstanceOf(BusinessException.class);
|
||||
JsonNode preview =
|
||||
request(
|
||||
signed(
|
||||
body(
|
||||
post("/admin-api/project-imports/preview"),
|
||||
Map.of(
|
||||
"repositoryUrl",
|
||||
"https://github.com/example/robot"))),
|
||||
200)
|
||||
.path("data");
|
||||
assertThat(preview.path("existingProjectCode").asText()).isEqualTo(code);
|
||||
request(
|
||||
signed(
|
||||
body(
|
||||
post("/admin-api/project-imports"),
|
||||
Map.of(
|
||||
"repositoryUrl",
|
||||
"https://github.com/example/robot",
|
||||
"project",
|
||||
metadata()))),
|
||||
409);
|
||||
String sha =
|
||||
request(signed(get("/admin-api/projects/" + code + "/tree")), 200)
|
||||
.path("data")
|
||||
.path("commitSha")
|
||||
.asText();
|
||||
JsonNode published =
|
||||
request(
|
||||
signed(
|
||||
body(
|
||||
put("/admin-api/projects/" + code + "/publication"),
|
||||
Map.of("commitSha", sha))),
|
||||
200)
|
||||
.path("data");
|
||||
assertThat(published.path("sourceLicense").asText()).isEqualTo("MIT");
|
||||
assertThat(published.path("sourceRepositoryUrl").asText())
|
||||
.isEqualTo("https://github.com/example/robot");
|
||||
ProjectImportTask source =
|
||||
tasks.selectOne(
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<
|
||||
ProjectImportTask>()
|
||||
.eq(ProjectImportTask::getTaskCode, taskCode));
|
||||
assertThat(source.getSourceRepositoryId()).isEqualTo(SOURCES.get());
|
||||
assertThat(source.getSourceDefaultBranch()).isEqualTo("master");
|
||||
assertThat(source.getSourceLicense()).isEqualTo("MIT");
|
||||
assertThat(published.has("externalRepositoryId")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void uncertainMigrationIsNotRepeatedAfterRestartRecovery() throws Exception {
|
||||
JsonNode task = createImport();
|
||||
String code = task.path("taskCode").asText();
|
||||
gitea.migrationTimeout = true;
|
||||
imports.run(code);
|
||||
imports.recover();
|
||||
assertThat(
|
||||
request(signed(get("/admin-api/project-imports/" + code)), 200)
|
||||
.path("data")
|
||||
.path("status")
|
||||
.asText())
|
||||
.isEqualTo("REVIEW");
|
||||
request(signed(post("/admin-api/project-imports/" + code + "/retry")), 409);
|
||||
imports.run(code);
|
||||
assertThat(gitea.migrations).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void completedReceiptCanResumeAfterBranchConflictWithoutRemigrating() throws Exception {
|
||||
JsonNode task = createImport();
|
||||
String code = task.path("taskCode").asText();
|
||||
gitea.mainConflict = true;
|
||||
imports.run(code);
|
||||
request(signed(post("/admin-api/project-imports/" + code + "/retry")), 409);
|
||||
gitea.mainConflict = false;
|
||||
Project project =
|
||||
projects.selectOne(
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<
|
||||
Project>()
|
||||
.eq(Project::getProjectCode, task.path("projectCode").asText()));
|
||||
gitea.createBranch(
|
||||
new com.linkerbot.community.service.gitea.GiteaClient.Repository(
|
||||
1, "community", project.getGiteaRepoName()),
|
||||
"main",
|
||||
"");
|
||||
com.linkerbot.community.service.gitea.GiteaClient.RemoteRepository remote =
|
||||
gitea.inspect(project.getGiteaRepoName());
|
||||
gitea.defaultBranch(remote.repository(), "main");
|
||||
request(signed(post("/admin-api/project-imports/" + code + "/retry")), 202);
|
||||
imports.run(code);
|
||||
assertThat(
|
||||
request(signed(get("/admin-api/project-imports/" + code)), 200)
|
||||
.path("data")
|
||||
.path("status")
|
||||
.asText())
|
||||
.isEqualTo("SUCCEEDED");
|
||||
assertThat(gitea.migrations).isEqualTo(1);
|
||||
String sha = gitea.head(remote.repository());
|
||||
request(
|
||||
signed(
|
||||
body(
|
||||
put(
|
||||
"/admin-api/projects/"
|
||||
+ project.getProjectCode()
|
||||
+ "/publication"),
|
||||
Map.of("commitSha", sha))),
|
||||
200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidSourceAndUserCannotEscalateRole() throws Exception {
|
||||
request(
|
||||
signed(
|
||||
body(
|
||||
post("/admin-api/project-imports/preview"),
|
||||
Map.of("repositoryUrl", "https://127.0.0.1/private"))),
|
||||
400);
|
||||
request(
|
||||
signed(
|
||||
body(
|
||||
patch("/admin-api/users/" + ordinary.getUserCode()),
|
||||
Map.of("nickname", "新昵称", "role", "ADMIN"))),
|
||||
200);
|
||||
assertThat(users.selectById(ordinary.getId()).getRole()).isEqualTo("USER");
|
||||
}
|
||||
|
||||
@Test
|
||||
void receiptPersistenceFailureCannotBeRetriedAsSuccessfulMigration() throws Exception {
|
||||
JsonNode task = createImport();
|
||||
String code = task.path("taskCode").asText();
|
||||
jdbc.execute("ALTER TABLE project_import_task ALTER COLUMN receipt_json VARCHAR(1)");
|
||||
imports.run(code);
|
||||
ProjectImportTask failed =
|
||||
tasks.selectOne(
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<
|
||||
ProjectImportTask>()
|
||||
.eq(ProjectImportTask::getTaskCode, code));
|
||||
assertThat(failed.getStatus()).isEqualTo("REVIEW");
|
||||
assertThat(failed.getReceiptJson()).isNull();
|
||||
assertThat(gitea.migrations).isEqualTo(1);
|
||||
request(signed(post("/admin-api/project-imports/" + code + "/retry")), 409);
|
||||
}
|
||||
|
||||
@Test
|
||||
void receiptSurvivesAssociationFailureAndResumesWithoutSecondMigration() throws Exception {
|
||||
JsonNode task = createImport();
|
||||
String code = task.path("taskCode").asText();
|
||||
jdbc.execute(
|
||||
"ALTER TABLE project ADD CONSTRAINT simulate_link_failure CHECK (repo_status <>"
|
||||
+ " 'READY')");
|
||||
imports.run(code);
|
||||
ProjectImportTask failed =
|
||||
tasks.selectOne(
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<
|
||||
ProjectImportTask>()
|
||||
.eq(ProjectImportTask::getTaskCode, code));
|
||||
assertThat(failed.getStatus()).isEqualTo("REVIEW");
|
||||
assertThat(failed.getReceiptJson()).isNotNull();
|
||||
assertThat(failed.getPhase()).isEqualTo("BRANCH_READY");
|
||||
assertThat(
|
||||
jdbc.queryForObject(
|
||||
"SELECT repo_status FROM project WHERE project_code=?",
|
||||
String.class,
|
||||
task.path("projectCode").asText()))
|
||||
.isEqualTo("CREATING");
|
||||
jdbc.execute("ALTER TABLE project DROP CONSTRAINT simulate_link_failure");
|
||||
request(signed(post("/admin-api/project-imports/" + code + "/retry")), 202);
|
||||
imports.run(code);
|
||||
assertThat(
|
||||
request(signed(get("/admin-api/project-imports/" + code)), 200)
|
||||
.path("data")
|
||||
.path("status")
|
||||
.asText())
|
||||
.isEqualTo("SUCCEEDED");
|
||||
assertThat(gitea.migrations).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void interruptedMigrationIsReviewedAndCompletedReceiptCanResume() throws Exception {
|
||||
JsonNode task = createImport();
|
||||
String code = task.path("taskCode").asText();
|
||||
String projectCode = task.path("projectCode").asText();
|
||||
com.linkerbot.community.service.gitea.GiteaClient.RemoteRepository receipt =
|
||||
gitea.migrate(
|
||||
"https://github.com/example/robot.git",
|
||||
"p_" + projectCode,
|
||||
java.time.Duration.ofMinutes(30));
|
||||
jdbc.update(
|
||||
"UPDATE project_import_task SET status='RUNNING',phase='MIGRATED',receipt_json=?"
|
||||
+ " WHERE task_code=?",
|
||||
json.writeValueAsString(receipt),
|
||||
code);
|
||||
jdbc.update(
|
||||
"UPDATE project SET repo_write_status='WRITING' WHERE project_code=?", projectCode);
|
||||
imports.recover();
|
||||
assertThat(
|
||||
request(signed(get("/admin-api/project-imports/" + code)), 200)
|
||||
.path("data")
|
||||
.path("status")
|
||||
.asText())
|
||||
.isEqualTo("REVIEW");
|
||||
request(signed(post("/admin-api/project-imports/" + code + "/retry")), 202);
|
||||
imports.run(code);
|
||||
assertThat(
|
||||
request(signed(get("/admin-api/project-imports/" + code)), 200)
|
||||
.path("data")
|
||||
.path("status")
|
||||
.asText())
|
||||
.isEqualTo("SUCCEEDED");
|
||||
assertThat(gitea.migrations).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void designatedOwnerRemainsSeparateAndAdminScopeIsAlwaysCleared() throws Exception {
|
||||
String code =
|
||||
request(
|
||||
signed(
|
||||
body(
|
||||
post("/admin-api/projects"),
|
||||
Map.of(
|
||||
"ownerUserCode",
|
||||
ordinary.getUserCode(),
|
||||
"project",
|
||||
metadata()))),
|
||||
200)
|
||||
.path("data")
|
||||
.path("projectCode")
|
||||
.asText();
|
||||
assertThat(ProjectActors.isAdmin()).isFalse();
|
||||
assertThat(projectService.owner(ordinary.getId(), code).getOwnerUserId())
|
||||
.isEqualTo(ordinary.getId());
|
||||
assertThatThrownBy(() -> projectService.owner(admin.getId(), code))
|
||||
.isInstanceOf(BusinessException.class);
|
||||
}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
package com.linkerbot.community.adminapi;
|
||||
|
||||
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();
|
||||
String lastAuthorCode;
|
||||
int migrations;
|
||||
boolean migrationTimeout;
|
||||
boolean mainConflict;
|
||||
private final Map<String, RemoteRepository> migrated = new HashMap<>();
|
||||
private final Set<String> mainReady = new HashSet<>();
|
||||
boolean timeoutNextCommit;
|
||||
boolean timeoutNextCreate;
|
||||
boolean failNextCreate;
|
||||
|
||||
void reset() {
|
||||
repositories.clear();
|
||||
migrated.clear();
|
||||
mainReady.clear();
|
||||
migrations = 0;
|
||||
migrationTimeout = false;
|
||||
mainConflict = false;
|
||||
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());
|
||||
}
|
||||
|
||||
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) {
|
||||
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) {
|
||||
lastAuthorCode = 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());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkMigrationSettings() {}
|
||||
|
||||
@Override
|
||||
public synchronized RemoteRepository migrate(
|
||||
String source, String name, java.time.Duration timeout) {
|
||||
migrations++;
|
||||
Repository repository = createRepository(name, true);
|
||||
RemoteRepository remote =
|
||||
new RemoteRepository(
|
||||
repository.id(), "community", name, true, false, false, source, "master");
|
||||
migrated.put(name, remote);
|
||||
if (migrationTimeout) throw new GiteaFailure(504, "REMOTE_RESULT_UNKNOWN", "迁移结果不明", true);
|
||||
return remote;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized RemoteRepository inspect(String name) {
|
||||
RemoteRepository remote = migrated.get(name);
|
||||
if (remote == null) throw new GiteaFailure(404, "NOT_FOUND", "仓库不存在", false);
|
||||
return remote;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized String branch(Repository repository, String branch) {
|
||||
if (branch.equals("main") && mainConflict) return "f".repeat(40);
|
||||
if (branch.equals("main") && !mainReady.contains(repository.name()))
|
||||
throw new GiteaFailure(404, "NOT_FOUND", "分支不存在", false);
|
||||
return head(repository);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void createBranch(Repository repository, String name, String sha) {
|
||||
mainReady.add(repository.name());
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void defaultBranch(Repository repository, String branch) {
|
||||
RemoteRepository remote = migrated.get(repository.name());
|
||||
migrated.put(
|
||||
repository.name(),
|
||||
new RemoteRepository(
|
||||
remote.id(),
|
||||
remote.owner(),
|
||||
remote.name(),
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
remote.originalUrl(),
|
||||
branch));
|
||||
}
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
package com.linkerbot.community.adminapi;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
|
||||
import com.linkerbot.community.common.BusinessException;
|
||||
import com.linkerbot.community.service.mapper.ProjectMapper;
|
||||
import com.linkerbot.community.service.support.ProjectLocks;
|
||||
import com.zaxxer.hikari.*;
|
||||
|
||||
import org.apache.ibatis.session.SqlSessionFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.mybatis.spring.SqlSessionTemplate;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.regex.*;
|
||||
|
||||
/** 只在新建的随机临时数据库验证,绝不对连接所指向的现有业务库执行DDL或写入。 */
|
||||
@EnabledIfEnvironmentVariable(named = "ADMIN_MYSQL_TEST_URL", matches = "jdbc:mysql:.*")
|
||||
class ProjectLocksMySqlTest {
|
||||
@Test
|
||||
void independentApplicationsShareLocksAndPersistUncertainWrites() throws Exception {
|
||||
String url = System.getenv("ADMIN_MYSQL_TEST_URL");
|
||||
String username = System.getenv("ADMIN_MYSQL_TEST_USERNAME");
|
||||
String password = System.getenv("ADMIN_MYSQL_TEST_PASSWORD");
|
||||
String database = "community_admin_verify_" + UUID.randomUUID().toString().replace("-", "");
|
||||
try (Connection bootstrap =
|
||||
DriverManager.getConnection(url, username, password == null ? "" : password)) {
|
||||
assertThat(bootstrap.getMetaData().getDatabaseProductName()).isEqualTo("MySQL");
|
||||
try (Statement statement = bootstrap.createStatement()) {
|
||||
statement.execute(
|
||||
"CREATE DATABASE "
|
||||
+ database
|
||||
+ " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
|
||||
}
|
||||
try {
|
||||
String plain = url.split("\\?", 2)[0];
|
||||
String isolated =
|
||||
plain.substring(0, plain.lastIndexOf('/') + 1)
|
||||
+ database
|
||||
+ (url.contains("?") ? "?" + url.split("\\?", 2)[1] : "");
|
||||
HikariConfig config = new HikariConfig();
|
||||
config.setJdbcUrl(isolated);
|
||||
config.setUsername(username);
|
||||
config.setPassword(password);
|
||||
config.setMaximumPoolSize(4);
|
||||
try (HikariDataSource source = new HikariDataSource(config)) {
|
||||
JdbcTemplate jdbc = new JdbcTemplate(source);
|
||||
for (String doc : List.of("database.md", "admin-database.md")) {
|
||||
Matcher tables =
|
||||
Pattern.compile("CREATE TABLE [\\s\\S]*?;")
|
||||
.matcher(Files.readString(Path.of("../docs/" + doc)));
|
||||
while (tables.find()) jdbc.execute(tables.group());
|
||||
}
|
||||
jdbc.update(
|
||||
"INSERT INTO"
|
||||
+ " sys_user(user_code,email,nickname,status,created_at,updated_at)"
|
||||
+ " VALUES"
|
||||
+ " ('111111111111','verify@example.invalid','verify','ACTIVE',UTC_TIMESTAMP(3),UTC_TIMESTAMP(3))");
|
||||
jdbc.update(
|
||||
"INSERT INTO"
|
||||
+ " project(project_code,owner_user_id,name,description,project_type,gitea_owner,gitea_repo_name,created_at,updated_at)"
|
||||
+ " SELECT"
|
||||
+ " '222222222222',id,'verify','','GENERAL','community','p_222222222222',UTC_TIMESTAMP(3),UTC_TIMESTAMP(3)"
|
||||
+ " FROM sys_user WHERE user_code='111111111111'");
|
||||
MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
|
||||
factory.setDataSource(source);
|
||||
SqlSessionFactory sessions = factory.getObject();
|
||||
sessions.getConfiguration().addMapper(ProjectMapper.class);
|
||||
ProjectMapper mapper =
|
||||
new SqlSessionTemplate(sessions).getMapper(ProjectMapper.class);
|
||||
ProjectLocks first = new ProjectLocks(source, mapper);
|
||||
ProjectLocks second = new ProjectLocks(source, mapper);
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
CountDownLatch entered = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
Future<String> writer =
|
||||
executor.submit(
|
||||
() ->
|
||||
first.write(
|
||||
"222222222222",
|
||||
() -> {
|
||||
entered.countDown();
|
||||
await(release);
|
||||
return "done";
|
||||
}));
|
||||
assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue();
|
||||
assertThat(
|
||||
jdbc.queryForObject(
|
||||
"SELECT repo_write_status FROM project WHERE"
|
||||
+ " project_code='222222222222'",
|
||||
String.class))
|
||||
.isEqualTo("WRITING");
|
||||
Future<String> other =
|
||||
executor.submit(() -> second.serial("222222222222", () -> "other"));
|
||||
Thread.sleep(100);
|
||||
assertThat(other.isDone()).isFalse();
|
||||
release.countDown();
|
||||
assertThat(writer.get(5, TimeUnit.SECONDS)).isEqualTo("done");
|
||||
assertThat(other.get(5, TimeUnit.SECONDS)).isEqualTo("other");
|
||||
assertThat(
|
||||
first.serial(
|
||||
"222222222222",
|
||||
() ->
|
||||
first.serial(
|
||||
"222222222222", () -> "reentrant")))
|
||||
.isEqualTo("reentrant");
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
first.write(
|
||||
"222222222222",
|
||||
() -> {
|
||||
throw new IllegalStateException(
|
||||
"simulated remote failure");
|
||||
}))
|
||||
.isInstanceOf(IllegalStateException.class);
|
||||
assertThat(
|
||||
jdbc.queryForObject(
|
||||
"SELECT repo_write_status FROM project WHERE"
|
||||
+ " project_code='222222222222'",
|
||||
String.class))
|
||||
.isEqualTo("REVIEW");
|
||||
first.close();
|
||||
assertThatThrownBy(() -> second.write("222222222222", () -> "unsafe retry"))
|
||||
.isInstanceOf(BusinessException.class);
|
||||
// 模拟进程在写入中退出:只有持久化WRITING,新的进程仍必须阻断。
|
||||
jdbc.update(
|
||||
"UPDATE project SET repo_write_status='WRITING' WHERE"
|
||||
+ " project_code='222222222222'");
|
||||
ProjectLocks restarted = new ProjectLocks(source, mapper);
|
||||
try {
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
restarted.write(
|
||||
"222222222222", () -> "unsafe restart"))
|
||||
.isInstanceOf(BusinessException.class);
|
||||
} finally {
|
||||
restarted.close();
|
||||
}
|
||||
// 断开真正持锁连接,检查不会把未知状态清为空闲。
|
||||
second.serial(
|
||||
"222222222222",
|
||||
() -> {
|
||||
second.confirmKnownResult("222222222222");
|
||||
return null;
|
||||
});
|
||||
String namespace = Integer.toHexString(database.hashCode());
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
second.write(
|
||||
"222222222222",
|
||||
() -> {
|
||||
Long connection =
|
||||
jdbc.queryForObject(
|
||||
"SELECT"
|
||||
+ " IS_USED_LOCK(?)",
|
||||
Long.class,
|
||||
"community:"
|
||||
+ namespace
|
||||
+ ":222222222222");
|
||||
jdbc.execute(
|
||||
"KILL CONNECTION "
|
||||
+ connection);
|
||||
return "unconfirmed";
|
||||
}))
|
||||
.isInstanceOf(BusinessException.class);
|
||||
assertThat(
|
||||
jdbc.queryForObject(
|
||||
"SELECT repo_write_status FROM project WHERE"
|
||||
+ " project_code='222222222222'",
|
||||
String.class))
|
||||
.isEqualTo("REVIEW");
|
||||
System.out.println("MySQL共享锁、重入、持久化阻断及连接断开验证完成,临时库=" + database);
|
||||
} finally {
|
||||
executor.shutdownNow();
|
||||
first.close();
|
||||
second.close();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
try (Statement statement = bootstrap.createStatement()) {
|
||||
statement.execute("DROP DATABASE " + database);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void await(CountDownLatch latch) {
|
||||
try {
|
||||
if (!latch.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("锁测试超时");
|
||||
} catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user