From 3e346ca47ed30c12678a502bf2401fb1ac445b54 Mon Sep 17 00:00:00 2001 From: Command1264 Date: Wed, 14 Oct 2026 00:48:32 +0800 Subject: [PATCH] test: strengthen offline anonymization acceptance coverage --- docs/operations/offline-anonymization.md | 2 + ...026-10-14-issue-25-anonymization-retest.md | 53 ++++ .../plugin/OfflineAnonymizeMainTest.kt | 275 +++++++++++++++++- .../json/JsonOfflineAnonymizationTest.kt | 215 +++++++++++++- .../sql/MysqlAnonymizationEvidenceTest.kt | 170 +++++++++++ .../storage/sql/MysqlIntegrationTest.kt | 2 +- .../sql/OfflinePlayerAnonymizerTest.kt | 113 ++++++- 7 files changed, 801 insertions(+), 29 deletions(-) create mode 100644 docs/testing/evidence/2026-10-14-issue-25-anonymization-retest.md create mode 100644 invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlAnonymizationEvidenceTest.kt diff --git a/docs/operations/offline-anonymization.md b/docs/operations/offline-anonymization.md index da184a3..e94923b 100644 --- a/docs/operations/offline-anonymization.md +++ b/docs/operations/offline-anonymization.md @@ -43,6 +43,8 @@ mise exec -- java -cp $JAR io.github.command1264.invitecode.plugin.OfflineAnonym ## 驗證與復原 +SQLite/JSON/MySQL 的匿名化、重新開啟、未處理獎勵拒絕、並行維護與失敗復原,以及離線 CLI 安全拒絕的補充自動證據見 [Issue #25 複驗紀錄](../testing/evidence/2026-10-14-issue-25-anonymization-retest.md)。這些測試使用合成資料;不能用其結果證明既有備份或外部資料也已匿名化。 + 工具顯示受影響的邀請、獎勵與舊碼數量。執行後確認:原 UUID 在 Player 查詢中不存在;歷史 ID 保留舊邀請關係;舊碼不能 Claim 或重新配發;資料可重新開啟;同 UUID 再加入會是新玩家。不要公開歷史 ID 與備份對照。交易失敗時 SQL 會回滾;若回滾狀態不明,停止所有寫入並檢查。JSON 快照失敗會停止當次寫入;檢查原檔與 `.previous` 後再處理。 匿名化不能刪除既有備份、log、終端機歷史、程序參數、第三方插件或玩家自行保存的資料。精確的歷史時間及關係仍可能被持有外部對照的人推測身分;備份與操作紀錄應依獨立保留政策保護與清除。工具不輸出新舊 ID 的對照。每次操作會新增固定理由的 `PLAYER_ANONYMIZED` 稽核事件,不在資料庫保留可能含身分的自由文字理由。 diff --git a/docs/testing/evidence/2026-10-14-issue-25-anonymization-retest.md b/docs/testing/evidence/2026-10-14-issue-25-anonymization-retest.md new file mode 100644 index 0000000..dafa085 --- /dev/null +++ b/docs/testing/evidence/2026-10-14-issue-25-anonymization-retest.md @@ -0,0 +1,53 @@ +# Issue #25 匿名化補充驗證 + +日期:2026-10-14。基線:`develop` 的 `befef792b20fd572b98e00569ca28a442b3e7320`。 +分支:`codex/test/issue-25-anonymization-evidence`。本次只修改測試與驗證文件;插件 production 程式碼、資料版本與匿名化設計均未變更。 + +## 補齊的驗收證據 + +| 邊界 | 已驗證內容 | +| --- | --- | +| SQLite | 匿名化後關閉/重開仍保留歷史邀請、Qualification Fact 與時間,舊 UUID/名稱/邀請碼不留在有效匯出;PENDING/PROCESSING/UNCERTAIN 拒絕且完整快照不變;真正寫入途中的 SQL trigger 失敗回滾;兩個獨立連線競爭同一玩家,僅一個操作成功。既有舊碼保留、重新加入、Invitee 與文字遮蔽測試保留。 | +| MySQL 8.4.11 | 完整合成歷史包含邀請、Qualification Fact、已完成 Reward/transition、稽核、登入日與網路雜湊。新建連線池重開驗證匿名關聯、狀態與時間、舊碼占用、新 UUID 世代與有效匯出隱私;三種未完成獎勵狀態拒絕且快照不變;兩個獨立連線池並行維護;SQLState 45000 trigger 故障完整回滾並允許明確重試。 | +| JSON | 完整邀請/資格/Reward/transition/稽核/網路資料在 close/reopen 後保留匿名關聯、狀態、時間與約束;有效 JSON 不含原 UUID、名稱及網路雜湊;舊碼不能 Claim 或重新啟用;同 UUID 可作為新玩家。三種未完成獎勵狀態拒絕且快照不變;第二個 open 被檔案鎖拒絕;備份發布失敗後,重開仍是完整舊資料。 | +| 離線 CLI execute 邊界 | 唯讀 preview 不改來源;缺 player/stopped/backup、無效 UUID、不存在目標、無效來源、錯長度密鑰、另一把有效長度密鑰與既有備份均拒絕。拒絕原因與來源 SHA-256、備份是否建立分開斷言,避免提前 parser 拒絕造成假通過。成功只改指定玩家,保留另一玩家;擷取正常及錯誤訊息,確認不輸出秘密、資料中名稱或新舊 ID 對照。操作者已提供的目標 UUID 可以在拒絕訊息出現。 | + +SQLite/MySQL 的失敗斷言核對實際注入錯誤/SQLState,不把任意 exception 當作故障注入通過。併發測試在兩個連線/連線池就緒後才同時放行,使用有界 Future 等待並結束 executor。JSON 的檔案鎖與 SQL 的維護交易/鎖各自驗證,不宣稱三者具有相同的線上多寫入者模型。 + +## 執行與結果 + +工具鏈依 mise 核對 `java@local-8`:Java `1.8.0_501`;沿用 Gradle Wrapper,未安裝 JDK 或新增 dependency。 + +```powershell +mise exec java@local-8 -- .\gradlew.bat check shadowJar --no-daemon --console=plain +``` + +最後完整檢查通過;JUnit XML 彙整 **56 suites、265 tests、0 failures、0 errors、0 skipped**。Java 8 bytecode 與插件 JAR 必要 entry 檢查通過。部分未變模組沿用 Gradle up-to-date 的有效結果;修改過的測試重新執行,不能把所有案例說成同一輪重新跑過。 + +| 本次專用 suite | tests | failures/errors/skipped | +| --- | ---: | --- | +| OfflinePlayerAnonymizerTest | 11 | 0/0/0 | +| MysqlAnonymizationEvidenceTest | 6 | 0/0/0 | +| JsonOfflineAnonymizationTest | 5 | 0/0/0 | +| OfflineAnonymizeMainTest | 8 | 0/0/0 | + +JSON 的三種未完成 Reward 狀態在一個 testcase 中依序核對。資料 fixture、編譯、錯誤訊息斷言及 MySQL 初始化的初期失敗保留 log,不計為插件故障的 RED 證據,也不計為通過。最初完整檢查的三個 plugin MySQL 案例因空測試密碼而跳過,改用本次專屬臨時帳號密碼後重跑,最終 XML 已無跳過。沒有為製造失敗而修改 production。 + +原始命令 log、最終 XML 副本與結果 manifest 保留於本 Worktree 的 `invitecode-plugin/build/issue25-evidence/`;隔離服務的初始化、正常停止與初期失敗 log 位於 `invitecode-plugin/build/issue25-mysql/`。該證據目錄不加入 Git,合併清理前須封存仍需追溯的檔案並同步索引。 + +## 產物與隔離邊界 + +本次重建 JAR SHA-256:`B82C7D3B3263AC1153C8048DA2E6342FF423C90EDADFED8F5228FA80331848F4`。 +與 Issue #12 的 D6AF 固定 JAR 比較,所有解壓後 entry 內容相同,沒有新增、刪除或變更 entry;外層 ZIP bytes/SHA-256 不同,不能把它們說成同一個檔案。本次未替換或部署至 Human 測服,不將重建 JAR 標記為新一次真人驗收。 + +MySQL 使用既有唯讀 8.4.11 binary,所有可寫資料放在本任務新建的 `invitecode-plugin/build/issue25-mysql/data`,只綁定 `127.0.0.1:63387`。測試以 UUID 名稱建立、清理專屬 `invitecode_test_*` database;未連到既有資料庫、Minecraft 或 InstanceHarbor 管理服務。初始化的 loopback 帳號設定錯誤曾在正常 shutdown 被拒後回收核對過的自有程序;此失敗另記錄,不計為成功流程。有效測試結束後以 mysqladmin 正常停止(exit 0),已確認自有程序與 port 釋放、移除臨時憑證並回收本次可重建資料目錄;保留 log、XML、JAR 與 resource manifest。刪除前資料目錄邏輯大小約 189 MiB,不將此數字當成磁碟實際釋放量。 + +## 保留的限制與交付 + +- 匿名化只處理有效 backend 資料,不清除既有備份、JSON `.previous`、伺服器 log、第三方插件或外部對照;依 [ADR 0005](../../adr/0005-offline-player-anonymization.md) 與[維運文件](../../operations/offline-anonymization.md)管理。 +- 所有寫入者仍須事先停止;`--stopped` 是操作者確認。並行維護測試不代表可以在遊戲伺服器持續寫入時安全匿名化。 +- 本次故障是在 SQL transaction/JSON 備份發布邊界注入,沒有測 OS 斷電、kill CLI 或 mysqld 崩潰。CLI 測試呼叫 execute,不驗證 JVM 子程序 exit code。 +- 新登入語義以 storage 的重新建立玩家及舊關係隔離驗證;不新增真人登入證據。既有 Issue #12 三核心人工確認保留。 +- 本次沒有 remote write。Issue #25 結案仍須指定版本交付/合併後,在 Issue 留下本證據與 CI 結果並取得結案授權;Issue #26 不在本次修改範圍。 + +下一步依 [Issue #25 驗收條件](https://github.com/Command1264/InviteCodeKt/issues/25)交付本機候選、授權後建立目標 `develop` 的 PR。之後再依 [Issue #26](https://github.com/Command1264/InviteCodeKt/issues/26)整理已具備的搬移證據與文件現況,銜接 [Roadmap #1「發行門檻」](https://github.com/Command1264/InviteCodeKt/issues/1)。不因本次自動測試通過而直接關閉 Issue 或正式發布。 diff --git a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/OfflineAnonymizeMainTest.kt b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/OfflineAnonymizeMainTest.kt index 9719b75..089f6be 100644 --- a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/OfflineAnonymizeMainTest.kt +++ b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/OfflineAnonymizeMainTest.kt @@ -5,39 +5,294 @@ import io.github.command1264.invitecode.platform.bukkit.NetworkAddressHasher import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard import io.github.command1264.invitecode.storage.sql.SqliteInviteCodeStorage import io.github.command1264.invitecode.storage.sql.SqliteSchemaMigrator +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir +import org.junit.jupiter.api.parallel.ResourceLock +import org.junit.jupiter.api.parallel.Resources +import java.io.ByteArrayOutputStream +import java.io.PrintStream import java.nio.file.Files import java.nio.file.Path +import java.security.MessageDigest import java.time.Instant import java.util.UUID +@ResourceLock(Resources.SYSTEM_OUT) class OfflineAnonymizeMainTest { @TempDir lateinit var directory: Path + @Test + fun `preview leaves source unchanged and does not create backup`() { + val fixture = createFixture() + val before = sha256(fixture.database) + val backup = directory.resolve("preview-backup.db") + + val result = capture(commandArgs(fixture)) + + assertNull(result.failure) + assertTrue(result.stdout.contains("影響範圍:")) + assertTrue(result.stderr.isEmpty()) + assertEquals(before, sha256(fixture.database)) + assertFalse(Files.exists(backup)) + assertPrivateOutput(result, fixture) + } + + @Test + fun `missing player stopped confirmation backup and explicit UUID are rejected without writes`() { + val fixture = createFixture() + val before = sha256(fixture.database) + val backup = directory.resolve("must-not-be-created.db") + val rejected = listOf( + commandArgs(fixture, omit = setOf("player")) to "缺少 --player", + commandArgs(fixture, flags = setOf("apply")) to "停止所有 InviteCode 實例", + commandArgs(fixture, flags = setOf("apply", "stopped")) to "必須指定 --backup", + commandArgs(fixture, overrides = mapOf("player" to "Alice")) to "UUID", + ) + + rejected.forEach { (command, reason) -> + val result = capture(command) + assertRejection(result, reason, fixture.database, before, backup) + assertPrivateOutput(result, fixture) + } + } + + @Test + fun `nonexistent target is rejected without changing source or creating backup`() { + val fixture = createFixture() + val before = sha256(fixture.database) + val backup = directory.resolve("nonexistent-target-backup.db") + + val absentPlayerId = UUID.randomUUID() + val result = capture(commandArgs( + fixture, + overrides = mapOf("player" to absentPlayerId.toString(), "backup" to backup.toString()), + flags = setOf("apply", "stopped"), + )) + + assertRejection(result, "is absent", fixture.database, before, backup) + assertPrivateOutput(result, fixture, allowedCallerUuids = setOf(absentPlayerId.toString())) + } + + @Test + fun `invalid secret is rejected without changing source or creating backup`() { + val fixture = createFixture() + val before = sha256(fixture.database) + val invalidSecret = directory.resolve("invalid-secret.key") + val invalidSecretText = "not-a-valid-anti-abuse-secret" + Files.write(invalidSecret, invalidSecretText.toByteArray(Charsets.UTF_8)) + val backup = directory.resolve("invalid-secret-backup.db") + + val result = capture(commandArgs( + fixture, + overrides = mapOf("secret" to invalidSecret.toString(), "backup" to backup.toString()), + flags = setOf("apply", "stopped"), + )) + + assertRejection(result, "must contain exactly 32 bytes", fixture.database, before, backup) + assertPrivateOutput(result, fixture, extraSecrets = listOf(invalidSecretText)) + } + + @Test + fun `invalid source file is rejected without changing its bytes`() { + val fixture = createFixture() + val invalidSource = directory.resolve("not-a-database.db") + Files.write(invalidSource, "not a SQLite database".toByteArray(Charsets.UTF_8)) + val before = sha256(invalidSource) + val backup = directory.resolve("invalid-source-backup.db") + + val result = capture(commandArgs( + fixture, + overrides = mapOf("source" to invalidSource.toString(), "backup" to backup.toString()), + flags = setOf("apply", "stopped"), + )) + + assertRejection(result, "is not initialized", invalidSource, before, backup) + assertPrivateOutput(result, fixture) + } + + @Test + fun `existing backup is preserved and source remains unchanged`() { + val fixture = createFixture() + val before = sha256(fixture.database) + val backup = directory.resolve("existing-backup.db") + val originalBackup = "preserve this existing backup".toByteArray(Charsets.UTF_8) + Files.write(backup, originalBackup) + + val result = capture(commandArgs( + fixture, + overrides = mapOf("backup" to backup.toString()), + flags = setOf("apply", "stopped"), + )) + + assertRejection(result, "備份檔已存在", fixture.database, before) + assertEquals(before, sha256(fixture.database)) + assertTrue(Files.readAllBytes(backup).contentEquals(originalBackup)) + assertPrivateOutput(result, fixture) + } + + @Test + fun `valid length but different reservation secret is rejected without modifying source`() { + val fixture = createFixture() + val priorPlayer = UUID.randomUUID() + NetworkAddressHasher.loadExisting(fixture.secret).use { hasher -> + val key = io.github.command1264.invitecode.storage.sql.CodeReservationKey(hasher.keyId, hasher::hashReservedCode) + SqliteInviteCodeStorage.open(fixture.database, fixture.guard, key).use { storage -> + storage.savePlayer(StoredPlayer(priorPlayer, Instant.parse("2026-01-01T00:00:00Z"), "PriorPlayer")) + storage.atomically { it.activate(io.github.command1264.invitecode.core.ActiveInviteCode( + priorPlayer, io.github.command1264.invitecode.core.InviteCode.fromNormalized("D4E5F6"), + Instant.parse("2026-01-01T00:00:00Z"), + )) } + storage.anonymizePlayer(priorPlayer) + } + } + val wrongSecret = directory.resolve("different-secret.key") + Files.write(wrongSecret, ByteArray(32) { 7 }) + val backup = directory.resolve("different-key-backup.db") + val before = sha256(fixture.database) + val result = capture(commandArgs(fixture, + overrides = mapOf("secret" to wrongSecret.toString(), "backup" to backup.toString()), + flags = setOf("apply", "stopped"), + )) + assertRejection(result, "use another anti-abuse key", fixture.database, before, backup) + assertPrivateOutput(result, fixture, extraSecrets = listOf("07".repeat(32))) + } + @Test fun `offline command copies and verifies backup before anonymizing the requested player`() { - val database = directory.resolve("players.db") - val secret = directory.resolve("anti-abuse.key") + val fixture = createFixture() val backup = directory.resolve("players.before-anonymization.db") + val otherPlayer = UUID.randomUUID() + SqliteInviteCodeStorage.open(fixture.database, fixture.guard).use { + it.savePlayer(StoredPlayer(otherPlayer, Instant.parse("2026-01-01T00:00:00Z"), "OtherPlayer")) + } + + val result = capture(commandArgs( + fixture, + overrides = mapOf("backup" to backup.toString()), + flags = setOf("apply", "stopped"), + )) + + assertNull(result.failure) + assertTrue(Files.isRegularFile(backup)) + SqliteInviteCodeStorage.open(backup, fixture.guard).use { assertNotNull(it.player(fixture.playerId)) } + SqliteInviteCodeStorage.open(fixture.database, fixture.guard).use { + assertNull(it.player(fixture.playerId)) + assertEquals("OtherPlayer", it.player(otherPlayer)?.lastKnownName) + } + assertPrivateOutput(result, fixture) + } + + private fun createFixture(): Fixture { + val database = directory.resolve("players-${UUID.randomUUID()}.db") + val secret = directory.resolve("anti-abuse-${UUID.randomUUID()}.key") val playerId = UUID.randomUUID() val guard = BlockingOperationGuard { } NetworkAddressHasher.loadOrCreate(secret).close() + val secretText = Files.readAllBytes(secret).joinToString("") { "%02x".format(it) } SqliteSchemaMigrator(database, guard).migrate() SqliteInviteCodeStorage.open(database, guard).use { storage -> - storage.savePlayer(StoredPlayer(playerId, Instant.parse("2026-01-01T00:00:00Z"), "Alice")) + storage.savePlayer(StoredPlayer(playerId, Instant.parse("2026-01-01T00:00:00Z"), STORED_NAME)) } + return Fixture(database, secret, secretText, playerId, guard) + } - OfflineAnonymizeMain.execute(arrayOf( - "--backend", "sqlite", "--source", database.toString(), "--secret", secret.toString(), - "--player", playerId.toString(), "--apply", "--stopped", "--backup", backup.toString(), - )) + private fun commandArgs( + fixture: Fixture, + overrides: Map = emptyMap(), + omit: Set = emptySet(), + flags: Set = emptySet(), + ): Array { + val values = linkedMapOf( + "backend" to "sqlite", + "source" to fixture.database.toString(), + "secret" to fixture.secret.toString(), + "player" to fixture.playerId.toString(), + ) + values.putAll(overrides) + omit.forEach { values.remove(it) } + val valueArgs = values.flatMap { (name, value) -> listOf("--$name", value) } + return (valueArgs + flags.map { "--$it" }).toTypedArray() + } - assertTrue(Files.isRegularFile(backup)) - SqliteInviteCodeStorage.open(backup, guard).use { assertNotNull(it.player(playerId)) } - SqliteInviteCodeStorage.open(database, guard).use { assertNull(it.player(playerId)) } + private fun capture(args: Array): CapturedExecution { + val stdout = ByteArrayOutputStream() + val stderr = ByteArrayOutputStream() + val previousOut = System.out + val previousErr = System.err + var failure: Throwable? = null + try { + System.setOut(PrintStream(stdout, true, "UTF-8")) + System.setErr(PrintStream(stderr, true, "UTF-8")) + try { + OfflineAnonymizeMain.execute(args) + } catch (error: Exception) { + failure = error + } + } finally { + System.setOut(previousOut) + System.setErr(previousErr) + } + return CapturedExecution( + String(stdout.toByteArray(), Charsets.UTF_8), + String(stderr.toByteArray(), Charsets.UTF_8), + failure, + ) + } + + private fun assertRejection( + result: CapturedExecution, + reason: String, + source: Path, + sourceHash: String, + backupThatMustNotExist: Path? = null, + ) { + val message = result.failure?.message + assertNotNull(message, "Expected command rejection") + assertTrue(message!!.contains(reason, ignoreCase = true), "Expected rejection reason '$reason', got '$message'") + assertEquals(sourceHash, sha256(source)) + backupThatMustNotExist?.let { assertFalse(Files.exists(it)) } + } + + private fun assertPrivateOutput( + result: CapturedExecution, + fixture: Fixture, + allowedCallerUuids: Set = emptySet(), + extraSecrets: List = emptyList(), + ) { + val output = result.stdout + result.stderr + result.failure?.message.orEmpty() + assertFalse(output.contains(fixture.secretText), "CLI output must not contain the secret contents") + extraSecrets.forEach { secret -> + assertFalse(output.contains(secret), "CLI output must not contain supplied secret material") + } + assertFalse(output.contains(STORED_NAME), "CLI output must not contain the stored player name") + val printedUuids = UUID_PATTERN.findAll(output).map { it.value }.toSet() + assertTrue( + printedUuids.all { it in allowedCallerUuids }, + "CLI output must not contain generated UUIDs or an ID mapping: $printedUuids", + ) + } + + private fun sha256(path: Path): String = MessageDigest.getInstance("SHA-256") + .digest(Files.readAllBytes(path)) + .joinToString("") { "%02x".format(it) } + + private data class Fixture( + val database: Path, + val secret: Path, + val secretText: String, + val playerId: UUID, + val guard: BlockingOperationGuard, + ) + + private data class CapturedExecution(val stdout: String, val stderr: String, val failure: Throwable?) + + private companion object { + const val STORED_NAME = "StoredAliceForPrivacyCheck" + val UUID_PATTERN = Regex("(?i)\\b[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}\\b") } } diff --git a/invitecode-storage-json/src/test/kotlin/io/github/command1264/invitecode/storage/json/JsonOfflineAnonymizationTest.kt b/invitecode-storage-json/src/test/kotlin/io/github/command1264/invitecode/storage/json/JsonOfflineAnonymizationTest.kt index 577671c..164f69e 100644 --- a/invitecode-storage-json/src/test/kotlin/io/github/command1264/invitecode/storage/json/JsonOfflineAnonymizationTest.kt +++ b/invitecode-storage-json/src/test/kotlin/io/github/command1264/invitecode/storage/json/JsonOfflineAnonymizationTest.kt @@ -1,19 +1,19 @@ package io.github.command1264.invitecode.storage.json import com.google.gson.JsonParser -import io.github.command1264.invitecode.core.StoredPlayer +import io.github.command1264.invitecode.api.InvitationStatus +import io.github.command1264.invitecode.core.* import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard import io.github.command1264.invitecode.storage.sql.CodeReservationKey -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertNotNull -import org.junit.jupiter.api.Assertions.assertNull -import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import java.time.Instant +import java.time.LocalDate +import java.time.Duration import java.util.UUID class JsonOfflineAnonymizationTest { @@ -22,20 +22,202 @@ class JsonOfflineAnonymizationTest { private val key = CodeReservationKey("a".repeat(64)) { "b".repeat(64) } @Test - fun `anonymization persists across JSON restart`() { + fun `anonymization preserves full history while removing identity from durable snapshot`() { val file = directory.resolve("players.json") - val oldId = UUID.randomUUID() - var historicalId: UUID? = null + val inviter = UUID.randomUUID() + val invitee = UUID.randomUUID() + val unrelatedPlayer = UUID.randomUUID() + val invitationId = UUID.randomUUID() + val auditId = UUID.randomUUID() + val code = InviteCode.fromNormalized("A1B2C3") + val claimedAt = Instant.parse("2026-01-02T03:04:05Z") + val qualifiedAt = Instant.parse("2026-01-03T03:04:05Z") + val rewardAt = Instant.parse("2026-01-04T03:04:05Z") + val deliveredAt = rewardAt.plusSeconds(1) + val delivery = StoredRewardDelivery( + UUID.randomUUID(), invitationId, "reward-Alice", RewardDeliveryStatus.PENDING, + "delivery:$inviter", qualifiedAt, qualifiedAt, + ) + val reward = StoredRewardAction( + UUID.randomUUID(), delivery.id, invitationId, inviter, 0, "MESSAGE", "Hello Alice $inviter", + RewardActionStatus.PENDING, "action:$inviter", qualifiedAt, qualifiedAt, + ) + val claimedInvitation = Invitation(invitationId, inviter, invitee, InvitationStatus.CLAIMED, claimedAt) + val invitation = Invitation( + invitationId, inviter, invitee, InvitationStatus.QUALIFIED, claimedAt, + qualifiedAt, "days-online", "revision-7", + ) + val fact = QualificationFact( + UUID.randomUUID(), invitationId, "days-online", "revision-7", "three-days", + QualificationFactOutcome.SATISFIED, qualifiedAt, + ) + val loginDay = LocalDate.parse("2026-01-01") + val networkHash = "c".repeat(64) + + var historicalId: UUID + JsonInviteCodeStorage.open(file, guard, key).use { storage -> + storage.savePlayer(StoredPlayer(inviter, Instant.parse("2025-12-01T00:00:00Z"), "Alice")) + storage.savePlayer(StoredPlayer(invitee, Instant.parse("2025-12-02T00:00:00Z"), "Bob")) + storage.savePlayer(StoredPlayer(unrelatedPlayer, Instant.parse("2025-12-03T00:00:00Z"), "Carol")) + storage.atomically { it.activate(ActiveInviteCode(inviter, code, claimedAt.minusSeconds(60))) } + storage.saveInvitation(claimedInvitation) + storage.saveQualifiedInvitationWithRewards( + invitation, listOf(fact), listOf(RewardDeliveryPlan(delivery, listOf(reward))), + ) + storage.saveRewardAction(reward.copy(status = RewardActionStatus.PROCESSING, updatedAt = rewardAt)) + val deliveredAction = reward.copy(status = RewardActionStatus.DELIVERED, updatedAt = deliveredAt) + storage.saveRewardAction(deliveredAction) + // saveRewardAction updates the aggregate automatically; persist the final delivery + // state explicitly through the complete-set API as a separate contract assertion. + storage.saveRewardDelivery( + delivery.copy(status = RewardDeliveryStatus.DELIVERED, updatedAt = deliveredAt), + listOf(deliveredAction), + ) + storage.recordLoginDay(inviter, loginDay) + storage.recordNetworkHash(PlayerNetworkHash(inviter, "a".repeat(64), networkHash, claimedAt, rewardAt)) + storage.saveAuditRecord(AuditRecord( + auditId, InvitationAuditAction.ELIGIBILITY_RESET, "Alice", "Alice requested for $inviter", + rewardAt, playerId = inviter, + )) + + val result = storage.anonymizePlayer(inviter) + historicalId = result.historicalId + assertNotEquals(inviter, historicalId) + assertNull(storage.player(inviter)) + assertEquals(historicalId, storage.invitation(invitationId)?.inviterId) + assertEquals(invitee, storage.invitation(invitationId)?.inviteeId) + assertEquals(invitation.status, storage.invitation(invitationId)?.status) + assertEquals(invitation.claimedAt, storage.invitation(invitationId)?.claimedAt) + assertEquals(invitation.qualifiedAt, storage.invitation(invitationId)?.qualifiedAt) + assertEquals(listOf(fact.copy( + policyId = "[anonymized]", qualificationRevision = "[anonymized]", conditionId = "[anonymized]", + )), storage.qualificationFacts(invitationId)) + assertEquals(1, storage.previewAnonymization(invitee).invitations) + assertTrue(storage.isInviteCodeReserved(code)) + assertNull(storage.activeInviteCode(code)) + assertTrue(storage.auditHistoryByPlayer(historicalId, 10).any { + it.action == InvitationAuditAction.ELIGIBILITY_RESET && it.playerId == historicalId + }) + assertEquals(0, storage.loginDays(inviter)) + } + + val snapshot = readUtf8(file) + listOf(inviter.toString(), "Alice", networkHash).forEach { assertFalse(snapshot.contains(it), "leaked $it") } + assertTrue(snapshot.contains(historicalId.toString())) + val json = Files.newBufferedReader(file, StandardCharsets.UTF_8).use { JsonParser.parseReader(it).asJsonObject } + assertTrue(json.getAsJsonObject("tables").getAsJsonArray("invitecode_qualification_facts").size() > 0) + + JsonInviteCodeStorage.open(file, guard, key).use { reopened -> + assertNull(reopened.player(inviter)) + assertNotNull(reopened.player(historicalId)) + assertNull(reopened.player(historicalId)?.lastKnownName) + val persistedInvitation = reopened.invitation(invitationId) + assertEquals(historicalId, persistedInvitation?.inviterId) + assertEquals(invitee, persistedInvitation?.inviteeId) + assertEquals(invitation.status, persistedInvitation?.status) + assertEquals(claimedAt, persistedInvitation?.claimedAt) + assertEquals(qualifiedAt, persistedInvitation?.qualifiedAt) + assertEquals( + listOf(fact.copy( + policyId = "[anonymized]", qualificationRevision = "[anonymized]", conditionId = "[anonymized]", + )), + reopened.qualificationFacts(invitationId), + ) + val persistedDelivery = reopened.rewardDeliveries(invitationId).single() + assertEquals(RewardDeliveryStatus.DELIVERED, persistedDelivery.status) + assertEquals(delivery.createdAt, persistedDelivery.createdAt) + assertEquals(deliveredAt, persistedDelivery.updatedAt) + assertEquals("[anonymized]", persistedDelivery.rewardId) + val persistedReward = reopened.rewardActions(persistedDelivery.id).single() + assertEquals(historicalId, persistedReward.recipientId) + assertEquals(RewardActionStatus.DELIVERED, persistedReward.status) + assertEquals(qualifiedAt, persistedReward.createdAt) + assertEquals(deliveredAt, persistedReward.updatedAt) + assertEquals("[anonymized]", persistedReward.payload) + assertFalse(persistedReward.idempotencyKey.contains(inviter.toString())) + assertEquals(deliveredAt, reopened.rewardActionTransitions(persistedReward.id).last().occurredAt) + assertEquals(1, reopened.previewAnonymization(historicalId).invitations) + assertTrue(reopened.isInviteCodeReserved(code)) + assertNull(reopened.activeInviteCode(code)) + reopened.savePlayer(StoredPlayer(inviter, Instant.parse("2026-02-01T00:00:00Z"), "AliceAgain")) + assertNotNull(reopened.player(inviter)) + assertTrue(reopened.invitationsByInviter(inviter).isEmpty()) + assertThrows(IllegalStateException::class.java) { + reopened.atomically { it.activate(ActiveInviteCode(inviter, code, rewardAt.plusSeconds(1))) } + } + val claimingPlayer = UUID.randomUUID() + reopened.savePlayer(StoredPlayer(claimingPlayer, rewardAt)) + val confirmation = ClaimConfirmation.present( + claimingPlayer, inviter, "AliceAgain", code, rewardAt, Duration.ofMinutes(1), + ).confirm(claimingPlayer, rewardAt.plusSeconds(1)) + val claimService = InvitationClaimService(reopened, ClaimEligibilityPolicy(Duration.ofDays(7)), UUID::randomUUID) + assertTrue(claimService.claim(confirmation) is InvitationClaimResult.InviteCodeUnavailable) + } + } + + @Test + fun `unresolved reward action states reject anonymization without changing snapshot`() { + listOf(RewardActionStatus.PENDING, RewardActionStatus.PROCESSING, RewardActionStatus.UNCERTAIN).forEach { status -> + val file = directory.resolve("${status.name.lowercase()}.json") + val playerId = UUID.randomUUID() + val whenCreated = Instant.parse("2026-01-01T00:00:00Z") + JsonInviteCodeStorage.open(file, guard, key).use { storage -> + storage.savePlayer(StoredPlayer(playerId, whenCreated, "Alice")) + val delivery = StoredRewardDelivery(UUID.randomUUID(), null, "reward", RewardDeliveryStatus.PENDING, + "delivery:$playerId", whenCreated, whenCreated) + val action = StoredRewardAction(UUID.randomUUID(), delivery.id, null, playerId, 0, "MESSAGE", "Alice", + RewardActionStatus.PENDING, "action:$playerId", whenCreated, whenCreated) + storage.saveRewardDelivery(delivery, listOf(action)) + if (status != RewardActionStatus.PENDING) { + val processing = action.copy(status = RewardActionStatus.PROCESSING, updatedAt = whenCreated.plusSeconds(1)) + storage.saveRewardAction(processing) + if (status == RewardActionStatus.UNCERTAIN) { + storage.saveRewardAction(processing.copy( + status = RewardActionStatus.UNCERTAIN, updatedAt = whenCreated.plusSeconds(2), + )) + } + } + val before = readUtf8(file) + assertThrows(IllegalStateException::class.java) { storage.anonymizePlayer(playerId) } + assertEquals(before, readUtf8(file)) + assertEquals("Alice", storage.player(playerId)?.lastKnownName) + } + } + } + + @Test + fun `second open is rejected while first handle owns JSON file lock`() { + val file = directory.resolve("locked.json") + JsonInviteCodeStorage.open(file, guard).use { + assertThrows(JsonStorageException::class.java) { JsonInviteCodeStorage.open(file, guard) } + } + JsonInviteCodeStorage.open(file, guard).close() + } + + @Test + fun `failed anonymization snapshot leaves previous complete identity after restart`() { + val file = directory.resolve("snapshot-failure.json") + val playerId = UUID.randomUUID() + val code = InviteCode.fromNormalized("D4E5F6") JsonInviteCodeStorage.open(file, guard, key).use { storage -> - storage.savePlayer(StoredPlayer(oldId, Instant.parse("2026-01-01T00:00:00Z"), "Alice")) - historicalId = storage.anonymizePlayer(oldId).historicalId + storage.savePlayer(StoredPlayer(playerId, Instant.parse("2026-01-01T00:00:00Z"), "Alice")) + storage.atomically { it.activate(ActiveInviteCode(playerId, code, Instant.parse("2026-01-01T00:00:00Z"))) } } + val original = readUtf8(file) + // A directory at the backup destination makes the atomic backup replacement fail reliably. + val previous = file.resolveSibling("${file.fileName}.previous") + // Replace this test's generated backup with an unwritable target type before the operation. + Files.deleteIfExists(previous) + Files.createDirectory(previous) JsonInviteCodeStorage.open(file, guard, key).use { storage -> - assertNull(storage.player(oldId)) - assertNotNull(storage.player(requireNotNull(historicalId))) - assertNull(storage.player(requireNotNull(historicalId))?.lastKnownName) - storage.savePlayer(StoredPlayer(oldId, Instant.now(), "AliceAgain")) - assertTrue(storage.invitationsByInviter(oldId).isEmpty()) + assertThrows(JsonStorageException::class.java) { storage.anonymizePlayer(playerId) } + assertNull(storage.player(playerId)) + } + assertEquals(original, readUtf8(file)) + Files.delete(file.resolveSibling("${file.fileName}.previous")) + JsonInviteCodeStorage.open(file, guard, key).use { reopened -> + assertEquals("Alice", reopened.player(playerId)?.lastKnownName) + assertEquals(playerId, reopened.activeInviteCode(code)?.inviterId) } } @@ -61,4 +243,7 @@ class JsonOfflineAnonymizationTest { assertEquals("Alice", storage.player(playerId)?.lastKnownName) } } + + private fun readUtf8(path: Path): String = + Files.newBufferedReader(path, StandardCharsets.UTF_8).use { it.readText() } } diff --git a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlAnonymizationEvidenceTest.kt b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlAnonymizationEvidenceTest.kt new file mode 100644 index 0000000..d67305c --- /dev/null +++ b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlAnonymizationEvidenceTest.kt @@ -0,0 +1,170 @@ +package io.github.command1264.invitecode.storage.sql + +import com.zaxxer.hikari.HikariDataSource +import io.github.command1264.invitecode.core.* +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.Test +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.ValueSource +import java.time.Instant +import java.util.UUID +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit + +class MysqlAnonymizationEvidenceTest { + private val guard = BlockingOperationGuard { } + private val key = CodeReservationKey("a".repeat(64)) { "b".repeat(64) } + private val code = InviteCode.fromNormalized("A1B2C3") + private val time = Instant.parse("2026-01-01T00:00:00Z") + private data class Fixture(val player: UUID, val invitation: UUID, val fact: UUID) + + @Test + fun `complete anonymous history persists through a new MySQL connection pool`() = withMysqlSchema { config, pool -> + val fixture = seed(pool, "DELIVERED") + val historical = MysqlInviteCodeStorage.open(pool, guard, key).use { it.anonymizePlayer(fixture.player).historicalId } + newPool(config).use { reopened -> + MysqlInviteCodeStorage.open(reopened, guard, key).use { storage -> + assertNull(storage.player(fixture.player)) + assertNull(storage.player(historical)?.lastKnownName) + assertEquals(historical, storage.invitation(fixture.invitation)?.inviterId) + assertEquals(time.plusSeconds(1), storage.invitation(fixture.invitation)?.claimedAt) + assertEquals(time.plusSeconds(2), storage.invitation(fixture.invitation)?.qualifiedAt) + assertEquals(fixture.fact, storage.qualificationFacts(fixture.invitation).single().id) + assertEquals(time.plusSeconds(2), storage.qualificationFacts(fixture.invitation).single().recordedAt) + assertTrue(storage.isInviteCodeReserved(code)) + assertNull(storage.activeInviteCode(code)) + assertTrue(storage.pendingRewardActions(historical).isEmpty()) + assertTrue(storage.auditHistoryByPlayer(historical, 10).any { it.action.name == "PLAYER_ANONYMIZED" }) + val exported = reopened.connection.use { OfflineStorageTransfer.export(it, StorageDialect.MYSQL, key.keyId) } + assertFalse(exported.toString().contains(fixture.player.toString())) + assertFalse(exported.toString().contains("Alice")) + assertFalse(exported.toString().contains("A1B2C3")) + assertFalse(exported.toString().contains("c".repeat(64))) + storage.savePlayer(StoredPlayer(fixture.player, time.plusSeconds(10), "Returner")) + assertTrue(storage.invitationsByInviter(fixture.player).isEmpty()) + assertThrows(IllegalStateException::class.java) { + storage.atomically { it.activate(ActiveInviteCode(fixture.player, code, time.plusSeconds(11))) } + } + } + } + // The newly joined player is separate; delivered history remains settled. + newPool(config).use { reopened -> + reopened.connection.use { connection -> + val snapshot = OfflineStorageTransfer.export(connection, StorageDialect.MYSQL, key.keyId) + assertFalse(snapshot.toString().contains("Alice")) + assertFalse(snapshot.toString().contains("A1B2C3")) + val actions = snapshot.tables.single { it.name == "invitecode_reward_actions" } + val status = actions.columns.indexOf("status") + assertEquals(PortableValue.Text("DELIVERED"), actions.rows.single().values[status]) + } + } + } + + @ParameterizedTest + @ValueSource(strings = ["PENDING", "PROCESSING", "UNCERTAIN"]) + fun `unresolved MySQL rewards reject anonymization without changing any record`(status: String) = withMysqlSchema { config, pool -> + val fixture = seed(pool, status) + val before = snapshot(config) + MysqlInviteCodeStorage.open(pool, guard, key).use { storage -> + assertThrows(IllegalStateException::class.java) { storage.anonymizePlayer(fixture.player) } + } + assertEquals(before, snapshot(config)) + } + + @Test + fun `independent MySQL maintenance pools serialize the same player`() = withMysqlSchema { config, pool -> + val fixture = seed(pool, "DELIVERED") + val start = CountDownLatch(1) + val ready = CountDownLatch(2) + val executor = Executors.newFixedThreadPool(2) + try { + val attempts = (1..2).map { + executor.submit> { + newPool(config).use { connectionPool -> + MysqlInviteCodeStorage.open(connectionPool, guard, key).use { storage -> + ready.countDown() + check(start.await(10, TimeUnit.SECONDS)) + try { java.util.Optional.of(storage.anonymizePlayer(fixture.player)) } + catch (failure: IllegalStateException) { + assertTrue(failure.message.orEmpty().contains("absent"), failure.message) + java.util.Optional.empty() + } + } + } + } + } + assertTrue(ready.await(10, TimeUnit.SECONDS)) + start.countDown() + val results = attempts.map { it.get(25, TimeUnit.SECONDS) } + assertEquals(1, results.count { it.isPresent }) + val historical = results.single { it.isPresent }.get().historicalId + newPool(config).use { reopened -> + MysqlInviteCodeStorage.open(reopened, guard, key).use { storage -> + assertNull(storage.player(fixture.player)) + assertEquals(historical, storage.invitation(fixture.invitation)?.inviterId) + assertEquals(1, storage.auditHistoryByPlayer(historical, 10).count { it.action.name == "PLAYER_ANONYMIZED" }) + } + } + } finally { + start.countDown() + executor.shutdownNow() + assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)) + } + } + + @Test + fun `MySQL write failure preserves the complete source and permits an explicit retry`() = withMysqlSchema { config, pool -> + val fixture = seed(pool, "DELIVERED") + pool.connection.use { connection -> + connection.createStatement().use { it.execute("CREATE TRIGGER fail_anonymization BEFORE DELETE ON invitecode_players FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'injected anonymization failure'") } + } + val before = snapshot(config) + MysqlInviteCodeStorage.open(pool, guard, key).use { storage -> + val failure = assertThrows(MysqlStorageException::class.java) { storage.anonymizePlayer(fixture.player) } + assertTrue(failure.message.orEmpty().contains("SQLState 45000")) + } + assertEquals(before, snapshot(config)) + newPool(config).use { reopened -> + reopened.connection.use { it.createStatement().use { statement -> statement.execute("DROP TRIGGER fail_anonymization") } } + MysqlInviteCodeStorage.open(reopened, guard, key).use { storage -> + storage.anonymizePlayer(fixture.player) + assertNull(storage.player(fixture.player)) + } + } + } + + private fun newPool(config: MysqlConfiguration) = MysqlInviteCodeStorage.createPool(config, System.getenv("INVITECODE_TEST_MYSQL_PASSWORD") ?: "") + private fun snapshot(config: MysqlConfiguration) = newPool(config).use { pool -> + pool.connection.use { OfflineStorageTransfer.export(it, StorageDialect.MYSQL, key.keyId) } + } + + private fun seed(pool: HikariDataSource, status: String): Fixture { + MysqlSchemaMigrator(pool, guard).migrate() + val player = UUID.randomUUID() + val invitee = UUID.randomUUID() + val invitation = UUID.randomUUID() + val fact = UUID.randomUUID() + val delivery = UUID.randomUUID() + val action = UUID.randomUUID() + pool.connection.use { connection -> + MysqlSchemaMigrator.bindNetworkKey(connection, key.keyId) + fun insert(sql: String, vararg values: Any?) = connection.prepareStatement(sql).use { statement -> + values.forEachIndexed { index, value -> statement.setObject(index + 1, value) } + statement.executeUpdate() + } + insert("INSERT INTO invitecode_players(player_id, first_seen_at, last_known_name) VALUES (?, ?, 'Alice'), (?, ?, 'Bob')", player.toString(), time.toString(), invitee.toString(), time.toString()) + insert("INSERT INTO invitecode_codes(code, inviter_id, activated_at) VALUES ('A1B2C3', ?, ?)", player.toString(), time.toString()) + insert("INSERT INTO invitecode_invitations(invitation_id, inviter_id, inviter_eligibility_generation, invitee_id, invitee_eligibility_generation, status, claimed_at, qualified_at, qualification_policy_id, qualification_revision) VALUES (?, ?, 0, ?, 0, 'QUALIFIED', ?, ?, 'policy', 'revision')", invitation.toString(), player.toString(), invitee.toString(), time.plusSeconds(1).toString(), time.plusSeconds(2).toString()) + insert("INSERT INTO invitecode_qualification_facts(fact_id, invitation_id, policy_id, qualification_revision, condition_id, outcome, recorded_at) VALUES (?, ?, 'policy', 'revision', 'condition', 'SATISFIED', ?)", fact.toString(), invitation.toString(), time.plusSeconds(2).toString()) + insert("INSERT INTO invitecode_reward_deliveries(delivery_id, invitation_id, reward_id, status, idempotency_key, created_at, updated_at) VALUES (?, ?, 'Alice reward', ?, ?, ?, ?)", delivery.toString(), invitation.toString(), status, "milestone:$player", time.plusSeconds(3).toString(), time.plusSeconds(4).toString()) + insert("INSERT INTO invitecode_reward_actions(action_id, reward_delivery_id, invitation_id, recipient_id, position, action_type, payload, status, idempotency_key, created_at, updated_at) VALUES (?, ?, ?, ?, 0, 'MESSAGE', 'Hello Alice', ?, ?, ?, ?)", action.toString(), delivery.toString(), invitation.toString(), player.toString(), status, "action:$player", time.plusSeconds(3).toString(), time.plusSeconds(4).toString()) + insert("INSERT INTO invitecode_reward_action_transitions(action_id, previous_status, current_status, occurred_at, actor, reason) VALUES (?, 'PROCESSING', ?, ?, 'Alice', 'Alice approved')", action.toString(), status, time.plusSeconds(4).toString()) + insert("INSERT INTO invitecode_reward_delivery_transitions(delivery_id, previous_status, current_status, occurred_at, actor, reason) VALUES (?, 'PROCESSING', ?, ?, 'Alice', 'Alice approved')", delivery.toString(), status, time.plusSeconds(4).toString()) + insert("INSERT INTO invitecode_player_login_days(player_id, login_date) VALUES (?, '2026-01-01')", player.toString()) + insert("INSERT INTO invitecode_player_network_hashes(player_id, key_id, network_hash, observed_at, expires_at) VALUES (?, ?, ?, ?, ?)", player.toString(), key.keyId, "c".repeat(64), time.toString(), time.plusSeconds(60).toString()) + insert("INSERT INTO invitecode_audit_records(audit_id, action, actor, reason, occurred_at, player_id, details_kind) VALUES (?, 'ELIGIBILITY_RESET', 'Alice', ?, ?, ?, 'NONE')", UUID.randomUUID().toString(), "Request by $player", time.toString(), player.toString()) + } + return Fixture(player, invitation, fact) + } +} diff --git a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt index ae476c6..7636e98 100644 --- a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt +++ b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt @@ -322,7 +322,7 @@ class MysqlIntegrationTest { } } -private fun withMysqlSchema(test: (MysqlConfiguration, HikariDataSource) -> Unit) { +internal fun withMysqlSchema(test: (MysqlConfiguration, HikariDataSource) -> Unit) { val host = System.getenv("INVITECODE_TEST_MYSQL_HOST") assumeTrue(!host.isNullOrBlank(), "MySQL integration requires explicit test server environment variables.") val port = System.getenv("INVITECODE_TEST_MYSQL_PORT")?.toIntOrNull() ?: 3306 diff --git a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/OfflinePlayerAnonymizerTest.kt b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/OfflinePlayerAnonymizerTest.kt index 8293fa6..80035cd 100644 --- a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/OfflinePlayerAnonymizerTest.kt +++ b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/OfflinePlayerAnonymizerTest.kt @@ -15,6 +15,11 @@ import java.nio.file.Path import java.security.MessageDigest import java.sql.Connection import java.util.UUID +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.ValueSource +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit class OfflinePlayerAnonymizerTest { @TempDir lateinit var directory: Path @@ -77,20 +82,122 @@ class OfflinePlayerAnonymizerTest { } } - @Test - fun `unresolved reward fails before any identity mutation`() { + @ParameterizedTest + @ValueSource(strings = ["PENDING", "PROCESSING", "UNCERTAIN"]) + fun `unresolved reward fails before any identity mutation`(status: String) { val database = directory.resolve("unresolved.db") SqliteSchemaMigrator(database, guard).migrate() val inviter = UUID.randomUUID() val invitee = UUID.randomUUID() val invitation = UUID.randomUUID() - seed(database, inviter, invitee, invitation, UUID.randomUUID(), UUID.randomUUID(), "PENDING") + seed(database, inviter, invitee, invitation, UUID.randomUUID(), UUID.randomUUID(), status) + val before = snapshot(database) SqliteInviteCodeStorage.open(database, guard, key).use { storage -> assertThrows(IllegalStateException::class.java) { storage.anonymizePlayer(inviter) } assertNotNull(storage.player(inviter)) assertFalse(storage.isInviteCodeReserved(InviteCode.fromNormalized("FFFFFF"))) assertNotNull(storage.activeInviteCode(InviteCode.fromNormalized("A1B2C3"))) } + assertEquals(before, snapshot(database)) + } + + @Test + fun `anonymized history remains private and linked after reopening`() { + val database = directory.resolve("restart.db") + SqliteSchemaMigrator(database, guard).migrate() + val inviter = UUID.randomUUID() + val invitee = UUID.randomUUID() + val invitation = UUID.randomUUID() + seed(database, inviter, invitee, invitation, UUID.randomUUID(), UUID.randomUUID(), "DELIVERED") + val fact = io.github.command1264.invitecode.core.QualificationFact( + UUID.randomUUID(), invitation, "policy", "revision", "condition", + io.github.command1264.invitecode.core.QualificationFactOutcome.SATISFIED, + Instant.parse("2026-01-03T00:00:00Z"), + ) + val historical = SqliteInviteCodeStorage.open(database, guard, key).use { storage -> + storage.saveQualifiedInvitation(requireNotNull(storage.invitation(invitation)).qualify(fact.recordedAt, fact.policyId, fact.qualificationRevision), listOf(fact)) + storage.anonymizePlayer(inviter).historicalId + } + SqliteInviteCodeStorage.open(database, guard, key).use { storage -> + assertNull(storage.player(inviter)) + assertEquals(historical, storage.invitation(invitation)?.inviterId) + assertEquals(Instant.parse("2026-01-02T00:00:00Z"), storage.invitation(invitation)?.claimedAt) + assertEquals(fact.recordedAt, storage.invitation(invitation)?.qualifiedAt) + assertEquals(fact.id, storage.qualificationFacts(invitation).single().id) + assertEquals(fact.recordedAt, storage.qualificationFacts(invitation).single().recordedAt) + assertNull(storage.player(historical)?.lastKnownName) + assertTrue(storage.isInviteCodeReserved(InviteCode.fromNormalized("A1B2C3"))) + assertTrue(storage.pendingRewardActions(historical).isEmpty()) + assertTrue(storage.auditHistoryByPlayer(historical, 10).any { it.action.name == "PLAYER_ANONYMIZED" }) + } + val exported = snapshot(database).toString() + assertFalse(exported.contains(inviter.toString())) + assertFalse(exported.contains("Alice")) + assertFalse(exported.contains("A1B2C3")) + } + + @Test + fun `write failure rolls back identity history and code reservation`() { + val database = directory.resolve("failed.db") + SqliteSchemaMigrator(database, guard).migrate() + val inviter = UUID.randomUUID() + seed(database, inviter, UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), "DELIVERED") + connect(database).use { connection -> + connection.createStatement().use { it.execute("CREATE TRIGGER fail_anonymization BEFORE DELETE ON invitecode_players BEGIN SELECT RAISE(ABORT, 'injected anonymization failure'); END") } + } + val before = snapshot(database) + SqliteInviteCodeStorage.open(database, guard, key).use { storage -> + val failure = assertThrows(SqliteStorageException::class.java) { storage.anonymizePlayer(inviter) } + assertTrue(generateSequence(failure) { it.cause }.any { + it.message.orEmpty().contains("injected anonymization failure") + }) + } + assertEquals(before, snapshot(database)) + connect(database).use { it.createStatement().use { statement -> statement.execute("DROP TRIGGER fail_anonymization") } } + SqliteInviteCodeStorage.open(database, guard, key).use { storage -> + storage.anonymizePlayer(inviter) + assertNull(storage.player(inviter)) + } + } + + @Test + fun `two SQLite maintenance connections cannot anonymize a player twice`() { + val database = directory.resolve("parallel.db") + SqliteSchemaMigrator(database, guard).migrate() + val inviter = UUID.randomUUID() + seed(database, inviter, UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), "DELIVERED") + val start = CountDownLatch(1) + val ready = CountDownLatch(2) + val executor = Executors.newFixedThreadPool(2) + try { + val attempts = (1..2).map { + executor.submit { + SqliteInviteCodeStorage.open(database, guard, key).use { storage -> + ready.countDown() + check(start.await(10, TimeUnit.SECONDS)) + try { storage.anonymizePlayer(inviter); true } catch (failure: IllegalStateException) { + assertTrue(failure.message.orEmpty().contains("absent"), failure.message) + false + } + } + } + } + assertTrue(ready.await(10, TimeUnit.SECONDS)) + start.countDown() + assertEquals(1, attempts.count { it.get(20, TimeUnit.SECONDS) }) + SqliteInviteCodeStorage.open(database, guard, key).use { storage -> + assertNull(storage.player(inviter)) + assertTrue(storage.isInviteCodeReserved(InviteCode.fromNormalized("A1B2C3"))) + } + } finally { + start.countDown() + executor.shutdownNow() + assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)) + } + } + + private fun snapshot(database: Path): PortableStorageSnapshot = connect(database).use { + OfflineStorageTransfer.export(it, StorageDialect.SQLITE, key.keyId) } @Test