安全与效率优化,引入Redis,包名修改

This commit is contained in:
lxp
2026-10-22 14:01:10 +08:00
parent cdc1e4d261
commit 961a61afb4
231 changed files with 5782 additions and 2049 deletions
@@ -0,0 +1,26 @@
package com.linkerbot.vibemake.adminapi;
import com.linkerbot.vibemake.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.vibemake.service.mapper")
@Import(TokenService.class)
@SpringBootApplication(
scanBasePackages = {
"com.linkerbot.vibemake.adminapi",
"com.linkerbot.vibemake.service",
"com.linkerbot.vibemake.common"
},
exclude = UserDetailsServiceAutoConfiguration.class)
public class AdminApplication {
public static void main(String[] args) {
SpringApplication.run(AdminApplication.class, args);
}
}
@@ -0,0 +1,39 @@
package com.linkerbot.vibemake.adminapi.config;
import com.linkerbot.vibemake.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);
}
}
@@ -0,0 +1,25 @@
package com.linkerbot.vibemake.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("Vibemake 管理端接口").version("v1"))
.components(
new Components()
.addSecuritySchemes(
"bearerAuth",
new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")))
.addSecurityItem(new SecurityRequirement().addList("bearerAuth"));
}
}
@@ -0,0 +1,111 @@
package com.linkerbot.vibemake.adminapi.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.adminapi.security.AdminTokenFilter;
import com.linkerbot.vibemake.common.*;
import com.linkerbot.vibemake.service.config.AdminProperties;
import com.linkerbot.vibemake.service.state.HttpSafetyFilter;
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<HttpSafetyFilter> disableSafetyServletRegistration(
HttpSafetyFilter filter) {
FilterRegistrationBean<HttpSafetyFilter> registration =
new FilterRegistrationBean<>(filter);
registration.setEnabled(false);
return registration;
}
@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,
HttpSafetyFilter safety)
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", "Retry-After"));
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",
"无后台访问权限")));
}))
.addFilterAfter(safety, org.springframework.web.filter.CorsFilter.class)
.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
@@ -0,0 +1,83 @@
package com.linkerbot.vibemake.adminapi.config;
import com.linkerbot.vibemake.service.admin.AdminImportService;
import com.linkerbot.vibemake.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();
}
}
@@ -0,0 +1,41 @@
package com.linkerbot.vibemake.adminapi.config;
import org.springframework.boot.ApplicationArguments;
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, ApplicationArguments arguments) {
for (String property :
List.of(
"spring.datasource.url",
"spring.datasource.username",
"spring.datasource.password",
"vibemake.gitea.base-url",
"vibemake.gitea.token",
"vibemake.gitea.owner")) {
String value;
try {
value = environment.getRequiredProperty(property);
} catch (IllegalArgumentException | IllegalStateException error) {
// 仅提示配置项名称,避免异常链携带配置值。
throw new IllegalStateException("生产环境必须配置 " + property);
}
if (value.isBlank()) {
throw new IllegalStateException("生产环境必须配置 " + property);
}
}
if (!arguments.containsOption("bootstrap-admin-user-code")) {
for (String property : List.of("REDIS_HOST", "REDIS_PASSWORD")) {
String value = environment.getProperty(property);
if (value == null || value.isBlank())
throw new IllegalStateException("生产环境必须配置 " + property);
}
}
}
}
@@ -0,0 +1,49 @@
package com.linkerbot.vibemake.adminapi.controller;
import com.linkerbot.vibemake.adminapi.security.*;
import com.linkerbot.vibemake.bean.AdminContracts.*;
import com.linkerbot.vibemake.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;
private final com.linkerbot.vibemake.service.state.ClientAddresses addresses;
@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, addresses.resolve(request))));
}
@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);
}
}
@@ -0,0 +1,55 @@
package com.linkerbot.vibemake.adminapi.controller;
import com.linkerbot.vibemake.bean.AdminContracts.*;
import com.linkerbot.vibemake.bean.Contracts.UrdfUploadSignature;
import com.linkerbot.vibemake.common.*;
import com.linkerbot.vibemake.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("/urdf/signature")
public ApiResponse<UrdfUploadSignature> urdfSignature(
@Valid @RequestBody ImportUrdfUploadInput input) {
return ApiResponse.success(service.urdfSignature(input));
}
@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)));
}
}
@@ -0,0 +1,181 @@
package com.linkerbot.vibemake.adminapi.controller;
import com.linkerbot.vibemake.bean.AdminContracts.*;
import com.linkerbot.vibemake.bean.Contracts.*;
import com.linkerbot.vibemake.common.*;
import com.linkerbot.vibemake.service.*;
import com.linkerbot.vibemake.service.admin.AdminManagementService;
import com.linkerbot.vibemake.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);
}
}
@@ -0,0 +1,27 @@
package com.linkerbot.vibemake.adminapi.controller;
import com.linkerbot.vibemake.bean.Contracts.*;
import com.linkerbot.vibemake.common.ApiResponse;
import com.linkerbot.vibemake.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)));
}
}
@@ -0,0 +1,58 @@
package com.linkerbot.vibemake.adminapi.controller;
import com.linkerbot.vibemake.bean.AdminContracts.*;
import com.linkerbot.vibemake.common.*;
import com.linkerbot.vibemake.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));
}
}
@@ -0,0 +1,146 @@
package com.linkerbot.vibemake.adminapi.security;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.linkerbot.vibemake.bean.AdminContracts.*;
import com.linkerbot.vibemake.bean.entity.User;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.common.RateLimitedException;
import com.linkerbot.vibemake.common.SecurityHashes;
import com.linkerbot.vibemake.common.state.TransientStateStore;
import com.linkerbot.vibemake.security.TokenService;
import com.linkerbot.vibemake.service.config.VibemakeProperties;
import com.linkerbot.vibemake.service.mapper.UserMapper;
import com.linkerbot.vibemake.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 VibemakeProperties properties;
private final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(12);
private final String dummyHash = encoder.encode("invalid-admin-password");
private final TransientStateStore failures;
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.remove(failureKey("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) {
String stored = failures.get(failureKey(key));
if (stored != null && Long.parseLong(stored) >= limit)
throw new RateLimitedException(
"ADMIN_LOGIN_LIMITED",
"尝试次数过多,请稍后重试",
failures.remainingSeconds(failureKey(key)));
}
private void failure(String key) {
failures.increment(failureKey(key), Duration.ofMinutes(15), true);
}
private String failureKey(String key) {
return "admin-failure:" + SecurityHashes.sha256(key);
}
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字节");
}
}
@@ -0,0 +1,83 @@
package com.linkerbot.vibemake.adminapi.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.bean.entity.User;
import com.linkerbot.vibemake.common.*;
import com.linkerbot.vibemake.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();
}
}
}
@@ -0,0 +1,18 @@
package com.linkerbot.vibemake.adminapi.security;
import com.linkerbot.vibemake.bean.entity.User;
import com.linkerbot.vibemake.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,39 @@
spring:
data:
redis:
# bootstrap 命令不连接 Redis;正常 prod 启动由 ProductionConfiguration 要求显式配置。
host: ${REDIS_HOST:localhost}
password: ${REDIS_PASSWORD:}
datasource:
url: ${DB_URL}
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
pool-name: VibemakeAdminHikariCP
minimum-idle: 1
maximum-pool-size: 20
connection-timeout: 5000
vibemake:
redis:
key-prefix: ${REDIS_KEY_PREFIX:vibemake:prod}
cors:
allowed-origins:
- https://vibemake.robotquan.com
oss:
root-directory: vibemake
gitea:
base-url: ${GITEA_BASE_URL}
owner: ${GITEA_ORGANIZATION}
token: ${GITEA_TOKEN}
logging:
level:
com.linkerbot.vibemake: INFO
springdoc:
api-docs:
enabled: false
swagger-ui:
enabled: false
@@ -0,0 +1,26 @@
spring:
datasource:
url: ${DB_URL:jdbc:mysql://localhost:3306/vibemake?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: VibemakeAdminHikariCP
minimum-idle: 1
maximum-pool-size: 10
connection-timeout: 5000
vibemake:
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:vibemake}
token: ${GITEA_TOKEN:}
logging:
level:
com.linkerbot.vibemake: DEBUG
@@ -0,0 +1,120 @@
server:
port: ${ADMIN_SERVER_PORT:8994}
spring:
application:
name: vibemake-adminapi
profiles:
default: test
sql:
init:
mode: never
servlet:
multipart:
max-file-size: 10MB
max-request-size: 52MB
jackson:
time-zone: UTC
data:
redis:
host: ${REDIS_HOST:localhost}
port: ${REDIS_PORT:6379}
username: ${REDIS_USERNAME:}
password: ${REDIS_PASSWORD:}
database: ${REDIS_DATABASE:0}
connect-timeout: ${REDIS_CONNECT_TIMEOUT:2s}
timeout: ${REDIS_TIMEOUT:1s}
client-name: ${spring.application.name}
ssl:
enabled: ${REDIS_SSL_ENABLED:false}
repositories:
enabled: false
main:
banner-mode: off
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
vibemake:
redis:
key-prefix: ${REDIS_KEY_PREFIX:vibemake:test}
application: admin
limits:
trusted-proxies: ${TRUSTED_PROXY_CIDRS:}
json-bytes: ${HTTP_JSON_MAX_BYTES:262144}
urdf-json-bytes: ${HTTP_URDF_JSON_MAX_BYTES:2097152}
commit-json-bytes: ${HTTP_COMMIT_JSON_MAX_BYTES:67108864}
file-concurrent: ${FILE_MAX_CONCURRENT:4}
per-minute:
captcha: ${RATE_CAPTCHA_PER_MINUTE:20}
login-ip: ${RATE_LOGIN_IP_PER_MINUTE:20}
login-account: ${RATE_LOGIN_ACCOUNT_PER_MINUTE:10}
admin-login: ${RATE_ADMIN_LOGIN_PER_MINUTE:30}
vibemake-read: ${RATE_VIBEMAKE_READ_PER_MINUTE:120}
file-read: ${RATE_FILE_READ_PER_MINUTE:60}
create: ${RATE_CREATE_PER_MINUTE:5}
fork: ${RATE_FORK_PER_MINUTE:10}
file-write: ${RATE_FILE_WRITE_PER_MINUTE:10}
cover-sign: ${RATE_COVER_SIGN_PER_MINUTE:30}
urdf-sign: ${RATE_URDF_SIGN_PER_MINUTE:20}
comment: ${RATE_COMMENT_PER_MINUTE:10}
like: ${RATE_LIKE_PER_MINUTE:60}
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: true
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}/vibemake-fork}
springdoc:
swagger-ui:
path: /swagger-ui.html
logging:
file:
path: ${LOG_PATH:logs}
level:
root: INFO
# 测试环境开启项目 DEBUG 时,仍不输出 SQL 参数或完整请求内容。
com.linkerbot.vibemake.service.mapper: INFO
org.springframework.web: INFO
# 管理端有独立的跨域配置,不复用社区前端来源。
@@ -0,0 +1,261 @@
package com.linkerbot.vibemake.adminapi;
import com.linkerbot.vibemake.bean.Contracts.*;
import com.linkerbot.vibemake.common.PageResponse;
import com.linkerbot.vibemake.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 migrationRejected;
boolean timeoutNextDelete;
boolean deletionRejected;
int deletions;
boolean mainConflict;
private final Map<String, RemoteRepository> migrated = new HashMap<>();
final Map<String, String> migrationDescriptions = 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;
deletions = 0;
migrationDescriptions.clear();
migrationTimeout = false;
migrationRejected = false;
timeoutNextDelete = false;
deletionRejected = 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(), "vibemake", 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) {
return migrate(source, name, timeout, null);
}
@Override
public synchronized RemoteRepository migrate(
String source, String name, java.time.Duration timeout, String description) {
migrations++;
Repository repository = createRepository(name, true);
RemoteRepository remote =
new RemoteRepository(
repository.id(), "vibemake", name, true, false, false, source, "master");
migrated.put(name, remote);
migrationDescriptions.put(name, description);
if (migrationTimeout) throw new GiteaFailure(504, "REMOTE_RESULT_UNKNOWN", "迁移结果不明", true);
if (migrationRejected) throw new GiteaFailure(422, "GITEA_MIGRATION_REJECTED", "迁移失败", false);
return remote;
}
@Override
public synchronized MigrationTarget inspectMigrationTarget(String name) {
return new MigrationTarget(inspect(name), migrationDescriptions.get(name));
}
@Override
public synchronized void deleteRepository(Repository repository) {
if (inspect(repository.name()).id() != repository.id())
throw new GiteaFailure(409, "GITEA_CONFLICT", "仓库身份已变化", false);
if (deletionRejected) throw new GiteaFailure(502, "GITEA_ERROR", "清理失败", false);
deletions++;
migrated.remove(repository.name());
migrationDescriptions.remove(repository.name());
mainReady.remove(repository.name());
repositories.remove(repository.id());
if (timeoutNextDelete) {
timeoutNextDelete = false;
throw new GiteaFailure(504, "REMOTE_RESULT_UNKNOWN", "删除结果不明", true);
}
}
@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));
}
}
@@ -0,0 +1,26 @@
package com.linkerbot.vibemake.adminapi;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.oss.OssObjectStore;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
final class FakeOssObjectStore implements OssObjectStore {
final Map<String, Metadata> objects = new ConcurrentHashMap<>();
@Override
public Metadata head(String objectKey) {
Metadata metadata = objects.get(objectKey);
if (metadata == null)
throw new BusinessException(400, "URDF_FILE_MISSING", "URDF 文件未上传完整,请重新上传");
return metadata;
}
@Override
public void copy(String sourceKey, String targetKey, String sourceEtag) {
Metadata source = head(sourceKey);
if (!source.etag().equals(sourceEtag)) throw BusinessException.conflict("源文件发生变化");
objects.put(targetKey, source);
}
}
@@ -0,0 +1,52 @@
package com.linkerbot.vibemake.adminapi;
import static org.assertj.core.api.Assertions.*;
import com.linkerbot.vibemake.adminapi.config.ProductionConfiguration;
import org.junit.jupiter.api.Test;
import org.springframework.boot.DefaultApplicationArguments;
import org.springframework.mock.env.MockEnvironment;
class ProductionConfigurationTest {
private MockEnvironment configuredBusiness() {
return new MockEnvironment()
.withProperty("spring.datasource.url", "jdbc:mysql://localhost/test")
.withProperty("spring.datasource.username", "fixture")
.withProperty("spring.datasource.password", "do-not-log-this")
.withProperty("vibemake.gitea.base-url", "https://example.invalid")
.withProperty("vibemake.gitea.token", "do-not-log-this")
.withProperty("vibemake.gitea.owner", "fixture");
}
@Test
void bootstrapDoesNotRequireRedisConfiguration() {
assertThatCode(
() ->
new ProductionConfiguration(
configuredBusiness(),
new DefaultApplicationArguments(
"--bootstrap-admin-user-code=111111111111")))
.doesNotThrowAnyException();
}
@Test
void normalProductionRequiresExplicitCredentialsWithoutLeakingValues() {
MockEnvironment environment = configuredBusiness();
assertThatThrownBy(
() ->
new ProductionConfiguration(
environment, new DefaultApplicationArguments()))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("REDIS_HOST")
.hasMessageNotContaining("do-not-log-this");
environment
.withProperty("REDIS_HOST", "localhost")
.withProperty("REDIS_PASSWORD", "fixture");
assertThatCode(
() ->
new ProductionConfiguration(
environment, new DefaultApplicationArguments()))
.doesNotThrowAnyException();
}
}
@@ -0,0 +1,202 @@
package com.linkerbot.vibemake.adminapi;
import static org.assertj.core.api.Assertions.*;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.mapper.ProjectMapper;
import com.linkerbot.vibemake.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 = "vibemake_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','vibemake','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,
"vibemake:"
+ 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);
}
}
}