feat: extend enterprise gateway policies billing protocols and operations
This commit is contained in:
1 parent
1528b71882
commit
af43947b5d
67 files changed
+1822
-69
No files matched your search
+86
@@ -0,0 +1,86 @@
|
||||
package com.moyi.controlplane.gateway;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.moyi.controlplane.common.ApiException;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.InetAddress;
|
||||
import java.time.*;
|
||||
import java.util.*;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
/** Policy checks fail closed. Budget reservations run inside the caller's wallet transaction. */
|
||||
@Service
|
||||
public class EnterprisePolicies {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final ObjectMapper json;
|
||||
public EnterprisePolicies(JdbcTemplate jdbc,ObjectMapper json) {this.jdbc=jdbc;this.json=json;}
|
||||
public record UserLimit(UUID userId,int rpm,int concurrency) {}
|
||||
public UserLimit taskLimit(UUID keyId) {
|
||||
var row=jdbc.queryForMap("SELECT k.user_id,coalesce(p.requests_per_minute,120) rpm,coalesce(p.max_concurrency,16) concurrency FROM platform_api_keys k LEFT JOIN gateway_user_policies p ON p.user_id=k.user_id WHERE k.id=?",keyId);
|
||||
return new UserLimit((UUID)row.get("user_id"),((Number)row.get("rpm")).intValue(),((Number)row.get("concurrency")).intValue());
|
||||
}
|
||||
public UserLimit access(UUID keyId) {
|
||||
var rows=jdbc.queryForList("SELECT k.user_id,p.expires_at,p.ip_allowlist,coalesce(u.requests_per_minute,120) rpm,coalesce(u.max_concurrency,16) concurrency FROM platform_api_keys k LEFT JOIN gateway_key_policies p ON p.key_id=k.id LEFT JOIN gateway_user_policies u ON u.user_id=k.user_id WHERE k.id=? AND k.status='active' AND k.deleted_at IS NULL",keyId);
|
||||
if(rows.isEmpty()) throw new ApiException("INVALID_API_KEY","API Key 不可用",401);
|
||||
var row=rows.getFirst();
|
||||
if(row.get("expires_at") instanceof java.sql.Timestamp expiry && !expiry.toInstant().isAfter(Instant.now())) throw new ApiException("API_KEY_EXPIRED","API Key 已过期",403);
|
||||
if(row.get("ip_allowlist")!=null) {
|
||||
try {
|
||||
List<String> ranges=json.readValue(row.get("ip_allowlist").toString(),new com.fasterxml.jackson.core.type.TypeReference<>(){});
|
||||
if(!ranges.isEmpty()) {
|
||||
var context=RequestContextHolder.getRequestAttributes();
|
||||
String address=context instanceof ServletRequestAttributes servlet?servlet.getRequest().getRemoteAddr():null;
|
||||
if(address==null||ranges.stream().noneMatch(range->matches(address,range))) throw new ApiException("IP_NOT_ALLOWED","此 IP 不在 API Key 白名单内",403);
|
||||
}
|
||||
} catch(ApiException e) {throw e;} catch(Exception e) {throw new ApiException("INVALID_KEY_POLICY","API Key 策略不可用",503);}
|
||||
}
|
||||
return new UserLimit((UUID)row.get("user_id"),((Number)row.get("rpm")).intValue(),((Number)row.get("concurrency")).intValue());
|
||||
}
|
||||
public static boolean matches(String address,String cidr) {
|
||||
try {
|
||||
String[] parts=cidr.split("/",-1);
|
||||
if(parts.length>2) return false;
|
||||
byte[] ip=literal(address),network=literal(parts[0]);
|
||||
int bits=parts.length==2?Integer.parseInt(parts[1]):network.length*8;
|
||||
if(bits<0||bits>network.length*8||ip.length!=network.length) return false;
|
||||
for(int i=0;i<ip.length;i++) {int mask=bits>=8?255:bits<=0?0:255<<(8-bits);if((ip[i]&mask)!=(network[i]&mask)) return false;bits-=8;}
|
||||
return true;
|
||||
} catch(Exception e) {return false;}
|
||||
}
|
||||
private static byte[] literal(String address) throws Exception {
|
||||
if(address==null||!address.matches("[0-9a-fA-F:.]+")||(!address.contains(":")&&!address.matches("[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+"))) throw new IllegalArgumentException("Literal IP required");
|
||||
return InetAddress.getByName(address).getAddress();
|
||||
}
|
||||
public static void validateRanges(List<?> ranges) {
|
||||
if(ranges.size()>100) throw new ApiException("INVALID_IP_RANGE","最多 100 个 IP / CIDR");
|
||||
for(Object item:ranges) if(!(item instanceof String range)||!matches(range.split("/",-1)[0],range)) throw new ApiException("INVALID_IP_RANGE","请输入有效的 IPv4 / IPv6 或 CIDR");
|
||||
}
|
||||
public void reserve(String requestId,UUID userId,UUID keyId,BigDecimal amount) {
|
||||
// Lock order matches wallet settlement. All keys owned by this user share one budget lock.
|
||||
jdbc.queryForList("SELECT user_id FROM user_wallets WHERE user_id=? FOR UPDATE",userId);
|
||||
var user=jdbc.queryForList("SELECT monthly_budget FROM gateway_user_policies WHERE user_id=?",userId);
|
||||
var key=jdbc.queryForList("SELECT total_budget,daily_budget,monthly_budget FROM gateway_key_policies WHERE key_id=?",keyId);
|
||||
ZonedDateTime now=ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
|
||||
Instant day=now.toLocalDate().atStartOfDay(now.getZone()).toInstant();
|
||||
Instant month=now.toLocalDate().withDayOfMonth(1).atStartOfDay(now.getZone()).toInstant();
|
||||
if(!user.isEmpty()) check(user.getFirst().get("monthly_budget"),userId,null,month,amount);
|
||||
if(!key.isEmpty()) {
|
||||
var p=key.getFirst();check(p.get("total_budget"),userId,keyId,Instant.EPOCH,amount);
|
||||
check(p.get("daily_budget"),userId,keyId,day,amount);check(p.get("monthly_budget"),userId,keyId,month,amount);
|
||||
}
|
||||
jdbc.update("INSERT INTO gateway_budget_holds(request_id,user_id,key_id,amount) VALUES (?,?,?,?)",requestId,userId,keyId,amount);
|
||||
}
|
||||
private void check(Object ceiling,UUID userId,UUID keyId,Instant since,BigDecimal amount) {
|
||||
if(ceiling==null) return;
|
||||
String keyClause=keyId==null?"":" AND api_key_id=?";
|
||||
var args=new ArrayList<Object>(List.of(userId,java.sql.Timestamp.from(since)));if(keyId!=null) args.add(keyId);
|
||||
// Includes archived usage: archival is not a budget reset.
|
||||
BigDecimal spent=jdbc.queryForObject("SELECT coalesce(sum(cost_amount),0) FROM usage_events WHERE user_id=? AND created_at>=?"+keyClause,BigDecimal.class,args.toArray());
|
||||
BigDecimal held=keyId==null?jdbc.queryForObject("SELECT coalesce(sum(amount),0) FROM gateway_budget_holds WHERE user_id=?",BigDecimal.class,userId):jdbc.queryForObject("SELECT coalesce(sum(amount),0) FROM gateway_budget_holds WHERE user_id=? AND key_id=?",BigDecimal.class,userId,keyId);
|
||||
if(spent.add(held).add(amount).compareTo(new BigDecimal(ceiling.toString()))>0) throw new ApiException("BUDGET_EXCEEDED","本次调用将超过用户或 API Key 的人民币预算,请联系管理员调整额度",402);
|
||||
}
|
||||
public void release(String requestId) {jdbc.update("DELETE FROM gateway_budget_holds WHERE request_id=?",requestId);}
|
||||
}
|
||||
Reference in new issue
Block a user