feat: add model groups, verified registration and CNY credit grants
This commit is contained in:
1 parent
f5ba6cb255
commit
7a18db2123
40 files changed
+1980
-263
No files matched your search
@@ -20,6 +20,15 @@
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-mail</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>dysmsapi20170525</artifactId>
|
||||
<version>4.6.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
|
||||
@@ -6,6 +6,11 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class HealthController {
|
||||
private final com.moyi.controlplane.auth.VerificationService verification;
|
||||
|
||||
public HealthController(com.moyi.controlplane.auth.VerificationService verification) {
|
||||
this.verification = verification;
|
||||
}
|
||||
@GetMapping("/health")
|
||||
public Map<String, Object> health() {
|
||||
return Map.of(
|
||||
@@ -13,7 +18,7 @@ public class HealthController {
|
||||
"service", "moyi-control-plane-java",
|
||||
"migration", "catalog",
|
||||
"capabilities", Map.of(
|
||||
"verificationCode", false,
|
||||
"verificationCode", verification.capabilities().containsValue(true),
|
||||
"passwordReset", false
|
||||
)
|
||||
);
|
||||
|
||||
@@ -26,26 +26,44 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
public class AuthController {
|
||||
private static final String SESSION_COOKIE = "moyi_session";
|
||||
private final AuthService authService;
|
||||
private final VerificationService verification;
|
||||
private final int sessionTtlHours;
|
||||
private final boolean secureCookie;
|
||||
|
||||
public AuthController(
|
||||
AuthService authService,
|
||||
VerificationService verification,
|
||||
@Value("${moyi.auth.session-ttl-hours}") int sessionTtlHours,
|
||||
@Value("${moyi.auth.secure-cookie}") boolean secureCookie
|
||||
) {
|
||||
this.authService = authService;
|
||||
this.verification = verification;
|
||||
this.sessionTtlHours = sessionTtlHours;
|
||||
this.secureCookie = secureCookie;
|
||||
}
|
||||
|
||||
public record LoginRequest(String account, String password) {}
|
||||
|
||||
public record RegisterRequest(String invitationCode, String account, String password, String displayName) {}
|
||||
public record RegisterRequest(String invitationCode, String account, String password, String displayName, String verificationCode) {}
|
||||
public record CodeRequest(String account, String invitationCode) {}
|
||||
|
||||
@GetMapping("/auth/verification")
|
||||
public Map<String,Boolean> verificationStatus() { return verification.capabilities(); }
|
||||
|
||||
@PostMapping("/auth/verification")
|
||||
public Map<String,Object> sendCode(@RequestBody CodeRequest input,HttpServletRequest request) {
|
||||
return verification.send(input.account(),input.invitationCode(),request.getRemoteAddr());
|
||||
}
|
||||
|
||||
public record InvitationRequest(String label, Integer maxUses, OffsetDateTime expiresAt) {}
|
||||
|
||||
public record RoleRequest(String role) {}
|
||||
public record CreateUserRequest(String account, String password, String displayName) {}
|
||||
|
||||
@PostMapping("/admin/users")
|
||||
public ResponseEntity<Map<String,Object>> createUser(@RequestBody CreateUserRequest input, HttpServletRequest request) {
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(Map.of("user",authService.createUser(sessionToken(request),input.account(),input.password(),input.displayName(),meta(request))));
|
||||
}
|
||||
|
||||
@PostMapping("/auth/login")
|
||||
public Map<String, Object> login(
|
||||
@@ -64,6 +82,7 @@ public class AuthController {
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response
|
||||
) {
|
||||
verification.consume(input.account(),input.verificationCode());
|
||||
AuthService.AuthResult result = authService.register(
|
||||
input.invitationCode(), input.account(), input.password(), input.displayName(), meta(request)
|
||||
);
|
||||
|
||||
@@ -234,6 +234,25 @@ public class AuthService {
|
||||
return jdbc.query("SELECT * FROM users ORDER BY created_at DESC", this::mapUser).stream().map(user -> toView(user, null)).toList();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserView createUser(String token, String accountInput, String password, String displayName, RequestMeta meta) {
|
||||
UserView actor=requireAdmin(token);
|
||||
String account=normalizeAccount(accountInput);
|
||||
if(account.isBlank() || account.length()>254 || (!EMAIL.matcher(account).matches() && !PHONE.matcher(account).matches() && !account.matches("[a-z0-9_]{3,64}"))) throw new ApiException("INVALID_ACCOUNT","请输入有效邮箱、手机号或 3 至 64 位字母数字下划线用户名");
|
||||
if(password==null || password.length()<8 || password.length()>256) throw new ApiException("WEAK_PASSWORD","普通用户密码长度为 8 至 256 位");
|
||||
if(findUserByAccount(account)!=null) throw new ApiException("ACCOUNT_EXISTS","账号已存在",409);
|
||||
String name=displayName==null || displayName.isBlank()?defaultDisplayName(account):displayName.trim();
|
||||
if(name.length()>80) throw new ApiException("INVALID_NAME","显示名称最多 80 字符");
|
||||
UUID id=UUID.randomUUID();
|
||||
jdbc.update("INSERT INTO users(id,account,account_kind,password_hash,display_name,role,status) VALUES (?,?,?,?,?,'user','active')",id,account,accountKind(account),passwordHasher.hash(password),name);
|
||||
authCreatedAudit(actor.id(),id,meta);
|
||||
return toView(findUserById(id),null);
|
||||
}
|
||||
|
||||
private void authCreatedAudit(UUID actor, UUID user, RequestMeta meta) {
|
||||
audit("user.admin_created",actor,meta,Map.of("targetUserId",user));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Map<String, Object> createInvitation(
|
||||
String token,
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.moyi.controlplane.auth;
|
||||
|
||||
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
|
||||
import com.aliyun.teaopenapi.models.Config;
|
||||
import com.aliyun.teautil.models.RuntimeOptions;
|
||||
import com.moyi.controlplane.common.ApiException;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class CloudVerificationSender implements VerificationSender {
|
||||
private final Environment env;
|
||||
public CloudVerificationSender(Environment env) { this.env=env; }
|
||||
private String value(String key) { return env.getProperty(key,"").trim(); }
|
||||
|
||||
@Override
|
||||
public boolean available(String channel) {
|
||||
if("email".equals(channel)) return !value("MOYI_SMTP_HOST").isEmpty() && !value("MOYI_SMTP_FROM").isEmpty();
|
||||
return !value("MOYI_SMS_ACCESS_KEY_ID").isEmpty() && !value("MOYI_SMS_ACCESS_KEY_SECRET").isEmpty() && !value("MOYI_SMS_SIGN_NAME").isEmpty() && !value("MOYI_SMS_TEMPLATE_CODE").isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(String channel,String account,String code) {
|
||||
if(!available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
|
||||
try {
|
||||
if("email".equals(channel)) {
|
||||
JavaMailSenderImpl mail=new JavaMailSenderImpl();
|
||||
mail.setHost(value("MOYI_SMTP_HOST"));
|
||||
mail.setPort(env.getProperty("MOYI_SMTP_PORT",Integer.class,465));
|
||||
mail.setUsername(value("MOYI_SMTP_USERNAME"));
|
||||
mail.setPassword(env.getProperty("MOYI_SMTP_PASSWORD",""));
|
||||
mail.setDefaultEncoding("UTF-8");
|
||||
var properties=mail.getJavaMailProperties();
|
||||
properties.setProperty("mail.smtp.auth",String.valueOf(!value("MOYI_SMTP_USERNAME").isEmpty()));
|
||||
properties.setProperty("mail.smtp.ssl.enable",env.getProperty("MOYI_SMTP_SSL","true"));
|
||||
properties.setProperty("mail.smtp.starttls.enable",env.getProperty("MOYI_SMTP_STARTTLS","false"));
|
||||
properties.setProperty("mail.smtp.starttls.required",env.getProperty("MOYI_SMTP_STARTTLS","false"));
|
||||
properties.setProperty("mail.smtp.ssl.checkserveridentity","true");
|
||||
properties.setProperty("mail.smtp.connectiontimeout","5000");
|
||||
properties.setProperty("mail.smtp.timeout","10000");
|
||||
properties.setProperty("mail.smtp.writetimeout","10000");
|
||||
SimpleMailMessage message=new SimpleMailMessage();
|
||||
message.setFrom(value("MOYI_SMTP_FROM"));
|
||||
message.setTo(account);
|
||||
message.setSubject("MOYI 注册验证码");
|
||||
message.setText("您的注册验证码为:"+code+",5 分钟内有效。请勿向他人泄露。若非本人操作,请忽略此邮件。");
|
||||
mail.send(message);
|
||||
} else {
|
||||
Config config=new Config().setAccessKeyId(value("MOYI_SMS_ACCESS_KEY_ID")).setAccessKeySecret(value("MOYI_SMS_ACCESS_KEY_SECRET")).setEndpoint("dysmsapi.aliyuncs.com").setProtocol("https");
|
||||
var client=new com.aliyun.dysmsapi20170525.Client(config);
|
||||
var request=new SendSmsRequest().setPhoneNumbers(account.startsWith("+86")?account.substring(3):account)
|
||||
.setSignName(value("MOYI_SMS_SIGN_NAME")).setTemplateCode(value("MOYI_SMS_TEMPLATE_CODE")).setTemplateParam("{\"code\":\""+code+"\"}");
|
||||
var response=client.sendSmsWithOptions(request,new RuntimeOptions().setAutoretry(false).setConnectTimeout(5000).setReadTimeout(10000));
|
||||
if(response.getBody()==null || !"OK".equals(response.getBody().getCode())) throw new IllegalStateException("SMS rejected");
|
||||
}
|
||||
} catch(Exception exception) {
|
||||
// SDK exceptions may contain credentials or recipients. Never expose them to logs or clients.
|
||||
throw new ApiException("VERIFICATION_SEND_FAILED","验证码发送失败,请稍后重试或联系管理员检查发送服务",502);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.moyi.controlplane.auth;
|
||||
|
||||
public interface VerificationSender {
|
||||
boolean available(String channel);
|
||||
void send(String channel, String account, String code);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.moyi.controlplane.auth;
|
||||
|
||||
import com.moyi.controlplane.common.ApiException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
public class VerificationService {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final VerificationSender sender;
|
||||
private final String pepper;
|
||||
private final SecureRandom random=new SecureRandom();
|
||||
public VerificationService(JdbcTemplate jdbc,VerificationSender sender,@Value("${moyi.auth.password-pepper}") String pepper) {
|
||||
this.jdbc=jdbc; this.sender=sender; this.pepper=pepper;
|
||||
}
|
||||
public Map<String,Boolean> capabilities() { return Map.of("email",sender.available("email"),"phone",sender.available("phone")); }
|
||||
public String normalize(String raw) {
|
||||
String account=raw==null?"":raw.trim().toLowerCase(Locale.ROOT);
|
||||
if(!account.contains("@")) account=account.replaceAll("[\\s-]","");
|
||||
if(account.length()>254 || (!account.matches("^[^\\s@,;<>]+@[^\\s@,;<>]+\\.[^\\s@,;<>]+$") && !account.matches("^(?:\\+86)?1[3-9][0-9]{9}$"))) throw new ApiException("INVALID_ACCOUNT","请输入有效邮箱或中国大陆手机号");
|
||||
return account;
|
||||
}
|
||||
private String digest(String account,String code) { return AuthService.hashSecret(pepper+":registration:"+account+":"+code); }
|
||||
|
||||
@Transactional(noRollbackFor=ApiException.class)
|
||||
public Map<String,Object> send(String raw,String invitation,String ip) {
|
||||
String account=normalize(raw), channel=account.contains("@")?"email":"phone";
|
||||
if(!sender.available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
|
||||
Integer invites=jdbc.queryForObject("SELECT count(*) FROM invitation_codes WHERE code_hash=? AND disabled_at IS NULL AND used_count<max_uses AND (expires_at IS NULL OR expires_at>now())",Integer.class,AuthService.hashSecret(invitation==null?"":invitation.trim()));
|
||||
if(invites==null || invites==0) throw new ApiException("INVITATION_INVALID","请先填写有效邀请码",403);
|
||||
String source=ip==null?"unknown":ip;
|
||||
// One global lock bounds aggregate sending and serializes account/IP limits across replicas.
|
||||
jdbc.queryForList("SELECT pg_advisory_xact_lock(734092615)");
|
||||
Integer limited=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>now()-interval '60 seconds'",Integer.class,account);
|
||||
Integer daily=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>now()-interval '24 hours'",Integer.class,account);
|
||||
Integer hourly=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE ip_address=? AND created_at>now()-interval '1 hour'",Integer.class,source);
|
||||
Integer total=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE created_at>now()-interval '24 hours'",Integer.class);
|
||||
if(limited>0 || daily>=10 || hourly>=30 || total>=1000) throw new ApiException("VERIFICATION_RATE_LIMIT","发送过于频繁,请稍后重试",429);
|
||||
String code=String.format(Locale.ROOT,"%06d",random.nextInt(1000000));
|
||||
jdbc.update("INSERT INTO verification_send_events(id,account,ip_address) VALUES (?,?,?)",UUID.randomUUID(),account,source);
|
||||
jdbc.update("INSERT INTO registration_codes(account,code_hash,expires_at) VALUES (?,?,now()+interval '5 minutes') ON CONFLICT(account) DO UPDATE SET code_hash=excluded.code_hash, expires_at=excluded.expires_at, attempts=0, consumed=false, created_at=now()",account,digest(account,code));
|
||||
try { sender.send(channel,account,code); }
|
||||
catch(ApiException exception) { jdbc.update("UPDATE registration_codes SET consumed=true WHERE account=?",account); throw exception; }
|
||||
jdbc.update("DELETE FROM verification_send_events WHERE created_at<now()-interval '2 days'");
|
||||
return Map.of("sent",true,"retryAfterSeconds",60,"expiresInSeconds",300);
|
||||
}
|
||||
|
||||
@Transactional(noRollbackFor=ApiException.class)
|
||||
public void consume(String raw,String code) {
|
||||
String account=normalize(raw);
|
||||
var rows=jdbc.queryForList("SELECT * FROM registration_codes WHERE account=? FOR UPDATE",account);
|
||||
if(rows.isEmpty()) throw new ApiException("VERIFICATION_INVALID","请先获取验证码");
|
||||
var row=rows.getFirst();
|
||||
java.time.Instant expiry=((java.sql.Timestamp)row.get("expires_at")).toInstant();
|
||||
if(Boolean.TRUE.equals(row.get("consumed")) || expiry.isBefore(java.time.Instant.now()) || ((Number)row.get("attempts")).intValue()>=5) throw new ApiException("VERIFICATION_EXPIRED","验证码已失效,请重新获取");
|
||||
jdbc.update("UPDATE registration_codes SET attempts=attempts+1 WHERE account=?",account);
|
||||
if(code==null || !code.matches("[0-9]{6}") || !MessageDigest.isEqual(String.valueOf(row.get("code_hash")).getBytes(StandardCharsets.UTF_8),digest(account,code).getBytes(StandardCharsets.UTF_8))) throw new ApiException("VERIFICATION_INVALID","验证码错误");
|
||||
jdbc.update("UPDATE registration_codes SET consumed=true WHERE account=?",account);
|
||||
}
|
||||
}
|
||||
+23
-2
@@ -8,6 +8,7 @@ import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
@@ -28,7 +29,7 @@ public class CatalogController {
|
||||
@GetMapping("/models")
|
||||
public Map<String, Object> models(jakarta.servlet.http.HttpServletRequest request) {
|
||||
authService.requireUser(AuthController.sessionToken(request));
|
||||
return Map.of("providers", catalogService.listProviders(false), "models", catalogService.listModels(false));
|
||||
return Map.of("providers", catalogService.listProviders(false), "models", catalogService.listModels(false), "logicalModels", catalogService.listDefinitions(false));
|
||||
}
|
||||
|
||||
@GetMapping("/overview")
|
||||
@@ -103,7 +104,27 @@ public class CatalogController {
|
||||
@GetMapping("/admin/models")
|
||||
public Map<String, Object> adminModels(jakarta.servlet.http.HttpServletRequest request) {
|
||||
authService.requireAdmin(AuthController.sessionToken(request));
|
||||
return Map.of("models", catalogService.listModels(true));
|
||||
return Map.of("models", catalogService.listModels(true), "logicalModels", catalogService.listDefinitions(true));
|
||||
}
|
||||
|
||||
@PatchMapping("/admin/providers/{id}")
|
||||
public Map<String,Object> updateProvider(@PathVariable String id, @RequestBody Map<String,Object> input, jakarta.servlet.http.HttpServletRequest request) {
|
||||
return Map.of("provider",catalogService.updateProvider(id,input,AuthController.sessionToken(request),authService));
|
||||
}
|
||||
|
||||
@PatchMapping("/admin/models/{id}")
|
||||
public Map<String,Object> updateGroup(@PathVariable String id, @RequestBody Map<String,Object> input, jakarta.servlet.http.HttpServletRequest request) {
|
||||
return Map.of("model",catalogService.updateModel(id,input,AuthController.sessionToken(request),authService));
|
||||
}
|
||||
|
||||
@PostMapping("/admin/model-definitions")
|
||||
public ResponseEntity<Map<String,Object>> createDefinition(@RequestBody Map<String,Object> input, jakarta.servlet.http.HttpServletRequest request) {
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(Map.of("model",catalogService.saveDefinition(null,input,AuthController.sessionToken(request),authService)));
|
||||
}
|
||||
|
||||
@PatchMapping("/admin/model-definitions/{id}")
|
||||
public Map<String,Object> updateDefinition(@PathVariable String id, @RequestBody Map<String,Object> input, jakarta.servlet.http.HttpServletRequest request) {
|
||||
return Map.of("model",catalogService.saveDefinition(id,input,AuthController.sessionToken(request),authService));
|
||||
}
|
||||
|
||||
@PostMapping("/admin/models")
|
||||
|
||||
+139
-15
@@ -48,8 +48,56 @@ public class CatalogService {
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> listModels(boolean includeDisabled) {
|
||||
String statusClause = includeDisabled ? "" : " WHERE status = 'active'";
|
||||
return jdbc.query("SELECT * FROM model_catalog" + statusClause + " ORDER BY public_name", this::mapModel);
|
||||
String statusClause = includeDisabled ? "" : " WHERE m.status = 'active' AND p.status = 'active' AND d.status = 'active'";
|
||||
return jdbc.query("SELECT m.* FROM model_catalog m JOIN model_providers p ON p.id=m.provider_id JOIN model_definitions d ON d.id=m.logical_model_id" + statusClause + " ORDER BY m.public_name, m.source_label", this::mapModel);
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> listDefinitions(boolean includeDisabled) {
|
||||
return jdbc.query("SELECT * FROM model_definitions" + (includeDisabled ? "" : " WHERE status='active'") + " ORDER BY public_name", (rs, n) -> {
|
||||
Map<String, Object> item = new LinkedHashMap<>();
|
||||
item.put("id", rs.getString("id"));
|
||||
item.put("publicName", rs.getString("public_name"));
|
||||
item.put("modelKey", rs.getString("model_key"));
|
||||
item.put("type", rs.getString("model_type"));
|
||||
item.put("mode", rs.getString("call_mode"));
|
||||
item.put("description", rs.getString("description"));
|
||||
item.put("inputTypes", readList(rs.getString("input_types")));
|
||||
item.put("outputTypes", readList(rs.getString("output_types")));
|
||||
item.put("status", rs.getString("status"));
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Map<String, Object> saveDefinition(String id, Map<String, Object> input, String token, AuthService auth) {
|
||||
UserView admin = auth.requireAdmin(token);
|
||||
boolean creating = id == null;
|
||||
Map<String, Object> value = creating ? new LinkedHashMap<>() : new LinkedHashMap<>(definition(id));
|
||||
value.putAll(input);
|
||||
String name = required(value, "publicName");
|
||||
String type = required(value, "type");
|
||||
String mode = required(value, "mode");
|
||||
String status = status(value);
|
||||
if (name.length() > 160 || !MODEL_TYPES.contains(type) || !CALL_MODES.contains(mode)) throw new ApiException("INVALID_MODEL", "模型名称、类型或调用模式无效");
|
||||
if (creating) {
|
||||
id = UUID.randomUUID().toString();
|
||||
jdbc.update("INSERT INTO model_definitions (id, model_key, public_name, model_type, call_mode, description, input_types, output_types, status) VALUES (?, ?, ?, ?, ?, ?, CAST(? AS jsonb), CAST(? AS jsonb), ?)", id, optional(value, "modelKey", null), name, type, mode, optional(value, "description", ""), jsonArray(value.get("inputTypes")), jsonArray(value.get("outputTypes")), status);
|
||||
} else {
|
||||
jdbc.update("UPDATE model_definitions SET model_key=?, public_name=?, model_type=?, call_mode=?, description=?, input_types=CAST(? AS jsonb), output_types=CAST(? AS jsonb), status=?, updated_at=now() WHERE id=?", optional(value,"modelKey",null), name, type, mode, optional(value,"description",""), jsonArray(value.get("inputTypes")), jsonArray(value.get("outputTypes")), status, id);
|
||||
jdbc.update("UPDATE model_catalog SET model_key=?, public_name=?, model_type=?, call_mode=?, description=?, input_types=CAST(? AS jsonb), output_types=CAST(? AS jsonb), updated_at=now() WHERE logical_model_id=?", optional(value,"modelKey",null), name, type, mode, optional(value,"description",""), jsonArray(value.get("inputTypes")), jsonArray(value.get("outputTypes")), id);
|
||||
}
|
||||
auth.audit(creating ? "model_definition.created" : "model_definition.updated", admin.id(), new AuthService.RequestMeta(null,null), Map.of("modelId",id));
|
||||
return definition(id);
|
||||
}
|
||||
|
||||
private Map<String, Object> definition(String id) {
|
||||
return listDefinitions(true).stream().filter(item -> id.equals(item.get("id"))).findFirst().orElseThrow(() -> new ApiException("MODEL_NOT_FOUND", "模型不存在", 404));
|
||||
}
|
||||
|
||||
private String status(Map<String, Object> input) {
|
||||
String value = optional(input,"status","active");
|
||||
if (!List.of("active","disabled").contains(value)) throw new ApiException("INVALID_STATUS", "状态无效");
|
||||
return value;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@@ -59,54 +107,123 @@ public class CatalogService {
|
||||
String name = required(input, "name");
|
||||
String protocol = optional(input, "protocol", "http");
|
||||
String sourceType = optional(input, "sourceType", "custom");
|
||||
if (!code.matches("^[a-z0-9][a-z0-9._-]{1,63}$") || !PROTOCOLS.contains(protocol) || !SOURCE_TYPES.contains(sourceType)) {
|
||||
if (!code.matches("^[a-z0-9][a-z0-9._-]{1,63}$") || name.length() > 120 || !PROTOCOLS.contains(protocol) || !SOURCE_TYPES.contains(sourceType)) {
|
||||
throw new ApiException("INVALID_PROVIDER", "供应商标识、协议或来源类型无效");
|
||||
}
|
||||
String id = UUID.randomUUID().toString();
|
||||
String baseUrl = optional(input, "baseUrl", null);
|
||||
validateBaseUrl(baseUrl);
|
||||
String description = optional(input, "description", "");
|
||||
String credentialType = optional(input, "credentialType", null);
|
||||
String secret = optional(input, "credentialSecret", null);
|
||||
String credentialType = optional(input, "credentialType", "none");
|
||||
if (!List.of("none", "api-key", "bearer", "access-token").contains(credentialType)) throw new ApiException("INVALID_CREDENTIAL_TYPE", "凭据类型无效");
|
||||
String secret = "none".equals(credentialType) ? null : optional(input, "credentialSecret", null);
|
||||
String masked = secret == null ? null : mask(secret);
|
||||
jdbc.update(
|
||||
"INSERT INTO model_providers (id, code, name, protocol, source_type, base_url, description, credential_type, credential_ciphertext, credential_masked, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')",
|
||||
id, code, name, protocol, sourceType, baseUrl, description, credentialType, secret == null ? null : secretCipher.encrypt(secret), masked
|
||||
"INSERT INTO model_providers (id, code, name, protocol, source_type, base_url, description, credential_type, credential_ciphertext, credential_masked, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
id, code, name, protocol, sourceType, baseUrl, description, credentialType, secret == null ? null : secretCipher.encrypt(secret), masked, status(input)
|
||||
);
|
||||
auth.audit("provider.created", admin.id(), new AuthService.RequestMeta(null, null), Map.of("providerId", id));
|
||||
return findProvider(id);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Map<String, Object> updateProvider(String id, Map<String, Object> input, String token, AuthService auth) {
|
||||
UserView admin = auth.requireAdmin(token);
|
||||
Map<String, Object> previous = findProvider(id);
|
||||
if (previous == null) throw new ApiException("PROVIDER_NOT_FOUND", "渠道不存在", 404);
|
||||
Map<String, Object> value = new LinkedHashMap<>(previous);
|
||||
value.putAll(input);
|
||||
String code=required(value,"code").toLowerCase(), name=required(value,"name"), protocol=required(value,"protocol"), sourceType=required(value,"sourceType");
|
||||
if (!code.matches("^[a-z0-9][a-z0-9._-]{1,63}$") || name.length()>120 || !PROTOCOLS.contains(protocol) || !SOURCE_TYPES.contains(sourceType)) throw new ApiException("INVALID_PROVIDER", "渠道标识、名称、协议或类型无效");
|
||||
String baseUrl=optional(value,"baseUrl",null);
|
||||
validateBaseUrl(baseUrl);
|
||||
String credentialType=optional(value,"credentialType","none");
|
||||
if (!List.of("none","api-key","bearer","access-token").contains(credentialType)) throw new ApiException("INVALID_CREDENTIAL_TYPE","凭据类型无效");
|
||||
jdbc.update("UPDATE model_providers SET code=?, name=?, protocol=?, source_type=?, base_url=?, description=?, credential_type=?, status=?, updated_at=now() WHERE id=?", code,name,protocol,sourceType,baseUrl,optional(value,"description",""),credentialType,status(value),id);
|
||||
String secret=optional(input,"credentialSecret","");
|
||||
if ("none".equals(credentialType)) jdbc.update("UPDATE model_providers SET credential_ciphertext=NULL, credential_masked=NULL WHERE id=?",id);
|
||||
else if (!secret.isBlank()) jdbc.update("UPDATE model_providers SET credential_ciphertext=?, credential_masked=? WHERE id=?",secretCipher.encrypt(secret),mask(secret),id);
|
||||
auth.audit("provider.updated",admin.id(),new AuthService.RequestMeta(null,null),Map.of("providerId",id));
|
||||
return findProvider(id);
|
||||
}
|
||||
|
||||
private void validateBaseUrl(String value) {
|
||||
if (value == null || value.isBlank()) return;
|
||||
try {
|
||||
java.net.URI uri=java.net.URI.create(value);
|
||||
if (!List.of("https","http").contains(uri.getScheme()) || uri.getHost()==null || uri.getUserInfo()!=null || uri.getQuery()!=null || uri.getFragment()!=null) throw new IllegalArgumentException();
|
||||
} catch (IllegalArgumentException exception) { throw new ApiException("INVALID_BASE_URL","Base URL 必须是 HTTP(S) 地址,不能包含密码、查询参数或片段"); }
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Map<String, Object> createModel(Map<String, Object> input, String token, AuthService auth) {
|
||||
UserView admin = auth.requireAdmin(token);
|
||||
input = new LinkedHashMap<>(input);
|
||||
String logicalId = optional(input, "logicalModelId", null);
|
||||
if (logicalId == null) logicalId = String.valueOf(saveDefinition(null, input, token, auth).get("id"));
|
||||
Map<String, Object> definition = definition(logicalId);
|
||||
for (String field : List.of("publicName","modelKey","type","mode","description","inputTypes","outputTypes")) input.put(field,definition.get(field));
|
||||
String providerId = required(input, "providerId");
|
||||
if (findProvider(providerId) == null) throw new ApiException("PROVIDER_NOT_FOUND", "供应商不存在", 404);
|
||||
String publicName = required(input, "publicName");
|
||||
String upstreamModel = required(input, "upstreamModel");
|
||||
if (upstreamModel.length() > 160) throw new ApiException("INVALID_MODEL", "上游模型标识不能超过 160 字符");
|
||||
String type = required(input, "type");
|
||||
String mode = required(input, "mode");
|
||||
if (!MODEL_TYPES.contains(type) || !CALL_MODES.contains(mode)) throw new ApiException("INVALID_MODEL", "模型类型或调用模式无效");
|
||||
String id = UUID.randomUUID().toString();
|
||||
String modelKey = optional(input, "modelKey", null);
|
||||
String sourceLabel = optional(input, "sourceLabel", null);
|
||||
String sourceLabel = optional(input, "sourceLabel", "默认分组");
|
||||
if (sourceLabel.isBlank() || sourceLabel.length()>160) throw new ApiException("INVALID_GROUP_NAME","请填写分组名称(最多 160 字符)");
|
||||
String description = optional(input, "description", "");
|
||||
String inputTypes = jsonArray(input.get("inputTypes"));
|
||||
String outputTypes = jsonArray(input.get("outputTypes"));
|
||||
String capabilities = jsonObject(input.get("capabilities"));
|
||||
String pricing = jsonObjectOrNull(input.get("pricing"));
|
||||
validatePricing(input.get("pricing"));
|
||||
Integer priority = integerOrNull(input.get("priority"));
|
||||
Integer maxConcurrency = integerOrNull(input.get("maxConcurrency"));
|
||||
if (priority != null && priority < 0) throw new ApiException("INVALID_MODEL_PRIORITY", "模型路由优先级必须大于等于 0");
|
||||
if (maxConcurrency != null && maxConcurrency < 0) throw new ApiException("INVALID_MODEL_CONCURRENCY", "模型并发上限必须大于等于 0");
|
||||
if (maxConcurrency != null && maxConcurrency < 1) throw new ApiException("INVALID_MODEL_CONCURRENCY", "模型并发上限必须大于等于 1");
|
||||
jdbc.update(
|
||||
"INSERT INTO model_catalog (id, provider_id, model_key, source_label, public_name, upstream_model, model_type, call_mode, description, input_types, output_types, capabilities, pricing, priority, max_concurrency, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS jsonb), CAST(? AS jsonb), CAST(? AS jsonb), CAST(? AS jsonb), ?, ?, 'active')",
|
||||
"INSERT INTO model_catalog (id, provider_id, model_key, source_label, public_name, upstream_model, model_type, call_mode, description, input_types, output_types, capabilities, pricing, priority, max_concurrency, logical_model_id, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS jsonb), CAST(? AS jsonb), CAST(? AS jsonb), CAST(? AS jsonb), ?, ?, ?, ?)",
|
||||
id, providerId, modelKey, sourceLabel, publicName, upstreamModel, type, mode, description,
|
||||
inputTypes, outputTypes, capabilities, pricing, priority, maxConcurrency
|
||||
inputTypes, outputTypes, capabilities, pricing, priority, maxConcurrency, logicalId, status(input)
|
||||
);
|
||||
auth.audit("model.created", admin.id(), new AuthService.RequestMeta(null, null), Map.of("modelId", id));
|
||||
return findModel(id);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Map<String, Object> updateModel(String id, Map<String, Object> input, String token, AuthService auth) {
|
||||
UserView admin=auth.requireAdmin(token);
|
||||
Map<String,Object> old=findModel(id);
|
||||
if (old==null) throw new ApiException("MODEL_NOT_FOUND","分组不存在",404);
|
||||
Map<String,Object> value=new LinkedHashMap<>(old);
|
||||
value.putAll(input);
|
||||
String logicalId=required(value,"logicalModelId");
|
||||
Map<String,Object> definition=definition(logicalId);
|
||||
String providerId=required(value,"providerId"), groupName=required(value,"sourceLabel"), upstream=required(value,"upstreamModel");
|
||||
if (findProvider(providerId)==null) throw new ApiException("PROVIDER_NOT_FOUND","渠道不存在",404);
|
||||
if(groupName.length()>160 || upstream.length()>160) throw new ApiException("INVALID_MODEL","分组名称或上游标识过长");
|
||||
Integer priority=integerOrNull(value.get("priority")), concurrency=integerOrNull(value.get("maxConcurrency"));
|
||||
if ((priority!=null && priority<0) || (concurrency!=null && concurrency<1)) throw new ApiException("INVALID_MODEL_LIMIT","优先级不能小于 0,并发上限至少为 1");
|
||||
validatePricing(value.get("pricing"));
|
||||
jdbc.update("UPDATE model_catalog SET logical_model_id=?, provider_id=?, source_label=?, upstream_model=?, public_name=?, model_key=?, model_type=?, call_mode=?, description=?, input_types=CAST(? AS jsonb), output_types=CAST(? AS jsonb), pricing=CAST(? AS jsonb), priority=?, max_concurrency=?, status=?, updated_at=now() WHERE id=?",logicalId,providerId,groupName,upstream,definition.get("publicName"),definition.get("modelKey"),definition.get("type"),definition.get("mode"),definition.get("description"),jsonArray(definition.get("inputTypes")),jsonArray(definition.get("outputTypes")),jsonObjectOrNull(value.get("pricing")),priority,concurrency,status(value),id);
|
||||
auth.audit("model_group.updated",admin.id(),new AuthService.RequestMeta(null,null),Map.of("groupId",id,"modelId",logicalId,"providerId",providerId));
|
||||
return findModel(id);
|
||||
}
|
||||
|
||||
private void validatePricing(Object input) {
|
||||
if (!(input instanceof Map<?,?> prices)) return;
|
||||
for(String field: List.of("input","output")) {
|
||||
Object amount=prices.get(field);
|
||||
if(amount==null) continue;
|
||||
try { if(new java.math.BigDecimal(String.valueOf(amount)).signum()<0) throw new NumberFormatException(); }
|
||||
catch(NumberFormatException e) { throw new ApiException("INVALID_PRICE","价格必须是非负数"); }
|
||||
}
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> listProjects(String token, AuthService auth) {
|
||||
UserView user = auth.requireUser(token);
|
||||
return jdbc.query("SELECT * FROM model_projects WHERE owner_user_id = ? AND status = 'active' ORDER BY created_at DESC", this::mapProject, user.id());
|
||||
@@ -158,8 +275,11 @@ public class CatalogService {
|
||||
@Transactional
|
||||
public Map<String, Object> updateKeyModels(String token, String keyId, List<String> modelIds, AuthService auth) {
|
||||
UserView user = auth.requireUser(token);
|
||||
List<String> uniqueIds = modelIds == null ? List.of() : modelIds.stream().map(String::trim).filter(value -> !value.isBlank()).distinct().toList();
|
||||
for (String modelId : uniqueIds) if (findActiveModel(modelId) == null) throw new ApiException("MODEL_NOT_FOUND", "模型不存在或已下线", 404);
|
||||
var existing = jdbc.query("SELECT * FROM platform_api_keys WHERE id=? AND user_id=? AND status='active' FOR UPDATE", this::mapApiKey, UUID.fromString(keyId), user.id());
|
||||
if (existing.isEmpty()) throw new ApiException("KEY_NOT_FOUND", "Key 不存在、已停用或无权修改", 404);
|
||||
List<?> priorIds = (List<?>) existing.getFirst().get("modelIds");
|
||||
List<String> uniqueIds = modelIds == null ? List.of() : modelIds.stream().filter(java.util.Objects::nonNull).map(String::trim).filter(value -> !value.isBlank()).distinct().toList();
|
||||
for (String modelId : uniqueIds) if (!priorIds.contains(modelId) && findActiveModel(modelId) == null) throw new ApiException("MODEL_NOT_FOUND", "分组不存在或已下线", 404);
|
||||
int changed = jdbc.update("UPDATE platform_api_keys SET model_ids = CAST(? AS jsonb) WHERE id = ? AND user_id = ? AND status = 'active'", writeJson(uniqueIds), UUID.fromString(keyId), user.id());
|
||||
if (changed == 0) throw new ApiException("KEY_NOT_FOUND", "Key 不存在、已停用或无权修改", 404);
|
||||
return Map.of("apiKey", findKey(keyId));
|
||||
@@ -185,13 +305,16 @@ public class CatalogService {
|
||||
result.put("tasks", Map.of("queued", 0, "running", 0, "succeeded", 0, "failed", 0));
|
||||
result.put("series", List.of());
|
||||
result.put("ledger", List.of());
|
||||
List<java.math.BigDecimal> balances=jdbc.queryForList("SELECT balance FROM user_wallets WHERE user_id=?",java.math.BigDecimal.class,user.id());
|
||||
result.put("availableCredit",balances.isEmpty()?java.math.BigDecimal.ZERO:balances.getFirst());
|
||||
result.put("ledger",jdbc.query("SELECT id, reason, amount, created_at FROM wallet_entries WHERE user_id=? ORDER BY created_at DESC LIMIT 100", (rs,n)->Map.of("id",rs.getString("id"),"title",rs.getString("reason"),"amount",rs.getBigDecimal("amount"),"createdAt",rs.getObject("created_at",OffsetDateTime.class)),user.id()));
|
||||
return result;
|
||||
}
|
||||
|
||||
public Map<String, Object> authenticateKey(String plaintext) {
|
||||
if (plaintext == null || plaintext.isBlank()) return null;
|
||||
try {
|
||||
return jdbc.queryForObject("SELECT * FROM platform_api_keys WHERE key_hash = ? AND status = 'active'", this::mapApiKey, sha256(plaintext.trim()));
|
||||
return jdbc.queryForObject("SELECT k.* FROM platform_api_keys k JOIN users u ON u.id=k.user_id WHERE k.key_hash = ? AND k.status = 'active' AND u.status='active'", this::mapApiKey, sha256(plaintext.trim()));
|
||||
} catch (EmptyResultDataAccessException exception) {
|
||||
return null;
|
||||
}
|
||||
@@ -237,7 +360,7 @@ public class CatalogService {
|
||||
}
|
||||
|
||||
private Map<String, Object> findActiveModel(String id) {
|
||||
try { return jdbc.queryForObject("SELECT * FROM model_catalog WHERE id = ? AND status = 'active'", this::mapModel, id); }
|
||||
try { return jdbc.queryForObject("SELECT m.* FROM model_catalog m JOIN model_providers p ON p.id=m.provider_id JOIN model_definitions d ON d.id=m.logical_model_id WHERE m.id = ? AND m.status = 'active' AND p.status='active' AND d.status='active'", this::mapModel, id); }
|
||||
catch (EmptyResultDataAccessException exception) { return null; }
|
||||
}
|
||||
|
||||
@@ -274,6 +397,7 @@ public class CatalogService {
|
||||
private Map<String, Object> mapModel(ResultSet resultSet, int rowNumber) throws SQLException {
|
||||
Map<String, Object> model = new LinkedHashMap<>();
|
||||
model.put("id", resultSet.getString("id"));
|
||||
model.put("logicalModelId", resultSet.getString("logical_model_id"));
|
||||
model.put("providerId", resultSet.getString("provider_id"));
|
||||
putIfNotNull(model, "modelKey", resultSet.getString("model_key"));
|
||||
putIfNotNull(model, "sourceLabel", resultSet.getString("source_label"));
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.moyi.controlplane.wallet;
|
||||
|
||||
import com.moyi.controlplane.auth.AuthController;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/admin")
|
||||
public class WalletController {
|
||||
private final WalletService wallet;
|
||||
public WalletController(WalletService wallet) { this.wallet=wallet; }
|
||||
public record GrantRequest(UUID requestId, String amount, String reason) {}
|
||||
@GetMapping("/wallets")
|
||||
public Map<String,Object> balances(HttpServletRequest request) { return Map.of("wallets",wallet.balances(AuthController.sessionToken(request))); }
|
||||
@GetMapping("/users/{id}/wallet")
|
||||
public Map<String,Object> entries(@PathVariable UUID id,HttpServletRequest request) { return Map.of("entries",wallet.entries(AuthController.sessionToken(request),id)); }
|
||||
@PostMapping("/users/{id}/wallet/grants")
|
||||
public Map<String,Object> grant(@PathVariable UUID id,@RequestBody GrantRequest input,HttpServletRequest request) {
|
||||
return wallet.grant(AuthController.sessionToken(request),id,input.requestId(),input.amount(),input.reason(),AuthController.meta(request));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.moyi.controlplane.wallet;
|
||||
|
||||
import com.moyi.controlplane.auth.AuthService;
|
||||
import com.moyi.controlplane.common.ApiException;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
public class WalletService {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final AuthService auth;
|
||||
|
||||
public WalletService(JdbcTemplate jdbc, AuthService auth) { this.jdbc=jdbc; this.auth=auth; }
|
||||
|
||||
public List<Map<String,Object>> balances(String token) {
|
||||
auth.requireAdmin(token);
|
||||
return jdbc.queryForList("SELECT u.id AS \"userId\", COALESCE(w.balance,0) AS balance FROM users u LEFT JOIN user_wallets w ON w.user_id=u.id");
|
||||
}
|
||||
|
||||
public List<Map<String,Object>> entries(String token, UUID userId) {
|
||||
auth.requireAdmin(token);
|
||||
return jdbc.queryForList("SELECT e.id, e.amount, e.balance_after AS \"balanceAfter\", e.currency, e.reason, e.created_at AS \"createdAt\", u.display_name AS actor FROM wallet_entries e JOIN users u ON u.id=e.actor_user_id WHERE e.user_id=? ORDER BY e.created_at DESC LIMIT 100",userId);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Map<String,Object> grant(String token, UUID userId, UUID requestId, String amountInput, String reasonInput, AuthService.RequestMeta meta) {
|
||||
var actor=auth.requireAdmin(token);
|
||||
if(requestId==null) throw new ApiException("INVALID_REQUEST_ID","请提供发放请求编号");
|
||||
BigDecimal amount;
|
||||
try {
|
||||
amount=new BigDecimal(amountInput).setScale(2,RoundingMode.UNNECESSARY);
|
||||
if(amount.signum()<=0 || amount.compareTo(new BigDecimal("1000000"))>0) throw new NumberFormatException();
|
||||
} catch(Exception exception) { throw new ApiException("INVALID_AMOUNT","金额需大于 0,最多两位小数,单次不超过 100 万元"); }
|
||||
String reason=reasonInput==null?"":reasonInput.trim();
|
||||
if(reason.isBlank() || reason.length()>500) throw new ApiException("INVALID_REASON","请填写发放原因(最多 500 字符)");
|
||||
if(jdbc.queryForObject("SELECT count(*) FROM users WHERE id=? AND status='active'",Integer.class,userId)==0) throw new ApiException("USER_NOT_FOUND","用户不存在或已停用",404);
|
||||
// Lock the idempotency key before the wallet so concurrent retries cannot grant twice.
|
||||
jdbc.queryForList("SELECT pg_advisory_xact_lock(hashtextextended(?, 0))",requestId.toString());
|
||||
List<Map<String,Object>> existing=jdbc.queryForList("SELECT * FROM wallet_entries WHERE request_id=?",requestId);
|
||||
if(!existing.isEmpty()) {
|
||||
var entry=existing.getFirst();
|
||||
if(!userId.equals(entry.get("user_id")) || !actor.id().equals(entry.get("actor_user_id")) || amount.compareTo((BigDecimal)entry.get("amount"))!=0 || !reason.equals(entry.get("reason"))) throw new ApiException("REQUEST_CONFLICT","请求编号已被另一笔发放使用",409);
|
||||
return Map.of("id",entry.get("id"),"balance",entry.get("balance_after"),"currency","CNY","replayed",true);
|
||||
}
|
||||
jdbc.update("INSERT INTO user_wallets(user_id) VALUES (?) ON CONFLICT DO NOTHING",userId);
|
||||
BigDecimal balance=jdbc.queryForObject("SELECT balance FROM user_wallets WHERE user_id=? FOR UPDATE",BigDecimal.class,userId);
|
||||
BigDecimal next=balance.add(amount);
|
||||
UUID id=UUID.randomUUID();
|
||||
jdbc.update("UPDATE user_wallets SET balance=?, updated_at=now() WHERE user_id=?",next,userId);
|
||||
jdbc.update("INSERT INTO wallet_entries(id,user_id,actor_user_id,request_id,amount,balance_after,reason) VALUES (?,?,?,?,?,?,?)",id,userId,actor.id(),requestId,amount,next,reason);
|
||||
auth.audit("wallet.credit_granted",actor.id(),meta,Map.of("userId",userId,"entryId",id,"amount",amount,"currency","CNY","reason",reason));
|
||||
return Map.of("id",id,"balance",next,"currency","CNY","replayed",false);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
CREATE TABLE model_definitions (
|
||||
id varchar(64) PRIMARY KEY,
|
||||
model_key varchar(160),
|
||||
public_name varchar(160) NOT NULL,
|
||||
model_type varchar(24) NOT NULL,
|
||||
call_mode varchar(16) NOT NULL,
|
||||
description text NOT NULL DEFAULT '',
|
||||
input_types jsonb NOT NULL DEFAULT '[]',
|
||||
output_types jsonb NOT NULL DEFAULT '[]',
|
||||
status varchar(16) NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'disabled')),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- Keep existing route IDs and key grants intact. Do not guess which legacy names are identical models.
|
||||
INSERT INTO model_definitions (id, model_key, public_name, model_type, call_mode, description, input_types, output_types, status)
|
||||
SELECT id, model_key, public_name, model_type, call_mode, description, input_types, output_types, status FROM model_catalog;
|
||||
ALTER TABLE model_catalog ADD COLUMN logical_model_id varchar(64) REFERENCES model_definitions(id);
|
||||
UPDATE model_catalog SET logical_model_id = id;
|
||||
ALTER TABLE model_catalog ALTER COLUMN logical_model_id SET NOT NULL;
|
||||
UPDATE model_catalog SET source_label = '默认分组' WHERE source_label IS NULL OR trim(source_label) = '';
|
||||
CREATE INDEX model_catalog_logical_idx ON model_catalog(logical_model_id);
|
||||
CREATE UNIQUE INDEX model_catalog_group_name_idx ON model_catalog(logical_model_id, source_label);
|
||||
|
||||
CREATE TABLE user_wallets (
|
||||
user_id uuid PRIMARY KEY REFERENCES users(id),
|
||||
balance numeric(20,8) NOT NULL DEFAULT 0 CHECK (balance >= 0),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE wallet_entries (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
actor_user_id uuid NOT NULL REFERENCES users(id),
|
||||
request_id uuid NOT NULL UNIQUE,
|
||||
amount numeric(20,8) NOT NULL CHECK (amount > 0),
|
||||
balance_after numeric(20,8) NOT NULL,
|
||||
currency varchar(3) NOT NULL DEFAULT 'CNY' CHECK (currency = 'CNY'),
|
||||
reason varchar(500) NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX wallet_entries_user_idx ON wallet_entries(user_id, created_at DESC);
|
||||
|
||||
CREATE TABLE registration_codes (
|
||||
account varchar(254) PRIMARY KEY,
|
||||
code_hash char(64) NOT NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
attempts integer NOT NULL DEFAULT 0,
|
||||
consumed boolean NOT NULL DEFAULT false,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE verification_send_events (
|
||||
id uuid PRIMARY KEY,
|
||||
account varchar(254) NOT NULL,
|
||||
ip_address varchar(128) NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX verification_send_account_idx ON verification_send_events(account, created_at);
|
||||
CREATE INDEX verification_send_ip_idx ON verification_send_events(ip_address, created_at);
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
package com.moyi.controlplane;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.moyi.controlplane.auth.*;
|
||||
import com.moyi.controlplane.catalog.CatalogService;
|
||||
import com.moyi.controlplane.common.ApiException;
|
||||
import com.moyi.controlplane.common.ApiExceptionHandler;
|
||||
import com.moyi.controlplane.security.SecretCipher;
|
||||
import com.moyi.controlplane.wallet.WalletService;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import javax.sql.DataSource;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.springframework.context.annotation.*;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.*;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@EnabledIfEnvironmentVariable(named="MOYI_AUTH_TEST_JDBC_URL", matches="jdbc:postgresql://127\\.0\\.0\\.1:[0-9]+/.+")
|
||||
class PlatformAdminPostgresTest {
|
||||
@Configuration @EnableTransactionManagement(proxyTargetClass=true)
|
||||
static class Transactions {}
|
||||
static class TestSender implements VerificationSender {
|
||||
final Map<String,String> codes = new ConcurrentHashMap<>();
|
||||
boolean enabled = true;
|
||||
boolean fail = false;
|
||||
public boolean available(String channel) { return enabled; }
|
||||
public void send(String channel, String account, String code) {
|
||||
if (fail) throw new ApiException("VERIFICATION_SEND_FAILED", "Test sender unavailable", 502);
|
||||
codes.put(account, code);
|
||||
}
|
||||
}
|
||||
private final ObjectMapper json = new ObjectMapper().findAndRegisterModules();
|
||||
private final AuthService.RequestMeta meta = new AuthService.RequestMeta("127.0.0.1", "isolated-test");
|
||||
private DriverManagerDataSource base;
|
||||
private AnnotationConfigApplicationContext context;
|
||||
private JdbcTemplate jdbc;
|
||||
private String schema, ownerToken, memberToken;
|
||||
private UUID memberId;
|
||||
private AuthService auth;
|
||||
private CatalogService catalog;
|
||||
private WalletService wallet;
|
||||
private VerificationService verification;
|
||||
private TestSender sender;
|
||||
|
||||
@BeforeEach void setup() throws Exception {
|
||||
String url = System.getenv("MOYI_AUTH_TEST_JDBC_URL");
|
||||
schema = "platform_test_" + UUID.randomUUID().toString().replace("-", "");
|
||||
base = new DriverManagerDataSource(url, "moyi_role_test", "");
|
||||
var source = new DriverManagerDataSource(url + "?currentSchema=" + schema, "moyi_role_test", "");
|
||||
jdbc = new JdbcTemplate(source);
|
||||
Flyway.configure().dataSource(base).schemas(schema).defaultSchema(schema).target("9").load().migrate();
|
||||
var legacyIds = jdbc.queryForList("SELECT id FROM model_catalog ORDER BY id", String.class);
|
||||
UUID legacyUser = UUID.randomUUID(), legacyKey = UUID.randomUUID();
|
||||
String legacyGrants = json.writeValueAsString(List.of(legacyIds.getFirst()));
|
||||
jdbc.update("INSERT INTO users(id,account,account_kind,password_hash,display_name) VALUES (?,'legacy_member','username','not-a-login-hash','Legacy Member')", legacyUser);
|
||||
jdbc.update("INSERT INTO platform_api_keys(id,user_id,name,key_prefix,key_hash,model_ids) VALUES (?,?,'Legacy Key','test-prefix',?,?::jsonb)", legacyKey, legacyUser, "a".repeat(64), legacyGrants);
|
||||
Flyway.configure().dataSource(base).schemas(schema).defaultSchema(schema).load().migrate();
|
||||
assertEquals(legacyIds, jdbc.queryForList("SELECT id FROM model_catalog ORDER BY id", String.class));
|
||||
assertEquals(legacyIds, jdbc.queryForList("SELECT logical_model_id FROM model_catalog ORDER BY id", String.class));
|
||||
assertEquals(json.readTree(legacyGrants), json.readTree(jdbc.queryForObject("SELECT model_ids::text FROM platform_api_keys WHERE id=?", String.class, legacyKey)));
|
||||
context = new AnnotationConfigApplicationContext();
|
||||
sender = new TestSender();
|
||||
context.register(Transactions.class);
|
||||
context.registerBean(DataSource.class, () -> source);
|
||||
context.registerBean(DataSourceTransactionManager.class, () -> new DataSourceTransactionManager(source));
|
||||
context.registerBean(AuthService.class, () -> new AuthService(jdbc, new PasswordHasher("test-pepper"), json, 168));
|
||||
context.registerBean(CatalogService.class, () -> new CatalogService(jdbc, json, new SecretCipher("test-encryption")));
|
||||
context.registerBean(WalletService.class, () -> new WalletService(jdbc, context.getBean(AuthService.class)));
|
||||
context.registerBean(VerificationService.class, () -> new VerificationService(jdbc, sender, "test-pepper"));
|
||||
context.refresh();
|
||||
auth = context.getBean(AuthService.class);
|
||||
catalog = context.getBean(CatalogService.class);
|
||||
wallet = context.getBean(WalletService.class);
|
||||
verification = context.getBean(VerificationService.class);
|
||||
auth.ensureAdmin("test_owner", "local-password", "Test Owner");
|
||||
ownerToken = auth.login("test_owner", "local-password", meta).token();
|
||||
memberId = auth.createUser(ownerToken, "test_member", "local-password", "Test Member", meta).id();
|
||||
memberToken = auth.login("test_member", "local-password", meta).token();
|
||||
}
|
||||
@AfterEach void cleanup() {
|
||||
if (context != null) context.close();
|
||||
// Only the random schema created by this isolated test is removed.
|
||||
if (base != null && schema != null) new JdbcTemplate(base).execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE");
|
||||
}
|
||||
@Test void modelGroupsKeepExactKeyGrantsAndEditableChannels() {
|
||||
var channel = catalog.createProvider(Map.of("code","test-relay","name","Relay","protocol","openai-compatible","sourceType","relay","baseUrl","https://example.test/v1","credentialType","api-key","credentialSecret","only-a-test-secret"), ownerToken, auth);
|
||||
String channelId = channel.get("id").toString();
|
||||
String cipher = jdbc.queryForObject("SELECT credential_ciphertext FROM model_providers WHERE id=?", String.class, channelId);
|
||||
var model = catalog.saveDefinition(null,Map.of("publicName","Test Model","type","text","mode","sync"),ownerToken,auth);
|
||||
String modelId = model.get("id").toString();
|
||||
var first = catalog.createModel(Map.of("logicalModelId",modelId,"providerId",channelId,"sourceLabel","Primary","upstreamModel","upstream-a"),ownerToken,auth);
|
||||
String firstId = first.get("id").toString();
|
||||
var second = catalog.createModel(Map.of("logicalModelId",modelId,"providerId",channelId,"sourceLabel","Backup","upstreamModel","upstream-b"),ownerToken,auth);
|
||||
String secondId = second.get("id").toString();
|
||||
var keyResult = catalog.createKey(memberToken,Map.of("modelIds",List.of(firstId)),auth);
|
||||
String plaintext = keyResult.get("key").toString();
|
||||
var key = catalog.authenticateKey(plaintext);
|
||||
String keyId = key.get("id").toString();
|
||||
assertTrue(catalog.keyCanInvoke(key,firstId));
|
||||
assertFalse(catalog.keyCanInvoke(key,secondId));
|
||||
assertFalse(catalog.keyCanInvoke(key,modelId));
|
||||
assertThrows(ApiException.class, () -> catalog.updateKeyModels(ownerToken,keyId,List.of(secondId),auth));
|
||||
var edited = catalog.updateProvider(channelId,Map.of("name","Relay Updated","baseUrl","https://example.test/v2","credentialSecret",""),ownerToken,auth);
|
||||
assertEquals("Relay Updated",edited.get("name"));
|
||||
assertFalse(edited.containsKey("credentialSecret"));
|
||||
assertEquals(cipher,jdbc.queryForObject("SELECT credential_ciphertext FROM model_providers WHERE id=?",String.class,channelId));
|
||||
catalog.saveDefinition(modelId,Map.of("publicName","Renamed"),ownerToken,auth);
|
||||
assertEquals("Renamed",catalog.activeModel(firstId).get("publicName"));
|
||||
catalog.updateModel(firstId,Map.of("sourceLabel","Edited Group","upstreamModel","upstream-c","maxConcurrency",2),ownerToken,auth);
|
||||
assertEquals("upstream-c",catalog.activeModel(firstId).get("upstreamModel"));
|
||||
assertTrue(catalog.keyCanInvoke(catalog.authenticateKey(plaintext),firstId));
|
||||
catalog.updateProvider(channelId,Map.of("status","disabled"),ownerToken,auth);
|
||||
assertNull(catalog.activeModel(firstId));
|
||||
assertTrue(catalog.listModels(false).stream().noneMatch(row -> row.get("id").equals(firstId)));
|
||||
catalog.updateKeyModels(memberToken,keyId,List.of(firstId),auth);
|
||||
assertThrows(ApiException.class, () -> catalog.updateKeyModels(memberToken,keyId,List.of(firstId,secondId),auth));
|
||||
catalog.updateProvider(channelId,Map.of("status","active"),ownerToken,auth);
|
||||
catalog.saveDefinition(modelId,Map.of("status","disabled"),ownerToken,auth);
|
||||
assertNull(catalog.activeModel(firstId));
|
||||
catalog.saveDefinition(modelId,Map.of("status","active"),ownerToken,auth);
|
||||
catalog.updateModel(firstId,Map.of("status","disabled"),ownerToken,auth);
|
||||
assertNull(catalog.activeModel(firstId));
|
||||
catalog.updateKeyModels(memberToken,keyId,List.of(),auth);
|
||||
assertFalse(catalog.keyCanInvoke(catalog.authenticateKey(plaintext),firstId));
|
||||
jdbc.update("UPDATE users SET status='disabled' WHERE id=?",memberId);
|
||||
assertNull(catalog.authenticateKey(plaintext));
|
||||
assertThrows(ApiException.class, () -> catalog.updateProvider(channelId,Map.of("name","bad"),memberToken,auth));
|
||||
}
|
||||
|
||||
@Test void grantsAreExactAuditedIdempotentAndConcurrent() throws Exception {
|
||||
assertThrows(ApiException.class, () -> wallet.grant(memberToken,memberId,UUID.randomUUID(),"1","unauthorized",meta));
|
||||
for (String invalid : List.of("0","-1","1.001","NaN","1000000.01")) assertThrows(ApiException.class, () -> wallet.grant(ownerToken,memberId,UUID.randomUUID(),invalid,"invalid",meta));
|
||||
UUID request = UUID.randomUUID();
|
||||
try (var pool = Executors.newFixedThreadPool(4)) {
|
||||
var one = pool.submit(() -> wallet.grant(ownerToken,memberId,request,"12.30","test grant",meta));
|
||||
var retry = pool.submit(() -> wallet.grant(ownerToken,memberId,request,"12.30","test grant",meta));
|
||||
assertEquals(one.get(10,TimeUnit.SECONDS).get("id"),retry.get(10,TimeUnit.SECONDS).get("id"));
|
||||
var two = pool.submit(() -> wallet.grant(ownerToken,memberId,UUID.randomUUID(),"0.10","second",meta));
|
||||
var three = pool.submit(() -> wallet.grant(ownerToken,memberId,UUID.randomUUID(),"0.20","third",meta));
|
||||
two.get(10,TimeUnit.SECONDS); three.get(10,TimeUnit.SECONDS);
|
||||
}
|
||||
assertThrows(ApiException.class, () -> wallet.grant(ownerToken,memberId,request,"99","test grant",meta));
|
||||
assertEquals(0,new BigDecimal("12.60").compareTo(jdbc.queryForObject("SELECT balance FROM user_wallets WHERE user_id=?",BigDecimal.class,memberId)));
|
||||
assertEquals(3,wallet.entries(ownerToken,memberId).size());
|
||||
assertEquals(3,jdbc.queryForObject("SELECT count(*) FROM auth_audit_log WHERE event_type='wallet.credit_granted'",Integer.class));
|
||||
assertEquals(0,new BigDecimal("12.60").compareTo((BigDecimal)catalog.overview(memberToken,auth).get("availableCredit")));
|
||||
}
|
||||
|
||||
@Test void directCreationCannotEscalateAndOtpIsRequiredOnBothChannels() throws Exception {
|
||||
MockMvc http = MockMvcBuilders.standaloneSetup(new AuthController(auth,verification,168,false)).setControllerAdvice(new ApiExceptionHandler()).build();
|
||||
http.perform(post("/api/admin/users").cookie(new Cookie("moyi_session",ownerToken)).contentType("application/json").content("{\"account\":\"created_user\",\"password\":\"test-password\",\"role\":\"super_admin\"}"))
|
||||
.andExpect(status().isCreated()).andExpect(jsonPath("$.user.role").value("user")).andExpect(jsonPath("$.user.password").doesNotExist());
|
||||
http.perform(post("/api/admin/users").cookie(new Cookie("moyi_session",memberToken)).contentType("application/json").content("{\"account\":\"bad_user\",\"password\":\"test-password\"}"))
|
||||
.andExpect(status().isForbidden());
|
||||
String invite = auth.createInvitation(ownerToken,"otp test",10,null,meta).get("code").toString();
|
||||
for (String account : List.of("otp@example.test","13800000000")) {
|
||||
var input = new LinkedHashMap<String,String>(Map.of("account",account,"password","test-password","invitationCode",invite));
|
||||
http.perform(post("/api/auth/register").contentType("application/json").content(json.writeValueAsBytes(input))).andExpect(status().isBadRequest());
|
||||
http.perform(post("/api/auth/verification").contentType("application/json").content(json.writeValueAsBytes(input)))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.code").doesNotExist()).andExpect(jsonPath("$.sent").value(true));
|
||||
String code = sender.codes.get(account);
|
||||
assertNotEquals(code,jdbc.queryForObject("SELECT code_hash FROM registration_codes WHERE account=?",String.class,account));
|
||||
input.put("verificationCode",code);
|
||||
http.perform(post("/api/auth/register").contentType("application/json").content(json.writeValueAsBytes(input)))
|
||||
.andExpect(status().isCreated()).andExpect(jsonPath("$.user.role").value("user"));
|
||||
assertThrows(ApiException.class, () -> verification.consume(account,code));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void otpLimitsExpiryAndFailedSendsPersistAcrossTransactions() {
|
||||
String invite = auth.createInvitation(ownerToken,"otp limits",20,null,meta).get("code").toString();
|
||||
String account="limits@example.test";
|
||||
assertThrows(ApiException.class, () -> verification.send(account,"bad-invite","127.0.0.1"));
|
||||
verification.send(account,invite,"127.0.0.1");
|
||||
assertThrows(ApiException.class, () -> verification.send(account,invite,"127.0.0.1"));
|
||||
String correct=sender.codes.get(account);
|
||||
String wrong=correct.equals("000000")?"111111":"000000";
|
||||
for(int i=0;i<5;i++) assertThrows(ApiException.class, () -> verification.consume(account,wrong));
|
||||
assertEquals(5,jdbc.queryForObject("SELECT attempts FROM registration_codes WHERE account=?",Integer.class,account));
|
||||
assertThrows(ApiException.class, () -> verification.consume(account,correct));
|
||||
verification.send("expired@example.test",invite,"127.0.0.1");
|
||||
jdbc.update("UPDATE registration_codes SET expires_at=now()-interval '1 second' WHERE account='expired@example.test'");
|
||||
assertThrows(ApiException.class, () -> verification.consume("expired@example.test",sender.codes.get("expired@example.test")));
|
||||
sender.fail=true;
|
||||
assertThrows(ApiException.class, () -> verification.send("failed@example.test",invite,"127.0.0.1"));
|
||||
assertTrue(jdbc.queryForObject("SELECT consumed FROM registration_codes WHERE account='failed@example.test'",Boolean.class));
|
||||
assertEquals(1,jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account='failed@example.test'",Integer.class));
|
||||
sender.enabled=false;
|
||||
assertFalse(verification.capabilities().containsValue(true));
|
||||
assertThrows(ApiException.class, () -> verification.send("unavailable@example.test",invite,"127.0.0.1"));
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,7 @@ class AuthPostgresTest {
|
||||
assertThrows(DataIntegrityViolationException.class, () -> jdbc.update("UPDATE users SET role = 'super_admin' WHERE id = ?", operatorId));
|
||||
assertThrows(IllegalStateException.class, () -> auth.ensureAdmin("operator", "test-password", "Other"));
|
||||
|
||||
MockMvc http = MockMvcBuilders.standaloneSetup(new AuthController(auth, 168, true))
|
||||
MockMvc http = MockMvcBuilders.standaloneSetup(new AuthController(auth, org.mockito.Mockito.mock(VerificationService.class), 168, true))
|
||||
.setControllerAdvice(new ApiExceptionHandler()).build();
|
||||
var ownerCookie = login(http, "adimin", "super_admin");
|
||||
var operatorCookie = login(http, "operator", "admin");
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.moyi.controlplane.auth;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PasswordHasherInteropTest {
|
||||
@Test
|
||||
void acceptsMaintenanceScriptPbkdf2HashesIncludingUnicode() {
|
||||
PasswordHasher hasher = new PasswordHasher("local-test-pepper");
|
||||
// Python hashlib fixtures with salt bytes 0..15; no real credentials.
|
||||
String ascii = "pbkdf2$210000$AAECAwQFBgcICQoLDA0ODw$_ZW4zVJDiheXQ51WuP_SSr_f8xjYJXBHvjkzLlPtFHo";
|
||||
String unicode = "pbkdf2$210000$AAECAwQFBgcICQoLDA0ODw$qZ4RLM7vU3k0rCJtetdh8uSbnAkWbxFYR7sD4GYRmb8";
|
||||
assertTrue(hasher.matches("Qa-Test42!", ascii));
|
||||
assertTrue(hasher.matches("\u6d4b\u8bd5A1!", unicode));
|
||||
assertFalse(hasher.matches("wrong-password", ascii));
|
||||
assertFalse(new PasswordHasher("wrong-pepper").matches("Qa-Test42!", ascii));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user