70 lines
5.8 KiB
Java
70 lines
5.8 KiB
Java
package com.moyi.controlplane.gateway;
|
||
|
||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||
import com.moyi.controlplane.auth.*;
|
||
import com.moyi.controlplane.common.ApiException;
|
||
import jakarta.servlet.http.HttpServletRequest;
|
||
import java.math.BigDecimal;
|
||
import java.time.OffsetDateTime;
|
||
import java.util.*;
|
||
import org.springframework.jdbc.core.JdbcTemplate;
|
||
import org.springframework.transaction.annotation.Transactional;
|
||
import org.springframework.web.bind.annotation.*;
|
||
|
||
@RestController
|
||
@RequestMapping("/api")
|
||
public class EnterprisePolicyController {
|
||
private final JdbcTemplate jdbc; private final AuthService auth; private final ObjectMapper json;
|
||
public EnterprisePolicyController(JdbcTemplate jdbc,AuthService auth,ObjectMapper json) {this.jdbc=jdbc;this.auth=auth;this.json=json;}
|
||
private AuthService.UserView owner(UUID keyId,HttpServletRequest request) {
|
||
var user=auth.requireUser(AuthController.sessionToken(request));
|
||
if(jdbc.queryForObject("SELECT count(*) FROM platform_api_keys WHERE id=? AND user_id=? AND deleted_at IS NULL",Integer.class,keyId,user.id())!=1) throw new ApiException("KEY_NOT_FOUND","API Key 不存在",404);
|
||
return user;
|
||
}
|
||
@GetMapping("/keys/{keyId}/policy")
|
||
public Map<String,Object> keyPolicy(@PathVariable UUID keyId,HttpServletRequest request) {
|
||
owner(keyId,request);
|
||
var rows=jdbc.queryForList("SELECT expires_at,ip_allowlist::text,total_budget,daily_budget,monthly_budget FROM gateway_key_policies WHERE key_id=?",keyId);
|
||
return rows.isEmpty()?Map.of("ip_allowlist","[]"):rows.getFirst();
|
||
}
|
||
@PutMapping("/keys/{keyId}/policy") @Transactional
|
||
public Map<String,Object> keyPolicy(@PathVariable UUID keyId,@RequestBody Map<String,Object> input,HttpServletRequest request) throws Exception {
|
||
var user=owner(keyId,request);
|
||
var ranges=input.getOrDefault("ipAllowlist",List.of());
|
||
if(!(ranges instanceof List<?> list)) throw new ApiException("INVALID_IP_RANGE","IP 白名单应为列表");
|
||
EnterprisePolicies.validateRanges(list);
|
||
OffsetDateTime expiry=null;
|
||
if(input.get("expiresAt")!=null&&!input.get("expiresAt").toString().isBlank()) {
|
||
try {expiry=OffsetDateTime.parse(input.get("expiresAt").toString());} catch(Exception e) {throw new ApiException("INVALID_EXPIRY","请输入带时区的有效截止时间");}
|
||
if(!expiry.isAfter(OffsetDateTime.now())) throw new ApiException("INVALID_EXPIRY","截止时间必须晚于当前时间");
|
||
}
|
||
// Serialize updates with admissions; lowering below current spend intentionally blocks new calls.
|
||
jdbc.queryForList("SELECT user_id FROM user_wallets WHERE user_id=? FOR UPDATE",user.id());
|
||
jdbc.update("INSERT INTO gateway_key_policies(key_id,expires_at,ip_allowlist,total_budget,daily_budget,monthly_budget) VALUES (?,?,?::jsonb,?,?,?) ON CONFLICT(key_id) DO UPDATE SET expires_at=excluded.expires_at,ip_allowlist=excluded.ip_allowlist,total_budget=excluded.total_budget,daily_budget=excluded.daily_budget,monthly_budget=excluded.monthly_budget,updated_at=now()",keyId,expiry,json.writeValueAsString(list),budget(input.get("totalBudget")),budget(input.get("dailyBudget")),budget(input.get("monthlyBudget")));
|
||
auth.audit("key.policy_updated",user.id(),AuthController.meta(request),Map.of("keyId",keyId,"policy",input));
|
||
return keyPolicy(keyId,request);
|
||
}
|
||
@GetMapping("/admin/users/{userId}/gateway-policy")
|
||
public Map<String,Object> userPolicy(@PathVariable UUID userId,HttpServletRequest request) {
|
||
auth.requireAdmin(AuthController.sessionToken(request));
|
||
var rows=jdbc.queryForList("SELECT requests_per_minute,max_concurrency,monthly_budget FROM gateway_user_policies WHERE user_id=?",userId);
|
||
return rows.isEmpty()?Map.of("requests_per_minute",120,"max_concurrency",16):rows.getFirst();
|
||
}
|
||
@PutMapping("/admin/users/{userId}/gateway-policy") @Transactional
|
||
public Map<String,Object> userPolicy(@PathVariable UUID userId,@RequestBody Map<String,Object> input,HttpServletRequest request) {
|
||
var actor=auth.requireAdmin(AuthController.sessionToken(request));
|
||
int rpm=integer(input.get("requestsPerMinute"),100000),concurrency=integer(input.get("maxConcurrency"),10000);
|
||
if(jdbc.queryForObject("SELECT count(*) FROM users WHERE id=?",Integer.class,userId)!=1) throw new ApiException("USER_NOT_FOUND","用户不存在",404);
|
||
jdbc.update("INSERT INTO user_wallets(user_id) VALUES (?) ON CONFLICT DO NOTHING",userId);
|
||
jdbc.queryForList("SELECT user_id FROM user_wallets WHERE user_id=? FOR UPDATE",userId);
|
||
jdbc.update("INSERT INTO gateway_user_policies(user_id,requests_per_minute,max_concurrency,monthly_budget) VALUES (?,?,?,?) ON CONFLICT(user_id) DO UPDATE SET requests_per_minute=excluded.requests_per_minute,max_concurrency=excluded.max_concurrency,monthly_budget=excluded.monthly_budget,updated_at=now()",userId,rpm,concurrency,budget(input.get("monthlyBudget")));
|
||
auth.audit("user.gateway_policy_updated",actor.id(),AuthController.meta(request),Map.of("userId",userId,"policy",input));
|
||
return userPolicy(userId,request);
|
||
}
|
||
static BigDecimal budget(Object value) {
|
||
if(value==null||value.toString().isBlank()) return null;
|
||
try {var n=new BigDecimal(value.toString());if(n.signum()<0||n.scale()>8||n.compareTo(new BigDecimal("1000000000"))>0) throw new NumberFormatException();return n;} catch(Exception e) {throw new ApiException("INVALID_BUDGET","预算须为 0–10 亿人民币,最多 8 位小数;留空为不限");}
|
||
}
|
||
static int integer(Object value,int max) {try {int n=new BigDecimal(value.toString()).intValueExact();if(n<1||n>max) throw new NumberFormatException();return n;} catch(Exception e) {throw new ApiException("INVALID_LIMIT","限额须为 1–"+max+" 的整数");}}
|
||
}
|