fix:"模型准入改为公平排队并收紧渠道凭据与目录暴露"

- acquire-pair.lua 增加模型到达顺序队列:空闲槽位先给更早等待者,超时/放弃/过期即出队,仅因自身 Key 满的等待者不占模型队位
- 修改渠道 Base URL 必须重新填写凭据,阻止已存密钥被发送到新地址;审计记录新旧地址
- 普通用户模型目录只返回渠道 id/name/status,不再暴露 Base URL 和凭据掩码
- 管理端用量 CSV 导出中和公式前缀
- 新增真实 Redis 公平准入、渠道凭据重填、目录字段和 CSV 回归

验证:mvn -B -o clean verify 403 项通过(独立 PostgreSQL/Redis)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
xppandClaude Opus 5.5 committed 2026-10-22 12:06:41 +08:00
1 parent 2e53b1d9c8
commit 1a608f8ff8
9 files changed
+178 -16

No files matched your search

@@ -125,10 +125,16 @@ class PlatformAdminPostgresTest {
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);
// The stored key must never follow a changed endpoint without being re-entered.
assertEquals("CREDENTIAL_REENTRY_REQUIRED", assertThrows(ApiException.class, () -> catalog.updateProvider(channelId,Map.of("baseUrl","https://attacker.test/v1","credentialSecret",""),ownerToken,auth)).getCode());
assertEquals("https://example.test/v1",jdbc.queryForObject("SELECT base_url FROM model_providers WHERE id=?",String.class,channelId));
var edited = catalog.updateProvider(channelId,Map.of("name","Relay Updated","baseUrl","https://example.test/v1/","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.updateProvider(channelId,Map.of("baseUrl","https://example.test/v2","credentialSecret","replacement-test-secret"),ownerToken,auth);
assertNotEquals(cipher,jdbc.queryForObject("SELECT credential_ciphertext FROM model_providers WHERE id=?",String.class,channelId));
assertTrue(jdbc.queryForObject("SELECT string_agg(details::text,' ') FROM auth_audit_log WHERE event_type='provider.updated'",String.class).contains("previousBaseUrl"));
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);
@@ -160,6 +166,10 @@ class PlatformAdminPostgresTest {
var cookie = new Cookie("moyi_session",memberToken);
var response = mvc.perform(get("/api/models").cookie(cookie)).andExpect(status().isOk()).andReturn();
var payload = json.readTree(response.getResponse().getContentAsString());
// Members see channel identity only, never endpoints or credential hints.
assertTrue(payload.get("providers").size() > 0);
assertTrue(payload.get("providers").findValues("baseUrl").isEmpty());
assertTrue(payload.get("providers").findValues("credentialMasked").isEmpty());
assertEquals(catalog.listDefinitions(false).size(),payload.get("logicalModels").size());
assertTrue(payload.get("logicalModels").size() > 250);
assertTrue(payload.get("logicalModels").findValuesAsText("id").contains(pending.get("id")));
@@ -0,0 +1,80 @@
package com.moyi.controlplane.gateway;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import static org.junit.jupiter.api.Assertions.*;
@EnabledIfEnvironmentVariable(named="MOYI_GATEWAY_TEST_REDIS_PORT", matches="[0-9]{2,5}")
class FairAdmissionRedisTest {
private LettuceConnectionFactory factory;
private StringRedisTemplate redis;
private final String prefix = "moyi:test:" + UUID.randomUUID() + ":";
private final Map<String,Object> model = Map.of("id", "fair-model", "maxConcurrency", 1);
@BeforeEach void setup() {
factory = new LettuceConnectionFactory("127.0.0.1", Integer.parseInt(System.getenv("MOYI_GATEWAY_TEST_REDIS_PORT")));
factory.afterPropertiesSet(); factory.start();
redis = new StringRedisTemplate(factory); redis.afterPropertiesSet();
}
@AfterEach void cleanup() {
if (redis != null) redis.delete(redis.keys(prefix + "*"));
if (factory != null) factory.destroy();
}
private GatewayGuard guard(long waitMs) { return new GatewayGuard(redis, 60, 300, 1, 4, waitMs, 10, prefix); }
@Test void newRequestCannotOvertakeAnEarlierWaiter() throws Exception {
var guard = guard(5000);
var holder = guard.acquire(model, UUID.randomUUID(), 5000);
var earlier = CompletableFuture.supplyAsync(() -> guard.acquire(model, UUID.randomUUID(), 5000));
// The earlier waiter is queued before the slot is released.
long until = System.nanoTime() + TimeUnit.SECONDS.toNanos(2);
while (zcard("order") == 0 && System.nanoTime() < until) Thread.sleep(5);
assertEquals(1L, zcard("order"));
holder.close();
// A newcomer that does not wait finds the free slot reserved for the earlier waiter.
var newcomer = assertThrows(GatewayLimitException.class, () -> guard(0).acquire(model, UUID.randomUUID(), 0));
assertEquals("MODEL_BUSY", newcomer.getCode());
try (var admitted = earlier.get(3, TimeUnit.SECONDS)) {
assertEquals(0L, zcard("order"));
assertEquals(0L, zcard("waiting"));
}
}
@Test void timedOutWaiterLeavesTheQueueAndDoesNotBlockLaterRequests() throws Exception {
var holder = guard(5000).acquire(model, UUID.randomUUID(), 5000);
assertThrows(GatewayLimitException.class, () -> guard(30).acquire(model, UUID.randomUUID(), 30));
assertEquals(0L, zcard("order"));
assertEquals(0L, zcard("waiting"));
holder.close();
try (var next = guard(0).acquire(model, UUID.randomUUID(), 0)) { assertNotNull(next); }
}
@Test void waiterBlockedByItsOwnKeyDoesNotHoldTheModelQueue() throws Exception {
UUID busyKey = UUID.randomUUID();
var keyGuard = new GatewayGuard(redis, 60, 300, 2, 1, 5000, 10, prefix);
var unlimitedModel = Map.<String,Object>of("id", "fair-model", "maxConcurrency", 2);
var keyHolder = keyGuard.acquire(unlimitedModel, busyKey, 5000);
var blockedByKey = CompletableFuture.supplyAsync(() -> keyGuard.acquire(unlimitedModel, busyKey, 200));
Thread.sleep(50);
// Another key may use the remaining model slot while the first key is at its own limit.
try (var other = keyGuard.acquire(unlimitedModel, UUID.randomUUID(), 0)) { assertNotNull(other); }
var failure = assertThrows(java.util.concurrent.ExecutionException.class, () -> blockedByKey.get(3, TimeUnit.SECONDS));
assertEquals("KEY_BUSY", ((GatewayLimitException) failure.getCause()).getCode());
keyHolder.close();
}
private long zcard(String kind) {
Long value = redis.opsForZSet().zCard(prefix + "gateway:" + kind + ":model:fair-model");
return value == null ? 0 : value;
}
}
@@ -0,0 +1,16 @@
package com.moyi.controlplane.usage;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class UsageCsvTest {
@Test void adminExportNeutralizesSpreadsheetFormulas() {
assertEquals("\"'=HYPERLINK(\"\"https://evil.test\"\")\"", UsageAuditService.csv("=HYPERLINK(\"https://evil.test\")"));
assertEquals("\"' @SUM(A1)\"", UsageAuditService.csv(" @SUM(A1)"));
assertEquals("\"'-1+2\"", UsageAuditService.csv("-1+2"));
assertEquals("\"'+cmd\"", UsageAuditService.csv("+cmd"));
assertEquals("\"plain text next\"", UsageAuditService.csv("plain text\r\nnext"));
assertEquals("\"\"", UsageAuditService.csv(null));
}
}