feat(open): ensure支持二次获取明文(ak存AES-GCM密文key_cipher, app.token-cipher-key派生密钥); 历史无密文Token自动轮换; V3迁移+回滚方案; 同步文档
This commit is contained in:
@@ -9,6 +9,7 @@ import me.iiv.agent.mapper.svc.AgentApiKeyMapper;
|
||||
import me.iiv.agent.mapper.svc.AgentScopeMapper;
|
||||
import me.iiv.agent.mapper.svc.TokenScopeMapper;
|
||||
import me.iiv.agent.security.AuthService;
|
||||
import me.iiv.agent.security.TokenCipher;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -33,6 +34,7 @@ class AdminTokenServiceTest {
|
||||
@Mock AgentApiKeyMapper tokenMapper;
|
||||
@Mock TokenScopeMapper tokenScopeMapper;
|
||||
@Mock AgentScopeMapper scopeMapper;
|
||||
@Mock TokenCipher tokenCipher;
|
||||
|
||||
private User stubUser() {
|
||||
User user = new User();
|
||||
@@ -43,11 +45,13 @@ class AdminTokenServiceTest {
|
||||
}
|
||||
|
||||
private AdminTokenService service() {
|
||||
return new AdminTokenService(userMapper, tokenMapper, tokenScopeMapper, scopeMapper);
|
||||
org.mockito.Mockito.lenient().when(tokenCipher.encrypt(any()))
|
||||
.thenAnswer(invocation -> "cipher:" + invocation.getArgument(0));
|
||||
return new AdminTokenService(userMapper, tokenMapper, tokenScopeMapper, scopeMapper, tokenCipher);
|
||||
}
|
||||
|
||||
@Test
|
||||
void issueReturnsPlaintextOnceAndStoresOnlyHash() {
|
||||
void issueReturnsPlaintextAndStoresHashAndCipher() {
|
||||
stubUser();
|
||||
AgentScope scope = new AgentScope();
|
||||
scope.setId(3L);
|
||||
@@ -68,6 +72,7 @@ class AdminTokenServiceTest {
|
||||
assertTrue(issued.get(0).plaintext().matches("xqak_[0-9a-f]{48}"));
|
||||
assertEquals(AuthService.sha256Hex(issued.get(0).plaintext()), stored.getKeyHash());
|
||||
assertNotEquals(issued.get(0).plaintext(), stored.getKeyHash());
|
||||
assertEquals("cipher:" + issued.get(0).plaintext(), stored.getKeyCipher());
|
||||
assertEquals(11L, issued.get(0).token().id());
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ class FlywayMigrationTest {
|
||||
|
||||
flyway.migrate();
|
||||
|
||||
assertEquals("2", flyway.info().current().getVersion().getVersion());
|
||||
assertEquals("3", flyway.info().current().getVersion().getVersion());
|
||||
assertEquals(255, passwordHashLength(dataSource));
|
||||
}
|
||||
|
||||
@@ -28,12 +28,13 @@ class FlywayMigrationTest {
|
||||
JdbcDataSource dataSource = dataSource("legacy");
|
||||
try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) {
|
||||
statement.execute("CREATE TABLE admin_user (id BIGINT AUTO_INCREMENT PRIMARY KEY, password_hash CHAR(64) NOT NULL)");
|
||||
statement.execute("CREATE TABLE agent_api_key (id BIGINT AUTO_INCREMENT PRIMARY KEY, key_hash CHAR(64) NOT NULL)");
|
||||
}
|
||||
Flyway flyway = flyway(dataSource, true);
|
||||
|
||||
flyway.migrate();
|
||||
|
||||
assertEquals("2", flyway.info().current().getVersion().getVersion());
|
||||
assertEquals("3", flyway.info().current().getVersion().getVersion());
|
||||
assertEquals(255, passwordHashLength(dataSource));
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import me.iiv.agent.entity.svc.AgentApiKey;
|
||||
import me.iiv.agent.entity.svc.AgentScope;
|
||||
import me.iiv.agent.mapper.m0.UserMapper;
|
||||
import me.iiv.agent.mapper.svc.AgentScopeMapper;
|
||||
import me.iiv.agent.security.TokenCipher;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
@@ -37,6 +38,7 @@ class OpenTokenServiceTest {
|
||||
@Mock AgentScopeMapper scopeMapper;
|
||||
@Mock AdminTokenService tokenService;
|
||||
@Mock AuditService auditService;
|
||||
@Mock TokenCipher tokenCipher;
|
||||
|
||||
OpenTokenService service;
|
||||
AgentScope scope;
|
||||
@@ -44,7 +46,7 @@ class OpenTokenServiceTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new OpenTokenService(userMapper, scopeMapper, tokenService, auditService);
|
||||
service = new OpenTokenService(userMapper, scopeMapper, tokenService, auditService, tokenCipher);
|
||||
scope = new AgentScope();
|
||||
scope.setId(3L);
|
||||
scope.setCode("operation");
|
||||
@@ -62,24 +64,62 @@ class OpenTokenServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingActiveTokenReturnsMetadataWithoutPlaintext() {
|
||||
void existingTokenWithCipherReturnsDecryptedPlaintext() {
|
||||
stubScopeAndUser();
|
||||
AgentApiKey existing = new AgentApiKey();
|
||||
existing.setId(11L);
|
||||
existing.setKeyPrefix("xqak_abcd1234");
|
||||
existing.setKeyCipher("packed-cipher");
|
||||
when(tokenService.findActiveToken(7L, 3L)).thenReturn(existing);
|
||||
when(tokenCipher.decrypt("packed-cipher")).thenReturn("xqak_abcd1234ffff");
|
||||
|
||||
OpenTokenController.EnsureResult result = service.ensure(
|
||||
new OpenTokenController.EnsureRequest("13800001111", null, "operation"));
|
||||
|
||||
assertFalse(result.created());
|
||||
assertNull(result.token());
|
||||
assertEquals("xqak_abcd1234ffff", result.token());
|
||||
assertEquals("xqak_abcd1234", result.keyPrefix());
|
||||
assertEquals(7L, result.userId());
|
||||
org.mockito.Mockito.verify(tokenService, never())
|
||||
.issueSingle(anyLong(), anyString(), anyLong(), isNull(), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingTokenWithoutCipherRotatesAndReturnsNewPlaintext() {
|
||||
stubScopeAndUser();
|
||||
AgentApiKey existing = new AgentApiKey();
|
||||
existing.setId(11L);
|
||||
existing.setKeyPrefix("xqak_abcd1234");
|
||||
when(tokenService.findActiveToken(7L, 3L)).thenReturn(existing);
|
||||
AdminTokenService.TokenView view = new AdminTokenService.TokenView(
|
||||
12L, "xqak_efgh5678", "open-api 自动签发(operation)", (byte) 1,
|
||||
null, null, List.of(3L), List.of("运营"));
|
||||
when(tokenService.issueSingle(eq(7L), anyString(), eq(3L), isNull(), eq(0L)))
|
||||
.thenReturn(new AdminTokenService.IssuedToken("xqak_" + "b".repeat(48), view));
|
||||
|
||||
OpenTokenController.EnsureResult result = service.ensure(
|
||||
new OpenTokenController.EnsureRequest("13800001111", null, "operation"));
|
||||
|
||||
org.mockito.Mockito.verify(tokenService).status(11L, (byte) 0, 0L);
|
||||
assertTrue(result.created());
|
||||
assertTrue(result.token().matches("xqak_[0-9a-f]{48}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void decryptFailureReturns500() {
|
||||
stubScopeAndUser();
|
||||
AgentApiKey existing = new AgentApiKey();
|
||||
existing.setId(11L);
|
||||
existing.setKeyPrefix("xqak_abcd1234");
|
||||
existing.setKeyCipher("bad-cipher");
|
||||
when(tokenService.findActiveToken(7L, 3L)).thenReturn(existing);
|
||||
when(tokenCipher.decrypt("bad-cipher")).thenThrow(new IllegalStateException("ak 密文解密失败"));
|
||||
|
||||
ResponseStatusException error = assertThrows(ResponseStatusException.class, () -> service.ensure(
|
||||
new OpenTokenController.EnsureRequest("13800001111", null, "operation")));
|
||||
assertEquals(500, error.getStatusCode().value());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingTokenCreatesPermanentOneAndReturnsPlaintext() {
|
||||
stubScopeAndUser();
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package me.iiv.agent.security;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class TokenCipherTest {
|
||||
|
||||
private final TokenCipher cipher = new TokenCipher("test-cipher-key");
|
||||
|
||||
@Test
|
||||
void encryptDecryptRoundTrip() {
|
||||
String plaintext = "xqak_25939fab31f812eb4e566197f53f16482d3e1f588b8bcaca";
|
||||
String packed = cipher.encrypt(plaintext);
|
||||
|
||||
assertNotEquals(plaintext, packed);
|
||||
assertEquals(plaintext, cipher.decrypt(packed));
|
||||
}
|
||||
|
||||
@Test
|
||||
void samePlaintextEncryptsDifferentlyEachTime() {
|
||||
String plaintext = "xqak_" + "a".repeat(48);
|
||||
assertNotEquals(cipher.encrypt(plaintext), cipher.encrypt(plaintext));
|
||||
}
|
||||
|
||||
@Test
|
||||
void wrongKeyCannotDecrypt() {
|
||||
String packed = cipher.encrypt("xqak_secret");
|
||||
TokenCipher other = new TokenCipher("another-key");
|
||||
assertThrows(IllegalStateException.class, () -> other.decrypt(packed));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tamperedCipherRejected() {
|
||||
String packed = cipher.encrypt("xqak_secret");
|
||||
byte[] raw = java.util.Base64.getDecoder().decode(packed);
|
||||
raw[raw.length - 1] ^= 0x01;
|
||||
String tampered = java.util.Base64.getEncoder().encodeToString(raw);
|
||||
assertThrows(IllegalStateException.class, () -> cipher.decrypt(tampered));
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankKeyDisablesCipher() {
|
||||
TokenCipher disabled = new TokenCipher(" ");
|
||||
assertThrows(IllegalStateException.class, () -> disabled.encrypt("xqak_x"));
|
||||
assertThrows(IllegalStateException.class, () -> disabled.decrypt("AAAA"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user