2026-09-18 17:27:58 +08:00
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 ;
2026-09-19 21:08:45 +08:00
import com.moyi.controlplane.catalog.CatalogController ;
import com.moyi.controlplane.usage.* ;
2026-09-18 17:27:58 +08:00
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" )));
}
2026-09-19 21:08:45 +08:00
@Test void deletedCatalogAndKeysCannotReturnButHistorySurvives () throws Exception {
var channel = catalog . createProvider ( Map . of ( "code" , "lifecycle-channel" , "name" , "Lifecycle Channel" ), ownerToken , auth );
String channelId = channel . get ( "id" ). toString ();
var model = catalog . saveDefinition ( null , Map . of ( "publicName" , "Lifecycle Model" , "type" , "text" , "mode" , "sync" ), ownerToken , auth );
String modelId = model . get ( "id" ). toString ();
var group = catalog . createModel ( Map . of ( "logicalModelId" , modelId , "providerId" , channelId , "sourceLabel" , "Primary" , "upstreamModel" , "test" ), ownerToken , auth );
String groupId = group . get ( "id" ). toString ();
var created = catalog . createKey ( memberToken , Map . of ( "name" , "History Key" , "modelIds" , List . of ( groupId )), auth );
String secret = created . get ( "key" ). toString ();
UUID keyId = ( UUID ) catalog . authenticateKey ( secret ). get ( "id" );
MockMvc http = MockMvcBuilders . standaloneSetup ( new CatalogController ( catalog , auth )). setControllerAdvice ( new ApiExceptionHandler ()). build ();
http . perform ( delete ( "/api/keys/" + keyId ). cookie ( new Cookie ( "moyi_session" , memberToken ))). andExpect ( status (). isConflict ());
http . perform ( patch ( "/api/keys/" + keyId + "/status" ). cookie ( new Cookie ( "moyi_session" , ownerToken )). contentType ( "application/json" ). content ( "{\"status\":\"disabled\"}" )). andExpect ( status (). isNotFound ());
catalog . revokeKey ( memberToken , keyId . toString (), auth );
assertNull ( catalog . authenticateKey ( secret ));
catalog . setKeyStatus ( memberToken , keyId . toString (), "active" , auth );
assertNotNull ( catalog . authenticateKey ( secret ));
new UsageAuditService ( jdbc , json ). recordCall ( memberId , keyId , groupId , channelId , "succeeded" , 120 , 10 , 20 , Map . of ( "messages" , List . of ( Map . of ( "role" , "user" , "content" , "history prompt" ))), Map . of ( "reply" , "saved response" ), null , null );
jdbc . update ( "INSERT INTO model_tasks(id,user_id,api_key_id,model_id,task_type,status,prompt) VALUES ('history-task',?,?,?,'3d','succeeded','test')" , memberId , keyId , groupId );
catalog . revokeKey ( memberToken , keyId . toString (), auth );
http . perform ( delete ( "/api/keys/" + keyId ). cookie ( new Cookie ( "moyi_session" , memberToken ))). andExpect ( status (). isNoContent ());
assertTrue ( catalog . listKeys ( memberToken , auth ). isEmpty ());
assertNull ( catalog . authenticateKey ( secret ));
assertThrows ( ApiException . class ,() -> catalog . setKeyStatus ( memberToken , keyId . toString (), "active" , auth ));
assertEquals ( 1 , jdbc . queryForObject ( "SELECT count(*) FROM model_tasks WHERE id='history-task'" , Integer . class ));
assertThrows ( ApiException . class ,() -> catalog . deleteCatalog ( "model" , modelId , memberToken , auth ));
assertEquals ( "CHANNEL_IN_USE" , assertThrows ( ApiException . class ,() -> catalog . deleteCatalog ( "channel" , channelId , ownerToken , auth )). getCode ());
catalog . deleteCatalog ( "group" , groupId , ownerToken , auth );
assertNull ( catalog . activeModel ( groupId ));
assertThrows ( ApiException . class ,() -> catalog . updateModel ( groupId , Map . of ( "status" , "active" ), ownerToken , auth ));
// The removed name can be reused without granting the replacement to existing keys.
var replacement = catalog . createModel ( Map . of ( "logicalModelId" , modelId , "providerId" , channelId , "sourceLabel" , "Primary" , "upstreamModel" , "test" ), ownerToken , auth );
catalog . deleteCatalog ( "model" , modelId , ownerToken , auth );
assertNull ( catalog . activeModel ( replacement . get ( "id" ). toString ()));
catalog . deleteCatalog ( "channel" , channelId , ownerToken , auth );
assertThrows ( ApiException . class ,() -> catalog . updateProvider ( channelId , Map . of ( "status" , "active" ), ownerToken , auth ));
assertDoesNotThrow (() -> catalog . createProvider ( Map . of ( "code" , "lifecycle-channel" , "name" , "New Channel" ), ownerToken , auth ));
var history = new UserUsageService ( jdbc , auth , json );
UUID usageId = jdbc . queryForObject ( "SELECT id FROM usage_events WHERE user_id=?" , UUID . class , memberId );
var detail = history . detail ( memberToken , usageId );
assertEquals ( "History Key" , detail . get ( "keyName" ));
assertEquals ( "Lifecycle Model" , detail . get ( "modelName" ));
assertEquals ( "Lifecycle Channel" , detail . get ( "providerName" ));
assertEquals ( "saved response" , json . valueToTree ( detail . get ( "output" )). get ( "reply" ). asText ());
}
@Test void walletAdjustmentsSerializeAndCannotOverdrawOrReplayTwice () throws Exception {
wallet . grant ( ownerToken , memberId , UUID . randomUUID (), "100" , "initial" , meta );
UUID request = UUID . randomUUID ();
try ( var pool = Executors . newFixedThreadPool ( 2 )) {
var a = pool . submit (() -> wallet . adjust ( ownerToken , memberId , request , "decrease" , "20" , "correction" , "100" , meta ));
var b = pool . submit (() -> wallet . adjust ( ownerToken , memberId , request , "decrease" , "20" , "correction" , "100" , meta ));
assertEquals ( a . get ( 10 , TimeUnit . SECONDS ). get ( "id" ), b . get ( 10 , TimeUnit . SECONDS ). get ( "id" ));
}
assertEquals ( "BALANCE_CHANGED" , assertThrows ( ApiException . class ,() -> wallet . adjust ( ownerToken , memberId , UUID . randomUUID (), "set" , "50" , "stale" , "100" , meta )). getCode ());
assertEquals ( "INSUFFICIENT_BALANCE" , assertThrows ( ApiException . class ,() -> wallet . adjust ( ownerToken , memberId , UUID . randomUUID (), "decrease" , "81" , "too much" , "80" , meta )). getCode ());
assertThrows ( ApiException . class ,() -> wallet . adjust ( memberToken , memberId , UUID . randomUUID (), "set" , "10" , "forbidden" , "80" , meta ));
wallet . adjust ( ownerToken , memberId , UUID . randomUUID (), "set" , "0" , "reset" , "80" , meta );
assertEquals ( 0 , BigDecimal . ZERO . compareTo ( jdbc . queryForObject ( "SELECT balance FROM user_wallets WHERE user_id=?" , BigDecimal . class , memberId )));
assertEquals ( 3 , wallet . entries ( ownerToken , memberId ). size ());
assertEquals ( 0 , BigDecimal . ZERO . compareTo ( jdbc . queryForObject ( "SELECT SUM(amount) FROM wallet_entries WHERE user_id=?" , BigDecimal . class , memberId )));
assertThrows ( ApiException . class ,() -> wallet . adjust ( ownerToken , memberId , request , "increase" , "20" , "correction" , "100" , meta ));
}
@Test void usageFiltersSummaryDetailsAndExportsStayWithinTheSessionOwner () throws Exception {
var key = catalog . createKey ( memberToken , Map . of ( "name" , "=formula key" ), auth );
UUID keyId = ( UUID ) catalog . authenticateKey ( key . get ( "key" ). toString ()). get ( "id" );
String groupId = jdbc . queryForObject ( "SELECT id FROM model_catalog ORDER BY id LIMIT 1" , String . class );
String modelId = jdbc . queryForObject ( "SELECT logical_model_id FROM model_catalog WHERE id=?" , String . class , groupId );
String providerId = jdbc . queryForObject ( "SELECT provider_id FROM model_catalog WHERE id=?" , String . class , groupId );
var audit = new UsageAuditService ( jdbc , json );
for ( int i = 0 ; i < 23 ; i ++ ) audit . recordCall ( memberId , keyId , groupId , providerId , "succeeded" , 100 , 10 , 20 , Map . of ( "prompt" , "member only" , "api_key" , "hidden" ), Map . of ( "reply" , "saved" ), null , null );
UUID other = auth . requireUser ( ownerToken ). id ();
audit . recordCall ( other , null , groupId , providerId , "failed" , 900 , 1000 , 1000 , Map . of ( "prompt" , "owner confidential" ), null , "ERR" , "internal" );
jdbc . update ( "UPDATE usage_events SET user_agent='Test Client', request_source='playground', endpoint='/v1/chat/completions', cost_amount=0.5, cached_input_units=2 WHERE user_id=?" , memberId );
jdbc . update ( "UPDATE usage_events SET admin_note='admin private note' WHERE user_id=?" , memberId );
var service = new UserUsageService ( jdbc , auth , json );
var f = new UserUsageService . Filters ( keyId . toString (), modelId , groupId , "succeeded" , "call" , "sync" , "playground" , "recorded" , "Client" , null , null , 2 , 20 , "time" , "desc" );
var result = service . list ( memberToken , f );
assertEquals ( 23L , result . get ( "total" )); assertEquals ( 3 ,(( List <?> ) result . get ( "records" )). size ());
var summary = ( Map <? , ?> ) result . get ( "summary" );
assertEquals ( 0 , new BigDecimal ( "11.5" ). compareTo (( BigDecimal ) summary . get ( "totalCost" )));
assertEquals ( 0 , new BigDecimal ( "230" ). compareTo (( BigDecimal ) summary . get ( "inputUnits" )));
var csv = service . exportCsv ( memberToken , f );
assertEquals ( 24 , csv . lines (). count ()); assertTrue ( csv . contains ( "'=formula key" )); assertFalse ( csv . contains ( "owner confidential" ));
UUID otherId = jdbc . queryForObject ( "SELECT id FROM usage_events WHERE user_id=?" , UUID . class , other );
assertThrows ( ApiException . class ,() -> service . detail ( memberToken , otherId ));
UUID ownId = jdbc . queryForObject ( "SELECT id FROM usage_events WHERE user_id=? LIMIT 1" , UUID . class , memberId );
var detail = service . detail ( memberToken , ownId );
assertFalse ( detail . containsKey ( "adminNote" )); assertFalse ( detail . containsKey ( "sourceIp" ));
assertEquals ( "[REDACTED]" , json . valueToTree ( detail . get ( "input" )). get ( "api_key" ). asText ());
MockMvc http = MockMvcBuilders . standaloneSetup ( new UserUsageController ( service )). setControllerAdvice ( new ApiExceptionHandler ()). build ();
http . perform ( get ( "/api/usage" ). cookie ( new Cookie ( "moyi_session" , memberToken )). param ( "keyId" , keyId . toString ()). param ( "page" , "2" ). param ( "size" , "20" ))
. andExpect ( status (). isOk ()). andExpect ( jsonPath ( "$.total" ). value ( 23 )). andExpect ( jsonPath ( "$.records.length()" ). value ( 3 ));
http . perform ( get ( "/api/usage/" + otherId ). cookie ( new Cookie ( "moyi_session" , memberToken ))). andExpect ( status (). isNotFound ());
http . perform ( get ( "/api/usage/options" ). cookie ( new Cookie ( "moyi_session" , memberToken ))). andExpect ( status (). isOk ());
http . perform ( get ( "/api/usage/export" ). cookie ( new Cookie ( "moyi_session" , memberToken )). param ( "status" , "failed" ))
. andExpect ( status (). isOk ()). andExpect ( content (). string ( org . hamcrest . Matchers . not ( org . hamcrest . Matchers . containsString ( "owner confidential" ))));
}
@Test void requestMetadataAndCacheUsageAreRecordedWithoutExposingSecrets () throws Exception {
String groupId = jdbc . queryForObject ( "SELECT id FROM model_catalog ORDER BY id LIMIT 1" , String . class );
String providerId = jdbc . queryForObject ( "SELECT provider_id FROM model_catalog WHERE id=?" , String . class , groupId );
var audit = new UsageAuditService ( jdbc , json );
var request = new org . springframework . mock . web . MockHttpServletRequest ( "POST" , "/v1/chat/completions" );
request . addHeader ( "X-Moyi-Source" , "playground" );
request . addHeader ( "User-Agent" , "Local test browser" );
org . springframework . web . context . request . RequestContextHolder . setRequestAttributes ( new org . springframework . web . context . request . ServletRequestAttributes ( request ));
try {
audit . recordCall ( memberId , null , groupId , providerId , "succeeded" , 200 , 100 , 20 ,
Map . of ( "prompt" , "hello" , "authorization" , "hidden" ),
Map . of ( "usage" , Map . of ( "prompt_tokens_details" , Map . of ( "cached_tokens" , 80 ), "cache_creation_input_tokens" , 5 )), null , null );
} finally { org . springframework . web . context . request . RequestContextHolder . resetRequestAttributes (); }
var saved = jdbc . queryForMap ( "SELECT * FROM usage_events WHERE user_id=?" , memberId );
assertEquals ( "/v1/chat/completions" , saved . get ( "endpoint" ));
assertEquals ( "playground" , saved . get ( "request_source" ));
assertEquals ( "Local test browser" , saved . get ( "user_agent" ));
assertEquals ( 80L , saved . get ( "cached_input_units" ));
assertEquals ( 5L , saved . get ( "cache_write_units" ));
assertNull ( saved . get ( "cost_amount" ));
assertNull ( saved . get ( "first_token_ms" ));
assertFalse ( saved . get ( "input_payload" ). toString (). contains ( "hidden" ));
audit . recordTask ( memberId , null , groupId , providerId , "local-timing-task" , "queued" , Map . of ( "prompt" , "hello" ), null , null , null );
jdbc . update ( "UPDATE usage_events SET created_at=now()-interval '2 seconds' WHERE provider_task_id='local-timing-task'" );
audit . updateTask ( "local-timing-task" , "succeeded" , Map . of ( "url" , "https://example.test/result" ), null , null );
assertTrue ( jdbc . queryForObject ( "SELECT latency_ms>=2000 FROM usage_events WHERE provider_task_id='local-timing-task'" , Boolean . class ));
}
2026-09-18 17:27:58 +08:00
@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" ));
}
}